<commit_before>import _ from 'lodash';
import Promise from 'bluebird';
import AppDispatcher from '../dispatchers/app-dispatcher';
import ProductConstants from '../constants/product-constants';
import { products, user } from '../lib/sprintly-client';
import FiltersAction from '../actions/filter-actions';
import {PUSHER_KEY, CHANNEL_PREFIX} from '../config';

var ProductStore = module.exports = {
  getAll: function() {
    let activeProducts = products.where({ archived: false });
    return _.sortBy(_.invoke(activeProducts, 'toJSON'), 'name');
  },
  getSortCriteria: function(collection) {
    let orderBy = collection.config.get('order_by');
    let direction;
    let field = orderBy;

    switch(orderBy) {
      case 'stale':
        field = 'last_modified';
        direction = 'asc';
        break;
      case 'recent':
        field = 'last_modified';
        direction = 'desc';
        break;
      case 'oldest':
        field = 'created_at';
        direction = 'asc';
        break;
      case 'newest':
        field = 'created_at'
        direction = 'desc';
        break;
      case 'priority':
        direction = 'asc';
        break;
      default:
        break;
    }

    return [field, direction]
  },
  getItemsForProduct: function(product, status, filters) {
    var items = product.getItemsByStatus(status);
    // Set "Recent" as the default sort
    if (items.config.get('order_by')) {
      items.config.set('order_by', 'recent');
    }
    var updatedFilters = internals.mergeFilters(items.config, filters);

    // Set additional defaults for fetching products
    updatedFilters.limit = 25;
    updatedFilters.children = true;
    updatedFilters.offset = 0;

    if(status === 'accepted') {
      updatedFilters.limit = 5;
    }

    items.config.set(updatedFilters);
    return items;
  },
  getMembers: function(product) {
    return product.members.toJSON();
  }
};

var proxyMethods = ['trigger', 'get', 'on', 'off', 'once', 'listenTo', 'stopListening']

proxyMethods.forEach(function(method) {
  ProductStore[method] = products[method].bind(products);
});

var internals = ProductStore.internals = {
  initProducts(productId) {
    var dependencies;
    if (products.length > 0 && user.id) {
      dependencies = [true];
    } else {
      dependencies = [
        user.fetch(),
        products.fetch({ silent: true })
      ]
    }

    return Promise.all(dependencies).then(() => {
      if (!productId) {
        products.trigger('change');
        return;
      }
      var product = products.get(productId);
      FiltersAction.init(product, user);
      internals.createSubscription(product);
      products.trigger('change');
      return product;
    });
  },

  loadMoreItems(coll) {
    var currentOffset = coll.config.get('offset');
    var newOffset = coll.config.get('status') === 'accepted' ? currentOffset + 5 :
      currentOffset + 25;

    coll.config.set({ offset: newOffset });
    coll.fetch({ silent:true, remove:false}).then((res) => {
      coll.trigger('change', { count: res.length });
    });
  },

  changeSortCriteria: function(collection, field, direction) {
    internals.setComparator(collection, field, direction);

    if (field === 'last_modified') {
      field = direction === 'asc' ? 'stale' : 'recent';
    }

    if (field === 'created_at') {
      field = direction === 'asc' ? 'oldest' : 'newest';
    }

    collection.config.set({
      order_by: field,
      offset: 0
    });

    collection.fetch({ reset: true, silent: true }).then(function() {
      collection.trigger('change');
    })
  },

  setComparator: function(collection, field, direction) {
    var presenter = (o) => +new Date(o);

    collection.comparator = (model) => {
      let criteria = model.get(field);
      if (field === 'priority') {
        return model.get('sort');
      }
      let value = presenter(criteria)
      return direction === 'desc' ? -value : value;
    };
  },

  ingestItem(product, item_data) {
    var item = product.items.get(item_data.number);
    if (item) {
      // Ignore stale timestamps. By using optimistic timestamps, items stay in
      // the correct positions relative to one another.
      if (item_data.last_modified < item.get('last_modified')) {
        item_data.last_modified = item.get('last_modified');
      }

      item.set(_.omit(item_data, 'number'));
    } else {
      internals.createItem(product, item_data);
    }
  },

  updateItem(productId, itemId, payload) {
    let product = products.get(productId);
    let item = product.items.get(itemId);

    if (payload.status) {
      item.unset('close_reason', { silent: true });

      if (_.contains(['backlog', 'someday'], item.get('status')) &&
          _.contains(['in-progress', 'completed'], payload.status) ) {
        payload.assigned_to = user.id;
      }
    }

    item.save(payload);
  },

  updateItemPriority(productId, itemId, priority) {
    let product = products.get(productId);
    let item = product.items.get(itemId);
    let status = item.get('status');
    let sort = item.get('sort');
    let payload = {};
    let col = product._filters[status].sortBy('sort');
    let index = _.findIndex(col, function(item) {
      return item.get('number') === itemId;
    })

    let previousItems = {
      after: col[index - 2],
      before: col[index - 1]
    };
    let nextItems = {
      after: col[index + 1],
      before: col[index + 2],
    }

    switch(priority) {
      case 'up':
        if (previousItems.before) {
          payload[!previousItems.after ? 'after' : 'before'] = previousItems.before.get('number');
        }
        if (previousItems.after) {
          payload.after = previousItems.after.get('number');
        }
        break;
      case 'down':
        if (nextItems.before) {
          payload.before = nextItems.before.get('number');
        }
        if (nextItems.after) {
          payload[!nextItems.before ? 'before' : 'after'] = nextItems.after.get('number');
        }
        break;
      case 'top':
        let topItem = _.first(col);
        payload.after = topItem.get('number');
        break;
      case 'bottom':
        let bottomItem = _.last(col);
        payload.before = bottomItem.get('number');
        break;
      default:
        throw new Error('Invalid priority direction: '+ priority);
        break;
    }

    item.resort(payload);
  },

  createItem(product, item_data) {
    let item = product.createItem(item_data);
    let collection = product.getItemsByStatus(item.get('status'))
    if (collection) {
      collection.add(item);
    }
  },

  getUpdatedTimestamps(model, status) {
    // Set the timestamp affected by the status change. This is happening
    // "now" so setting this optimistically to the current timestamp makes
    // items stay in the correct relative positions. This will get reset by
    // any filter change that triggers a reset.
    let attrs = {
      last_modified: +new Date()
    };
    let progress = model.get('progress');

    if (progress) {
      if (status === 'in-progress') {
        progress.started_at = +new Date();
      } else if (status === 'completed') {
        progress.closed_at = +new Date();
      } else if (status === 'accepted') {
        progress.accepted_at = +new Date();
      }
      attrs.progress = progress;
    }

    return attrs
  },

  matchesFilter(item, filter) {
    let fields = ['tags', 'assigned_to', 'created_by', 'estimate', 'type'];
    let activeFilters = 0;
    let matchingFilters = _.filter(fields, function(field) {
      let criteria = filter[field];
      if (criteria) {
        activeFilters++;
        if (_.isArray(criteria)) {
          if (_.isArray(item.get(field))) {
            return _.intersection(criteria, item.get(field)).length > 0;
          } else {
            return _.contains(criteria, item.get(field))
          }
        } else {
          if (field === 'assigned_to' || field === 'created_by') {
            return item.get(field).id === criteria;
          } else {
            return item.get(field) === criteria;
          }
        }
      } else {
        return false;
      }
    });

    return [activeFilters, matchingFilters];
  },

  createSubscription(product) {
    product.items.on('change:status', function(model) {
      let status = model.get('status');
      let collection = product._filters[status];
      let config = collection.config.toJSON();
      // Prevent "jumpy" items
      model.set(internals.getUpdatedTimestamps(model, status), { silent: true });

      let [activeFilterCount, matchingFilters] = internals.matchesFilter(model, config);
      if (activeFilterCount === matchingFilters.length) {
        // Swap items between status collections.
        let previousStatus = model.previous('status');
        let previousCollection = product._filters[previousStatus];
        previousCollection.remove(model);
        collection.add(model);
      }
    });

    var channelName = `${CHANNEL_PREFIX}_${product.id}`;
    var options = {
      encrypted: false,
      auth: {
        params: {
          product: product.id
        }
      }
    };

    var socket = new window.Pusher(PUSHER_KEY, options);
    var productChannel = socket.subscribe(channelName);

    productChannel.bind('changed', function(msg) {
      let model = msg['class'];

      switch(model) {
        case 'Item':
          internals.ingestItem(product, msg.data);
          break
      }
    });

    productChannel.bind('deleted', function(data) {
      console.log(data);
    });
  },

  mergeFilters(configModel, filters) {
    var defaultFilters = configModel.toJSON();
    var updatedFilters = _.extend(defaultFilters, filters);

    // unset previously-set global filters
    _.each(['tags', 'assigned_to', 'created_by', 'estimate', 'members'], function(field) {
      if (_.has(filters, field) === false && _.has(updatedFilters, field)) {
        configModel.unset(field, { silent: true });
        delete updatedFilters[field];
      }
    });

    if (updatedFilters.assigned_to === 'unassigned') {
      updatedFilters.assigned_to = '';
    }
    return updatedFilters;
  }
};

ProductStore.dispatchToken = AppDispatcher.register(function(action) {

  switch(action.actionType) {
    case ProductConstants.INIT_PRODUCTS:
      internals.initProducts(action.productId);
      break;

    case ProductConstants.CHANGE_SORT_CRITERIA:
      internals.changeSortCriteria(action.itemCollection, action.sortField, action.sortDirection);
      break;

    case ProductConstants.GET_ITEMS:
      internals.setComparator(action.itemCollection, action.sortField, action.sortDirection);
      action.itemCollection.fetch({ reset: true });
      break;

    case ProductConstants.LOAD_MORE:
      internals.loadMoreItems(action.itemCollection);
      break;

    case ProductConstants.SUBSCRIBE:
      internals.createSubscription(action.id);
      break;

    case ProductConstants.UPDATE_ITEM_PRIORITY:
      internals.updateItemPriority(action.productId, action.itemId, action.priority);
      break;

    case ProductConstants.UPDATE_ITEM:
      internals.updateItem(action.productId, action.itemId, action.payload);
      break;

    default:
      break;
  }

});
<commit_msg>handle deletes from pusher<commit_after>import _ from 'lodash';
import Promise from 'bluebird';
import AppDispatcher from '../dispatchers/app-dispatcher';
import ProductConstants from '../constants/product-constants';
import { products, user } from '../lib/sprintly-client';
import FiltersAction from '../actions/filter-actions';
import {PUSHER_KEY, CHANNEL_PREFIX} from '../config';

var ProductStore = module.exports = {
  getAll: function() {
    let activeProducts = products.where({ archived: false });
    return _.sortBy(_.invoke(activeProducts, 'toJSON'), 'name');
  },
  getSortCriteria: function(collection) {
    let orderBy = collection.config.get('order_by');
    let direction;
    let field = orderBy;

    switch(orderBy) {
      case 'stale':
        field = 'last_modified';
        direction = 'asc';
        break;
      case 'recent':
        field = 'last_modified';
        direction = 'desc';
        break;
      case 'oldest':
        field = 'created_at';
        direction = 'asc';
        break;
      case 'newest':
        field = 'created_at'
        direction = 'desc';
        break;
      case 'priority':
        direction = 'asc';
        break;
      default:
        break;
    }

    return [field, direction]
  },
  getItemsForProduct: function(product, status, filters) {
    var items = product.getItemsByStatus(status);
    // Set "Recent" as the default sort
    if (items.config.get('order_by')) {
      items.config.set('order_by', 'recent');
    }
    var updatedFilters = internals.mergeFilters(items.config, filters);

    // Set additional defaults for fetching products
    updatedFilters.limit = 25;
    updatedFilters.children = true;
    updatedFilters.offset = 0;

    if(status === 'accepted') {
      updatedFilters.limit = 5;
    }

    items.config.set(updatedFilters);
    return items;
  },
  getMembers: function(product) {
    return product.members.toJSON();
  }
};

var proxyMethods = ['trigger', 'get', 'on', 'off', 'once', 'listenTo', 'stopListening']

proxyMethods.forEach(function(method) {
  ProductStore[method] = products[method].bind(products);
});

var internals = ProductStore.internals = {
  initProducts(productId) {
    var dependencies;
    if (products.length > 0 && user.id) {
      dependencies = [true];
    } else {
      dependencies = [
        user.fetch(),
        products.fetch({ silent: true })
      ]
    }

    return Promise.all(dependencies).then(() => {
      if (!productId) {
        products.trigger('change');
        return;
      }
      var product = products.get(productId);
      FiltersAction.init(product, user);
      internals.createSubscription(product);
      products.trigger('change');
      return product;
    });
  },

  loadMoreItems(coll) {
    var currentOffset = coll.config.get('offset');
    var newOffset = coll.config.get('status') === 'accepted' ? currentOffset + 5 :
      currentOffset + 25;

    coll.config.set({ offset: newOffset });
    coll.fetch({ silent:true, remove:false}).then((res) => {
      coll.trigger('change', { count: res.length });
    });
  },

  changeSortCriteria: function(collection, field, direction) {
    internals.setComparator(collection, field, direction);

    if (field === 'last_modified') {
      field = direction === 'asc' ? 'stale' : 'recent';
    }

    if (field === 'created_at') {
      field = direction === 'asc' ? 'oldest' : 'newest';
    }

    collection.config.set({
      order_by: field,
      offset: 0
    });

    collection.fetch({ reset: true, silent: true }).then(function() {
      collection.trigger('change');
    })
  },

  setComparator: function(collection, field, direction) {
    var presenter = (o) => +new Date(o);

    collection.comparator = (model) => {
      let criteria = model.get(field);
      if (field === 'priority') {
        return model.get('sort');
      }
      let value = presenter(criteria)
      return direction === 'desc' ? -value : value;
    };
  },

  ingestItem(product, item_data) {
    var item = product.items.get(item_data.number);
    if (item) {
      // Ignore stale timestamps. By using optimistic timestamps, items stay in
      // the correct positions relative to one another.
      if (item_data.last_modified < item.get('last_modified')) {
        item_data.last_modified = item.get('last_modified');
      }

      item.set(_.omit(item_data, 'number'));
    } else {
      internals.createItem(product, item_data);
    }
  },

  updateItem(productId, itemId, payload) {
    let product = products.get(productId);
    let item = product.items.get(itemId);

    if (payload.status) {
      item.unset('close_reason', { silent: true });

      if (_.contains(['backlog', 'someday'], item.get('status')) &&
          _.contains(['in-progress', 'completed'], payload.status) ) {
        payload.assigned_to = user.id;
      }
    }

    item.save(payload);
  },

  updateItemPriority(productId, itemId, priority) {
    let product = products.get(productId);
    let item = product.items.get(itemId);
    let status = item.get('status');
    let sort = item.get('sort');
    let payload = {};
    let col = product._filters[status].sortBy('sort');
    let index = _.findIndex(col, function(item) {
      return item.get('number') === itemId;
    })

    let previousItems = {
      after: col[index - 2],
      before: col[index - 1]
    };
    let nextItems = {
      after: col[index + 1],
      before: col[index + 2],
    }

    switch(priority) {
      case 'up':
        if (previousItems.before) {
          payload[!previousItems.after ? 'after' : 'before'] = previousItems.before.get('number');
        }
        if (previousItems.after) {
          payload.after = previousItems.after.get('number');
        }
        break;
      case 'down':
        if (nextItems.before) {
          payload.before = nextItems.before.get('number');
        }
        if (nextItems.after) {
          payload[!nextItems.before ? 'before' : 'after'] = nextItems.after.get('number');
        }
        break;
      case 'top':
        let topItem = _.first(col);
        payload.after = topItem.get('number');
        break;
      case 'bottom':
        let bottomItem = _.last(col);
        payload.before = bottomItem.get('number');
        break;
      default:
        throw new Error('Invalid priority direction: '+ priority);
        break;
    }

    item.resort(payload);
  },

  createItem(product, item_data) {
    let item = product.createItem(item_data);
    let collection = product.getItemsByStatus(item.get('status'))
    if (collection) {
      collection.add(item);
    }
  },

  getUpdatedTimestamps(model, status) {
    // Set the timestamp affected by the status change. This is happening
    // "now" so setting this optimistically to the current timestamp makes
    // items stay in the correct relative positions. This will get reset by
    // any filter change that triggers a reset.
    let attrs = {
      last_modified: +new Date()
    };
    let progress = model.get('progress');

    if (progress) {
      if (status === 'in-progress') {
        progress.started_at = +new Date();
      } else if (status === 'completed') {
        progress.closed_at = +new Date();
      } else if (status === 'accepted') {
        progress.accepted_at = +new Date();
      }
      attrs.progress = progress;
    }

    return attrs
  },

  matchesFilter(item, filter) {
    let fields = ['tags', 'assigned_to', 'created_by', 'estimate', 'type'];
    let activeFilters = 0;
    let matchingFilters = _.filter(fields, function(field) {
      let criteria = filter[field];
      if (criteria) {
        activeFilters++;
        if (_.isArray(criteria)) {
          if (_.isArray(item.get(field))) {
            return _.intersection(criteria, item.get(field)).length > 0;
          } else {
            return _.contains(criteria, item.get(field))
          }
        } else {
          if (field === 'assigned_to' || field === 'created_by') {
            return item.get(field).id === criteria;
          } else {
            return item.get(field) === criteria;
          }
        }
      } else {
        return false;
      }
    });

    return [activeFilters, matchingFilters];
  },

  deleteItem(product, item_data) {
    product.items.remove(item_data.number);
    let col = product._filters[item_data.status];
    if (col) {
      col.remove(item_data.number);
    }
  },

  createSubscription(product) {
    product.items.on('change:status', function(model) {
      let status = model.get('status');
      let collection = product._filters[status];
      let config = collection.config.toJSON();
      // Prevent "jumpy" items
      model.set(internals.getUpdatedTimestamps(model, status), { silent: true });

      let [activeFilterCount, matchingFilters] = internals.matchesFilter(model, config);
      if (activeFilterCount === matchingFilters.length) {
        // Swap items between status collections.
        let previousStatus = model.previous('status');
        let previousCollection = product._filters[previousStatus];
        previousCollection.remove(model);
        collection.add(model);
      }
    });

    var channelName = `${CHANNEL_PREFIX}_${product.id}`;
    var options = {
      encrypted: false,
      auth: {
        params: {
          product: product.id
        }
      }
    };

    var socket = new window.Pusher(PUSHER_KEY, options);
    var productChannel = socket.subscribe(channelName);

    productChannel.bind('changed', function(msg) {
      let model = msg['class'];

      switch(model) {
        case 'Item':
          internals.ingestItem(product, msg.data);
          break;
        default:
          break;
      }
    });

    productChannel.bind('deleted', function(msg) {
      let model = msg['class'];

      switch(model) {
        case 'Item':
          internals.deleteItem(product, msg.data)
          break;
        default:
          break;
      }
    });
  },

  mergeFilters(configModel, filters) {
    var defaultFilters = configModel.toJSON();
    var updatedFilters = _.extend(defaultFilters, filters);

    // unset previously-set global filters
    _.each(['tags', 'assigned_to', 'created_by', 'estimate', 'members'], function(field) {
      if (_.has(filters, field) === false && _.has(updatedFilters, field)) {
        configModel.unset(field, { silent: true });
        delete updatedFilters[field];
      }
    });

    if (updatedFilters.assigned_to === 'unassigned') {
      updatedFilters.assigned_to = '';
    }
    return updatedFilters;
  }
};

ProductStore.dispatchToken = AppDispatcher.register(function(action) {

  switch(action.actionType) {
    case ProductConstants.INIT_PRODUCTS:
      internals.initProducts(action.productId);
      break;

    case ProductConstants.CHANGE_SORT_CRITERIA:
      internals.changeSortCriteria(action.itemCollection, action.sortField, action.sortDirection);
      break;

    case ProductConstants.GET_ITEMS:
      internals.setComparator(action.itemCollection, action.sortField, action.sortDirection);
      action.itemCollection.fetch({ reset: true });
      break;

    case ProductConstants.LOAD_MORE:
      internals.loadMoreItems(action.itemCollection);
      break;

    case ProductConstants.SUBSCRIBE:
      internals.createSubscription(action.id);
      break;

    case ProductConstants.UPDATE_ITEM_PRIORITY:
      internals.updateItemPriority(action.productId, action.itemId, action.priority);
      break;

    case ProductConstants.UPDATE_ITEM:
      internals.updateItem(action.productId, action.itemId, action.payload);
      break;

    default:
      break;
  }

});
<|endoftext|>


<commit_before>import * as React from 'react';
import { connect } from 'react-redux';
import { Container, Button, Grid, Header } from 'semantic-ui-react'
import { actionCreators } from '../store';

import CodePanel from './CodePanel';
import ScorePanel from './ScorePanel';
import AttemptList from './AttemptList';
import HighScoreList from './HighScoreList';
class Game extends React.Component {
    constructor(props) {
        super(props);
    }
    handleCodeEnter = (code) => {
        this.props.enterCode(code);
    }
    handleStartGame = () => {
        this.props.startGame();
    }
    handleRegisterScore = name => {
        this.props.registerScore(name);
    }
    componentDidMount() {
        this.props.loadScores();
    }
    render() {
        let startView = (<Container>
            Welcome to Code Breaker
            <Button onClick={this.handleStartGame}>Start Game</Button>
            <HighScoreList scores={this.props.scores} />
        </Container>);
        let gameView = (<Container>
            <CodePanel onCodeEnter={this.handleCodeEnter} digits={this.props.options.digits} minValue={this.props.options.minValue} maxValue={this.props.options.maxValue} />
            <AttemptList attempts={this.props.attempts} />
        </Container>);
        let finishedGame = (<Container>
            {this.props.isScoreRegistered ? Welcome to Code Breaker : <ScorePanel score={this.props.score} registerScore={this.handleRegisterScore} />}
            <Button onClick={this.handleStartGame}>Start Game</Button>
        </Container>);
        return (<Grid>
            <Grid.Row />
            <Grid.Row>
                <Grid.Column width="5" />
                <Grid.Column width="6">
                    {this.props.id ? (this.props.score ? finishedGame : gameView) : startView}
                </Grid.Column>
                <Grid.Column width="5" />
            </Grid.Row>
        </Grid>);
    }
}

export default connect((state) => state.game, actionCreators.game)(Game);
<commit_msg>Reset demo<commit_after>import * as React from 'react';
import { connect } from 'react-redux';
import { Container, Button, Grid, Header } from 'semantic-ui-react'
import { actionCreators } from '../store';

import CodePanel from './CodePanel';
import ScorePanel from './ScorePanel';
import AttemptList from './AttemptList';
import HighScoreList from './HighScoreList';
class Game extends React.Component {
    constructor(props) {
        super(props);
    }
    handleCodeEnter = (code) => {
        this.props.enterCode(code);
    }
    handleStartGame = () => {
        this.props.startGame();
    }
    handleRegisterScore = name => {
        this.props.registerScore(name);
    }
    componentDidMount() {
        //this.props.loadScores();
    }
    render() {
        let startView = (<Container>
            Welcome to Code Breaker
            <Button onClick={this.handleStartGame}>Start Game</Button>
            <HighScoreList scores={this.props.scores} />
        </Container>);
        let gameView = (<Container>
            <CodePanel onCodeEnter={this.handleCodeEnter} digits={this.props.options.digits} minValue={this.props.options.minValue} maxValue={this.props.options.maxValue} />
            <AttemptList attempts={this.props.attempts} />
        </Container>);
        let finishedGame = (<Container>
            {this.props.isScoreRegistered ? Welcome to Code Breaker : <ScorePanel score={this.props.score} registerScore={this.handleRegisterScore} />}
            <Button onClick={this.handleStartGame}>Start Game</Button>
        </Container>);
        return (<Grid>
            <Grid.Row />
            <Grid.Row>
                <Grid.Column width="5" />
                <Grid.Column width="6">
                    {this.props.id ? (this.props.score ? finishedGame : gameView) : startView}
                </Grid.Column>
                <Grid.Column width="5" />
            </Grid.Row>
        </Grid>);
    }
}

export default connect((state) => state.game, actionCreators.game)(Game);
<|endoftext|>


<commit_before>;(function () {

    // This file contains the code to define the graphics and then
    // renders them using data randomly generated by data.js.

    var data = gg.sampleData;
    var div  = d3.select('#examples');
    var opts = { width: 300, height: 200, padding: 35 };

    // Define graphics ...

    function g (spec) { return gg(spec).renderer(div, opts); }

    var linechart = g({
        layers: [
            { geometry: 'line', mapping: { x: 'd', y: 'r', group: 'subject', color: 'subject'} },
            { geometry: 'text', mapping: { x: 'd', y: 'r', }, text: '{d}, {r}', show: 'hover' }
        ],
        scales: [
            { aesthetic: 'color', range: ['#CFF09E', '#A8DBA8', '#79BD9A', '#3B8686'] }
        ]
    });

    var combined = g({
        layers: [
            { geometry: 'point', mapping: { x: 'd', y: 'r' }, size: 3 },
            { geometry: 'line', mapping: { x: 'd', y: 'r' } }
            //{ geometry: 'interval', mapping: { x: 'd', y: 'r' }, width: 2 },
        ]
    });

    var barchart = g({
        layers: [{ geometry: 'interval', mapping: { x: 'd', y: 'r' }, color: 'blue', width: 2 }],
        scales: [{ aesthetic: 'y', min: 0 }]
    });

    var quadrants = g({
        layers: [
            {
                geometry: 'point',
                mapping: { x: 'x', y: 'y', size: 'size' }
            },
            { geometry: 'text', mapping: { x: 'x', y: 'y' }, text: '{name}: {size}',  show: 'hover' }
        ],
        scales: [ { aesthetic: 'size', range: [ 1, 5 ]} ]
    });

    var histogram = g({
        layers: [{
            geometry: 'interval',
            mapping: { x: 'group', y: 'count', color: 'group' },
            width: 20,
            statistic: { kind: 'sum', group: 'who', variable: 'purchases' }
        }],
        scales: [
            { type: 'categorical', aesthetic: 'x' },
            { aesthetic: 'y', min: 0 }
        ]
    });

    var semilog = g({
        layers: [
            { geometry: 'point', mapping: { x: 'd', y: 'r' }, size: 3 },
            { geometry: 'line', mapping: { x: 'd', y: 'r' } }
        ],
        scales: [ { type: 'log', aesthetic: 'y', legend: 'whatever' },
                  { aesthetic: 'x', legend: 'foo' } ]
    });

    var heightHistogram = g({
        layers: [
            {
                geometry: 'interval',
                mapping: { x: 'bin', y: 'count' },
                statistic: { kind: 'bin', variable: 'height', bins: 30 }
            }
        ],
        scales: [
            { type: 'categorical', aesthetic: 'x' },
            { aesthetic: 'y', min: 0 }
        ]
    });

    var twoPopulations = g({
        name: 'twoPopulations',
        layers: [ {
            geometry: 'point',
            mapping: { x: 'intelligence', y: 'wisdom', color: 'group' },
        }]
    });

    var boxplot = g({
        layers: [ {
            geometry: 'box',
            mapping: { x: 'group', y: false },
            statistic: { kind: 'box', group: 'grade', variable: 'value' }
        }],
        scales: [
            { type: 'categorical', aesthetic: 'x' }
        ]
    });

    var symmetric = g({
        layers: [ { geometry: 'line', mapping: { x: 'd', y: 'r' } }, ],
        scales: [ { aesthetic: 'y', center: 0 } ]
    });

    var areachartSmooth = g({
        layers: [ { geometry: 'area', mapping: { x: 'a', y: false, y0: 'top', y1: 'bottom' }, smooth: true } ]
    });

    var areachart = g({ layers: [ { geometry: 'area', mapping: { x: 'a', y: false, y0: 'top', y1: 'bottom' } } ] });

    // ... and render 'em

    linechart(data.upwardSubjects);
    combined(data.upward);
    barchart(_.map(data.upward, function (d) { return { d: d.d, r: Math.max(d.r, 0) }; }));
    quadrants(data.quadrants);
    histogram(data.purchases);
    semilog(data.semiLogData);
    heightHistogram(data.heightWeight);
    twoPopulations(data.twoPopulations);
    boxplot(data.forBoxPlots);
    symmetric(data.toBeCentered);
    areachartSmooth(data.upwardPairs);
    areachart(data.upwardPairs);

})();
<commit_msg>Cleaning up examples.js a bit.<commit_after>;(function () {

    // This file contains the code to define the graphics and then
    // renders them using data randomly generated by data.js.

    var data = gg.sampleData;
    var div  = d3.select('#examples');
    var opts = { width: 300, height: 200, padding: 35 };

    // Define graphics ...

    function g (spec) { return gg(spec).renderer(div, opts); }

    var linechart = g({
        layers: [
            { geometry: 'line', mapping: { x: 'd', y: 'r', group: 'subject', color: 'subject'} },
            { geometry: 'text', mapping: { x: 'd', y: 'r', }, text: '{d}, {r}', show: 'hover' }
        ],
        scales: [
            { aesthetic: 'color', range: ['#CFF09E', '#A8DBA8', '#79BD9A', '#3B8686'] }
        ]
    });

    var combined = g({
        layers: [
            { geometry: 'point', mapping: { x: 'd', y: 'r' }, size: 3 },
            { geometry: 'line', mapping: { x: 'd', y: 'r' } }
            //{ geometry: 'interval', mapping: { x: 'd', y: 'r' }, width: 2 },
        ]
    });

    var barchart = g({
        layers: [{ geometry: 'interval', mapping: { x: 'd', y: 'r' }, color: 'blue', width: 2 }],
        scales: [{ aesthetic: 'y', min: 0 }]
    });

    var quadrants = g({
        layers: [
            {
                geometry: 'point',
                mapping: { x: 'x', y: 'y', size: 'size' }
            },
            { geometry: 'text', mapping: { x: 'x', y: 'y' }, text: '{name}: {size}',  show: 'hover' }
        ],
        scales: [ { aesthetic: 'size', range: [ 1, 5 ]} ]
    });

    var histogram = g({
        layers: [{
            geometry: 'interval',
            mapping: { x: 'group', y: 'count', color: 'group' },
            width: 20,
            statistic: { kind: 'sum', group: 'who', variable: 'purchases' }
        }],
        scales: [
            { aesthetic: 'x', type: 'categorical' },
            { aesthetic: 'y', min: 0 }
        ]
    });

    var semilog = g({
        layers: [
            { geometry: 'point', mapping: { x: 'd', y: 'r' }, size: 3 },
            { geometry: 'line', mapping: { x: 'd', y: 'r' } }
        ],
        scales: [
            { aesthetic: 'y', type: 'log', legend: 'whatever' },
            { aesthetic: 'x', legend: 'foo' }
        ]
    });

    var heightHistogram = g({
        layers: [{
            geometry: 'interval',
            mapping: { x: 'bin', y: 'count' },
            statistic: { kind: 'bin', variable: 'height', bins: 30 }
        }],
        scales: [
            { aesthetic: 'x', type: 'categorical' },
            { aesthetic: 'y', min: 0 }
        ]
    });

    var twoPopulations = g({
        name: 'twoPopulations',
        layers: [ {
            geometry: 'point',
            mapping: { x: 'intelligence', y: 'wisdom', color: 'group' },
        }]
    });

    var boxplot = g({
        layers: [ {
            geometry: 'box',
            mapping: { x: 'group', y: false },
            statistic: { kind: 'box', group: 'grade', variable: 'value' }
        }],
        scales: [
            { aesthetic: 'x', type: 'categorical' }
        ]
    });

    var symmetric = g({
        layers: [ { geometry: 'line', mapping: { x: 'd', y: 'r' } }, ],
        scales: [ { aesthetic: 'y', center: 0 } ]
    });

    var areachartSmooth = g({
        layers: [ { geometry: 'area', mapping: { x: 'a', y: false, y0: 'top', y1: 'bottom' }, smooth: true } ]
    });

    var areachart = g({ layers: [ { geometry: 'area', mapping: { x: 'a', y: false, y0: 'top', y1: 'bottom' } } ] });

    // ... and render 'em

    linechart(data.upwardSubjects);
    combined(data.upward);
    barchart(_.map(data.upward, function (d) { return { d: d.d, r: Math.max(d.r, 0) }; }));
    quadrants(data.quadrants);
    histogram(data.purchases);
    semilog(data.semiLogData);
    heightHistogram(data.heightWeight);
    twoPopulations(data.twoPopulations);
    boxplot(data.forBoxPlots);
    symmetric(data.toBeCentered);
    areachartSmooth(data.upwardPairs);
    areachart(data.upwardPairs);

})();
<|endoftext|>


<commit_before>// Module imports

var fs = require('fs');

var mineflayer = require('mineflayer');
var navigatePlugin = require('mineflayer-navigate')(mineflayer);

var generate_name = require('./lib/name')
var name = generate_name();
var bot = mineflayer.createBot({
    username: name,
    host: '192.9.206.136',
});

navigatePlugin(bot);

function faraway() {
    var xrange = 500;
    var yrange = 64;
    var zrange = 500;

    var pos = bot.entity.position.offset(
            (Math.random() - 0.5) * xrange,
            (Math.random() - 0.5) * yrange,
            (Math.random() - 0.5) * zrange);
    return pos.floor();
}

function wander() {
    var sensible_goals = false;
    var count = 0;
    var timeout = 500;
    while (!sensible_goals) {
        var destination = faraway();
        count = count + 1;
        var answer = bot.navigate.findPathSync(destination,
                {'timeout': timeout});
        if (answer['status'] == 'success' || answer['status'] == 'tooFar') {
            sensible_goals = true;
        }
    }
    console.log("Tried " + count + " paths. Going to " + destination);
    bot.navigate.to(faraway(), {'timeout':timeout});
}

bot.on("spawn", function() {
    console.log(name + " spawned.");
    wander();
});

bot.navigate.on('cannotFind', function(path) {
    console.log("Cannot find path.");
    var nearest = path[path.length - 1];
    console.log("Nearest is: " + nearest);
    bot.navigate.to(nearest);
});

bot.navigate.on('arrived', function() {
    console.log("Arrived!");
    wander();
});

bot.navigate.on('interrupted', function() {
    console.log("Interrupted!");
    wander();
});
<commit_msg>Command line arguments for host/port<commit_after>// Module imports

var fs = require('fs');

var mineflayer = require('mineflayer');
var navigatePlugin = require('mineflayer-navigate')(mineflayer);

var generate_name = require('./lib/name')
var name = generate_name();
var bot = mineflayer.createBot({
    username: name,
    host: process.argv[2],
    port: process.argv[3]
});

navigatePlugin(bot);

function faraway() {
    var xrange = 500;
    var yrange = 64;
    var zrange = 500;

    var pos = bot.entity.position.offset(
            (Math.random() - 0.5) * xrange,
            (Math.random() - 0.5) * yrange,
            (Math.random() - 0.5) * zrange);
    return pos.floor();
}

function wander() {
    var sensible_goals = false;
    var count = 0;
    var timeout = 500;
    while (!sensible_goals) {
        var destination = faraway();
        count = count + 1;
        var answer = bot.navigate.findPathSync(destination,
                {'timeout': timeout});
        if (answer['status'] == 'success' || answer['status'] == 'tooFar') {
            sensible_goals = true;
        }
    }
    console.log("Tried " + count + " paths. Going to " + destination);
    bot.navigate.to(faraway(), {'timeout':timeout});
}

bot.on("spawn", function() {
    console.log(name + " spawned.");
    wander();
});

bot.navigate.on('cannotFind', function(path) {
    console.log("Cannot find path.");
    var nearest = path[path.length - 1];
    console.log("Nearest is: " + nearest);
    bot.navigate.to(nearest);
});

bot.navigate.on('arrived', function() {
    console.log("Arrived!");
    wander();
});

bot.navigate.on('interrupted', function() {
    console.log("Interrupted!");
    wander();
});
<|endoftext|>


<commit_before>function appendListItem(content) {
  var li = document.createElement('li');
  if (typeof(content) == 'string') {
    li.innerHTML = content;
  } else {
    li.appendChild(content);
  }
  document.querySelector('#passwords').appendChild(li);
}

function fillInPassword() {
  var username = this.querySelector('span').innerHTML;

  getText('http://localhost:3131/pass/' + this.dataset['path'], function(data) {
    chrome.tabs.getSelected(null, function(tab) {
      chrome.tabs.executeScript(tab.id, { code: fillInScript(username, data.trim()) });
    });
  }, null);
}

function fillInScript(username, password) {
  return "var passwordInput = document.querySelector('input[type=password]');" +
    "passwordInput.value = '" + password + "';" +
    "var form = passwordInput.parentElement;" +
    "while (form.tagName != 'FORM') { form = form.parentElement; };" +
    "var usernameInput = form.querySelector('input[type=text]');" +
    "usernameInput.value = '" + username + "';" +
    "form.submit();";
}

function getText(url, success, error) {
  var xhr = new XMLHttpRequest();
  xhr.open('GET', url, true);

  xhr.onreadystatechange = function() {
    if (xhr.readyState == 4) {
      success(xhr.responseText);
    }
  };

  xhr.onerror = error;
  xhr.send();
}

function getJSON(url, success, error) {
  getText(url, function(data) {
    success(JSON.parse(data));
  }, error);
}

document.addEventListener('DOMContentLoaded', function() {
  chrome.tabs.getSelected(null, function(tab) {
    var url = tldjs.getDomain(tab.url);

    getJSON('http://localhost:3131/domain/' + url, function(data) {
      if (data.length > 0) {
        data.forEach(function(item) {
          var img = document.createElement('img');
          img.src = tab.favIconUrl;

          var span = document.createElement('span');
          span.innerHTML = item.username;

          var a = document.createElement('a');
          a.href = 'javascript:;';
          a.dataset['path'] = item.path;
          a.appendChild(img);
          a.appendChild(span);
          a.addEventListener('click', fillInPassword);

          appendListItem(a);
        });
      } else {
        appendListItem('There are no passwords for this website.');
      }
    }, function() {
      appendListItem('passd is not running.');
    });
  });
});
<commit_msg>close the popup when completing the sign in form. fallback to a email input when there's no text input<commit_after>function appendListItem(content) {
  var li = document.createElement('li');
  if (typeof(content) == 'string') {
    li.innerHTML = content;
  } else {
    li.appendChild(content);
  }
  document.querySelector('#passwords').appendChild(li);
}

function fillInPassword() {
  var username = this.querySelector('span').innerHTML;

  getText('http://localhost:3131/pass/' + this.dataset['path'], function(data) {
    chrome.tabs.getSelected(null, function(tab) {
      chrome.tabs.executeScript(tab.id, { code: fillInScript(username, data.trim()) });
      // close the popup
      window.close();
    });
  }, null);
}

function fillInScript(username, password) {
  return "var passwordInput = document.querySelector('input[type=password]');" +
    "passwordInput.value = '" + password + "';" +
    "var form = passwordInput.parentElement;" +
    "while (form.tagName != 'FORM') { form = form.parentElement; };" +
    "var usernameInput = form.querySelector('input[type=text]');" +
    "if (usernameInput == undefined) { usernameInput = form.querySelector('input[type=email]'); };" +
    "usernameInput.value = '" + username + "';" +
    "form.submit();";
}

function getText(url, success, error) {
  var xhr = new XMLHttpRequest();
  xhr.open('GET', url, true);

  xhr.onreadystatechange = function() {
    if (xhr.readyState == 4) {
      success(xhr.responseText);
    }
  };

  xhr.onerror = error;
  xhr.send();
}

function getJSON(url, success, error) {
  getText(url, function(data) {
    success(JSON.parse(data));
  }, error);
}

document.addEventListener('DOMContentLoaded', function() {
  chrome.tabs.getSelected(null, function(tab) {
    var url = tldjs.getDomain(tab.url);

    getJSON('http://localhost:3131/domain/' + url, function(data) {
      if (data.length > 0) {
        data.forEach(function(item) {
          var img = document.createElement('img');
          img.src = tab.favIconUrl;

          var span = document.createElement('span');
          span.innerHTML = item.username;

          var a = document.createElement('a');
          a.href = 'javascript:;';
          a.dataset['path'] = item.path;
          a.appendChild(img);
          a.appendChild(span);
          a.addEventListener('click', fillInPassword);

          appendListItem(a);
        });
      } else {
        appendListItem('There are no passwords for this website.');
      }
    }, function() {
      appendListItem('passd is not running.');
    });
  });
});
<|endoftext|>


<commit_before>import React from 'react';
import { connect } from 'react-redux';
import { createSelector } from 'reselect';
import { getCurrentUser, User, userActions } from 'src/core/users';

import Tracklist from '../../components/tracklist';
import UserCard from '../../components/user-card';

export class UserPage extends React.Component {
  static propTypes = {
    loadUser: React.PropTypes.func.isRequired,
    loadUserLikes: React.PropTypes.func.isRequired,
    loadUserTracks: React.PropTypes.func.isRequired,
    params: React.PropTypes.shape({
      id: React.PropTypes.string.isRequired,
      resource: React.PropTypes.string.isRequired
    }),
    user: React.PropTypes.instanceOf(User)
  };

  componentWillMount() {
    this.loadUser();
  }

  componentWillUpdate(nextProps) {
    if (nextProps.params.resource !== this.props.params.resource) {
      this.loadUser(nextProps.params);
    }
  }

  loadUser(params) {
    params = params || this.props.params;

    this.props.loadUser(params.id);

    if (params.resource === 'likes') {
      this.props.loadUserLikes(params.id);
    }
    else {
      this.props.loadUserTracks(params.id);
    }
  }

  render() {
    const { user } = this.props;

    if (!user) return null;

    return (

        <UserCard user={user} />
        <Tracklist />

    );
  }
}

//=====================================
//  CONNECT
//-------------------------------------

const mapStateToProps = createSelector(
  getCurrentUser,
  user => ({user})
);

const mapDispatchToProps = {
  loadUser: userActions.loadUser,
  loadUserLikes: userActions.loadUserLikes,
  loadUserTracks: userActions.loadUserTracks
};

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(UserPage);
<commit_msg>fix(UserPage): `props.params` is now `props.match.params` in latest `react-router`<commit_after>import React from 'react';
import { connect } from 'react-redux';
import { createSelector } from 'reselect';
import { getCurrentUser, User, userActions } from 'src/core/users';

import Tracklist from '../../components/tracklist';
import UserCard from '../../components/user-card';

export class UserPage extends React.Component {
  static propTypes = {
    loadUser: React.PropTypes.func.isRequired,
    loadUserLikes: React.PropTypes.func.isRequired,
    loadUserTracks: React.PropTypes.func.isRequired,
    params: React.PropTypes.shape({
      id: React.PropTypes.string.isRequired,
      resource: React.PropTypes.string.isRequired
    }),
    user: React.PropTypes.instanceOf(User)
  };

  componentWillMount() {
    this.loadUser();
  }

  componentWillUpdate(nextProps) {
    if (nextProps.match.params.resource !== this.props.match.params.resource) {
      this.loadUser(nextProps.match.params);
    }
  }

  loadUser(params) {
    params = params || this.props.match.params;

    this.props.loadUser(params.id);

    if (params.resource === 'likes') {
      this.props.loadUserLikes(params.id);
    }
    else {
      this.props.loadUserTracks(params.id);
    }
  }

  render() {
    const { user } = this.props;

    if (!user) return null;

    return (

        <UserCard user={user} />
        <Tracklist />

    );
  }
}

//=====================================
//  CONNECT
//-------------------------------------

const mapStateToProps = createSelector(
  getCurrentUser,
  user => ({user})
);

const mapDispatchToProps = {
  loadUser: userActions.loadUser,
  loadUserLikes: userActions.loadUserLikes,
  loadUserTracks: userActions.loadUserTracks
};

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(UserPage);
<|endoftext|>


<commit_before>import { AUTH_API_BASE, IAM_API_BASE } from '../api-version';

const URL_PATH_ACCOUNTS = 'accounts';
const URL_PATH_PROFILE = 'profile';
const URL_PATH_AVATAR = 'avatar';
const URL_PATH_TEAMS = 'teams';
const URL_PATH_ROLE = 'role';
const URL_PATH_ROLES = 'roles';
const URL_PATH_TEAM = 'team';
const URL_PATH_ORGANIZATION = 'organization';
const URL_PATH_MEMBERS = 'members';
const URL_PATH_ROLE_ASSIGNMENTS = 'roleassignments';
const URL_PATH_ORG_DOMAIN = 'domain';
const URL_PATH_ORG_DOMAINS = 'domains';
const URL_PATH_DATA_SCOPE = 'scope';
const URL_PATH_DATA_SETS = 'datasets';

const toPath = (...paths) => `${IAM_API_BASE}/${paths.join('/')}`;

// TODO: move methods to corresponding servlets (auth, me, iam, saas)
export default function authServletFactory(fetch, options) {
    return {
        getAvatar: (id) =>
            fetch(toPath(URL_PATH_ACCOUNTS, id, URL_PATH_AVATAR), {
                ...options,
                raw: true,
            }),

        getOrgAvatar: (id) =>
            fetch(toPath(URL_PATH_ORGANIZATION, id, URL_PATH_AVATAR), {
                ...options,
                raw: true,
            }),

        getAccount: (id) =>
            fetch(toPath(URL_PATH_ACCOUNTS, id) + '?profile=true', options),

        getAccountProfile: (id) =>
            fetch(toPath(URL_PATH_ACCOUNTS, URL_PATH_PROFILE, id), options),

        getAccountProfileByAccountId: (id) =>
            fetch(toPath(URL_PATH_ACCOUNTS, id, URL_PATH_PROFILE), options),

        getTeam: (id) => fetch(toPath(URL_PATH_TEAM, id), options),

        getTeamMembers: (id) =>
            fetch(
                toPath(URL_PATH_TEAM, id, URL_PATH_MEMBERS) + '?profile=true',
                options,
            ),

        getOrganizationMembers: (id) =>
            fetch(
                toPath(URL_PATH_ORGANIZATION, id, URL_PATH_MEMBERS) +
                    '?profile=true',
                options,
            ),

        organizationTeams: (id, virtual = false) =>
            fetch(
                toPath(URL_PATH_ORGANIZATION, id, URL_PATH_TEAMS) +
                    (virtual ? '?include-virtual=true' : ''),
                options,
            ),

        accountTeams: (id) =>
            fetch(toPath(URL_PATH_ACCOUNTS, id, URL_PATH_TEAMS), options),

        organizationDomains: (id) =>
            fetch(
                toPath(URL_PATH_ORGANIZATION, id, URL_PATH_ORG_DOMAINS),
                options,
            ),

        organizationRoleAssignments: (id) =>
            fetch(
                toPath(URL_PATH_ORGANIZATION, id, URL_PATH_ROLE_ASSIGNMENTS) +
                    '?detail=true',
                options,
            ),

        getDomainOrganization: (id) =>
            fetch(
                toPath(URL_PATH_ORG_DOMAIN, id, URL_PATH_ORGANIZATION),
                options,
            ),

        organizationScopes: (id) =>
            fetch(
                toPath(URL_PATH_ORGANIZATION, id, URL_PATH_DATA_SCOPE),
                options,
            ),

        getDataScope: (id) => fetch(toPath(URL_PATH_DATA_SCOPE, id), options),

        organizationDataSets: (id) =>
            fetch(
                toPath(URL_PATH_ORGANIZATION, id, URL_PATH_DATA_SETS),
                options,
            ),

        listAllRoles: () => fetch(toPath(URL_PATH_ROLES), options),

        listRoles: (limit, offset, name) => {
            return fetch(toPath(URL_PATH_ROLE), {
                ...options,
                body: JSON.stringify({ limit, offset, name }),
            });
        },

        revoke: (clientId) => {
            return fetch(`${AUTH_API_BASE}/revoke`, {
                ...options,
                method: 'POST',
                body: JSON.stringify({ client_id: clientId }),
            });
        },
    };
}
<commit_msg>Dont use cors on revoke<commit_after>import { AUTH_API_BASE, IAM_API_BASE } from '../api-version';

const URL_PATH_ACCOUNTS = 'accounts';
const URL_PATH_PROFILE = 'profile';
const URL_PATH_AVATAR = 'avatar';
const URL_PATH_TEAMS = 'teams';
const URL_PATH_ROLE = 'role';
const URL_PATH_ROLES = 'roles';
const URL_PATH_TEAM = 'team';
const URL_PATH_ORGANIZATION = 'organization';
const URL_PATH_MEMBERS = 'members';
const URL_PATH_ROLE_ASSIGNMENTS = 'roleassignments';
const URL_PATH_ORG_DOMAIN = 'domain';
const URL_PATH_ORG_DOMAINS = 'domains';
const URL_PATH_DATA_SCOPE = 'scope';
const URL_PATH_DATA_SETS = 'datasets';

const toPath = (...paths) => `${IAM_API_BASE}/${paths.join('/')}`;

// TODO: move methods to corresponding servlets (auth, me, iam, saas)
export default function authServletFactory(fetch, options) {
    return {
        getAvatar: (id) =>
            fetch(toPath(URL_PATH_ACCOUNTS, id, URL_PATH_AVATAR), {
                ...options,
                raw: true,
            }),

        getOrgAvatar: (id) =>
            fetch(toPath(URL_PATH_ORGANIZATION, id, URL_PATH_AVATAR), {
                ...options,
                raw: true,
            }),

        getAccount: (id) =>
            fetch(toPath(URL_PATH_ACCOUNTS, id) + '?profile=true', options),

        getAccountProfile: (id) =>
            fetch(toPath(URL_PATH_ACCOUNTS, URL_PATH_PROFILE, id), options),

        getAccountProfileByAccountId: (id) =>
            fetch(toPath(URL_PATH_ACCOUNTS, id, URL_PATH_PROFILE), options),

        getTeam: (id) => fetch(toPath(URL_PATH_TEAM, id), options),

        getTeamMembers: (id) =>
            fetch(
                toPath(URL_PATH_TEAM, id, URL_PATH_MEMBERS) + '?profile=true',
                options,
            ),

        getOrganizationMembers: (id) =>
            fetch(
                toPath(URL_PATH_ORGANIZATION, id, URL_PATH_MEMBERS) +
                    '?profile=true',
                options,
            ),

        organizationTeams: (id, virtual = false) =>
            fetch(
                toPath(URL_PATH_ORGANIZATION, id, URL_PATH_TEAMS) +
                    (virtual ? '?include-virtual=true' : ''),
                options,
            ),

        accountTeams: (id) =>
            fetch(toPath(URL_PATH_ACCOUNTS, id, URL_PATH_TEAMS), options),

        organizationDomains: (id) =>
            fetch(
                toPath(URL_PATH_ORGANIZATION, id, URL_PATH_ORG_DOMAINS),
                options,
            ),

        organizationRoleAssignments: (id) =>
            fetch(
                toPath(URL_PATH_ORGANIZATION, id, URL_PATH_ROLE_ASSIGNMENTS) +
                    '?detail=true',
                options,
            ),

        getDomainOrganization: (id) =>
            fetch(
                toPath(URL_PATH_ORG_DOMAIN, id, URL_PATH_ORGANIZATION),
                options,
            ),

        organizationScopes: (id) =>
            fetch(
                toPath(URL_PATH_ORGANIZATION, id, URL_PATH_DATA_SCOPE),
                options,
            ),

        getDataScope: (id) => fetch(toPath(URL_PATH_DATA_SCOPE, id), options),

        organizationDataSets: (id) =>
            fetch(
                toPath(URL_PATH_ORGANIZATION, id, URL_PATH_DATA_SETS),
                options,
            ),

        listAllRoles: () => fetch(toPath(URL_PATH_ROLES), options),

        listRoles: (limit, offset, name) => {
            return fetch(toPath(URL_PATH_ROLE), {
                ...options,
                body: JSON.stringify({ limit, offset, name }),
            });
        },

        revoke: (clientId) => {
            return fetch(`${AUTH_API_BASE}/revoke`, {
                ...options,
                method: 'POST',
                body: JSON.stringify({ client_id: clientId }),
                mode: 'no-cors',
                raw: true,
            });
        },
    };
}
<|endoftext|>


<commit_before>/**
 *
 * Configuration options are loaded from files in tasks/options
 *
 * Normally inside this file you'd see:
 *
 * clean: {
 *   development: ['file-to-clean']
 * }
 *
 * Instead the file at tasks/options/clean.js contains:
 *
 * module.exports = {
 *   development: ['file-to-clean']
 * }
 *
 * Sharing Configuration Options:
 *
 * Configuration options used across multiple modules are set in the following
 * manner:
 *
 * `grunt.config('settings', settings);`
 * `grunt.config('paths', settings.paths);`
 *
 *
 * Furthermore, getting those options occurs in a similar fashion:
 *
 * `grunt.config('paths.output.js');` //=> public/js
 *
 * Using the conventional <%%= paths.output.js %> will NOT work
 *
 */

module.exports = function(grunt) {

  var settings = {
    liveReloadPort: 35729 || process.env.LRPort,
    port: process.env.PORT || 8000,
    hostname: 'localhost',
    templates: {},
    paths: {
      'public': 'public',
      dist: 'dist',
      tmpDist: 'tmpDist',
      distOutput: {
        js: 'dist/main.js',
      },
      output: {
        js: 'public/js',
        css: 'public/css'
      },
      js: 'js',
      css: 'css',
      templates: 'js/templates',
      views: 'js/views',
      models: 'js/models',
      collections: 'js/collections'
    }
  };

  grunt.config('settings', settings);
  grunt.config('paths', settings.paths);

  grunt.loadNpmTasks('thorax-inspector'); // TODO: remove livereload issue
  grunt.loadTasks('tasks');

  grunt.registerTask('default', [
    'ensure-installed',
    'clean:development',
    'styles',
    'templates:public/js',
    'copy:requirejs',
    'requirejs:development',
    'thorax:inspector',
    'connect:development',
    'open-browser',
    'watch'
  ]);

  grunt.registerTask('production', [
    'clean:production',
    'styles',
    'cssmin',
    'templates:tmpDist',
    'copy:tmpDist',
    'requirejs:production',
    'open-browser',
    'connect:production'
  ]);

  require('load-grunt-config')(grunt, {
    configPath: __dirname + '/tasks/options'
  });

};
<commit_msg>remove comment added to _Gruntfile.js, isolate source of error<commit_after>module.exports = function(grunt) {

  var settings = {
    liveReloadPort: 35729 || process.env.LRPort,
    port: process.env.PORT || 8000,
    hostname: 'localhost',
    templates: {},
    paths: {
      'public': 'public',
      dist: 'dist',
      tmpDist: 'tmpDist',
      distOutput: {
        js: 'dist/main.js',
      },
      output: {
        js: 'public/js',
        css: 'public/css'
      },
      js: 'js',
      css: 'css',
      templates: 'js/templates',
      views: 'js/views',
      models: 'js/models',
      collections: 'js/collections'
    }
  };

  grunt.config('settings', settings);
  grunt.config('paths', settings.paths);

  grunt.loadNpmTasks('thorax-inspector'); // TODO: remove livereload issue
  grunt.loadTasks('tasks');

  grunt.registerTask('default', [
    'ensure-installed',
    'clean:development',
    'styles',
    'templates:public/js',
    'copy:requirejs',
    'requirejs:development',
    'thorax:inspector',
    'connect:development',
    'open-browser',
    'watch'
  ]);

  grunt.registerTask('production', [
    'clean:production',
    'styles',
    'cssmin',
    'templates:tmpDist',
    'copy:tmpDist',
    'requirejs:production',
    'open-browser',
    'connect:production'
  ]);

  require('load-grunt-config')(grunt, {
    configPath: __dirname + '/tasks/options'
  });

};
<|endoftext|>


<commit_before>/*! Copyright (c) 2013 Brandon Aaron (http://brandonaaron.net)
 * Licensed under the MIT License (LICENSE.txt).
 *
 * Thanks to: http://adomas.org/javascript-mouse-wheel/ for some pointers.
 * Thanks to: Mathias Bank(http://www.mathias-bank.de) for a scope bug fix.
 * Thanks to: Seamus Leahy for adding deltaX and deltaY
 *
 * Version: 3.1.2
 *
 * Requires: 1.2.2+
 */

(function (factory) {
    if ( typeof define === 'function' && define.amd ) {
        // AMD. Register as an anonymous module.
        define(['jquery'], factory);
    } else if (typeof exports === 'object') {
        // Node/CommonJS style for Browserify
        module.exports = factory;
    } else {
        // Browser globals
        factory(jQuery);
    }
}(function ($) {

    var toFix = ['wheel', 'mousewheel', 'DOMMouseScroll'];
    var toBind = 'onwheel' in document || document.documentMode >= 9 ? ['wheel'] : ['mousewheel', 'DomMouseScroll', 'MozMousePixelScroll'];
    var lowestDelta, lowestDeltaXY;

    if ( $.event.fixHooks ) {
        for ( var i = toFix.length; i; ) {
            $.event.fixHooks[ toFix[--i] ] = $.event.mouseHooks;
        }
    }

    $.event.special.mousewheel = {
        setup: function() {
            if ( this.addEventListener ) {
                for ( var i = toBind.length; i; ) {
                    this.addEventListener( toBind[--i], handler, false );
                }
            } else {
                this.onmousewheel = handler;
            }
        },

        teardown: function() {
            if ( this.removeEventListener ) {
                for ( var i = toBind.length; i; ) {
                    this.removeEventListener( toBind[--i], handler, false );
                }
            } else {
                this.onmousewheel = null;
            }
        }
    };

    $.fn.extend({
        mousewheel: function(fn) {
            return fn ? this.bind("mousewheel", fn) : this.trigger("mousewheel");
        },

        unmousewheel: function(fn) {
            return this.unbind("mousewheel", fn);
        }
    });

    function handler(event) {
        var orgEvent = event || window.event,
            args = [].slice.call(arguments, 1),
            delta = 0,
            deltaX = 0,
            deltaY = 0,
            absDelta = 0,
            absDeltaXY = 0,
            fn;
        event = $.event.fix(orgEvent);
        event.type = "mousewheel";

        // Old school scrollwheel delta
        if ( orgEvent.wheelDelta ) { delta = orgEvent.wheelDelta; }
        if ( orgEvent.detail )     { delta = orgEvent.detail * -1; }

        // New school wheel delta (wheel event)
        if ( orgEvent.deltaY ) {
            deltaY = orgEvent.deltaY * -1;
            delta  = deltaY;
        }
        if ( orgEvent.deltaX ) {
            deltaX = orgEvent.deltaX;
            delta  = deltaX * -1;
        }

        // Webkit
        if ( orgEvent.wheelDeltaY !== undefined ) { deltaY = orgEvent.wheelDeltaY; }
        if ( orgEvent.wheelDeltaX !== undefined ) { deltaX = orgEvent.wheelDeltaX * -1; }

        // Look for lowest delta to normalize the delta values
        absDelta = Math.abs(delta);
        if ( !lowestDelta || absDelta < lowestDelta ) { lowestDelta = absDelta; }
        absDeltaXY = Math.max(Math.abs(deltaY), Math.abs(deltaX));
        if ( !lowestDeltaXY || absDeltaXY < lowestDeltaXY ) { lowestDeltaXY = absDeltaXY; }

        // Get a whole value for the deltas
        fn = delta > 0 ? 'floor' : 'ceil';
        delta  = Math[fn](delta / lowestDelta);
        deltaX = Math[fn](deltaX / lowestDeltaXY);
        deltaY = Math[fn](deltaY / lowestDeltaXY);

        // Add event and delta to the front of the arguments
        args.unshift(event, delta, deltaX, deltaY);

        return ($.event.dispatch || $.event.handle).apply(this, args);
    }

}));
<commit_msg>add MozMousePixelScroll to the fixed events list<commit_after>/*! Copyright (c) 2013 Brandon Aaron (http://brandonaaron.net)
 * Licensed under the MIT License (LICENSE.txt).
 *
 * Thanks to: http://adomas.org/javascript-mouse-wheel/ for some pointers.
 * Thanks to: Mathias Bank(http://www.mathias-bank.de) for a scope bug fix.
 * Thanks to: Seamus Leahy for adding deltaX and deltaY
 *
 * Version: 3.1.2
 *
 * Requires: 1.2.2+
 */

(function (factory) {
    if ( typeof define === 'function' && define.amd ) {
        // AMD. Register as an anonymous module.
        define(['jquery'], factory);
    } else if (typeof exports === 'object') {
        // Node/CommonJS style for Browserify
        module.exports = factory;
    } else {
        // Browser globals
        factory(jQuery);
    }
}(function ($) {

    var toFix = ['wheel', 'mousewheel', 'DOMMouseScroll', 'MozMousePixelScroll'];
    var toBind = 'onwheel' in document || document.documentMode >= 9 ? ['wheel'] : ['mousewheel', 'DomMouseScroll', 'MozMousePixelScroll'];
    var lowestDelta, lowestDeltaXY;

    if ( $.event.fixHooks ) {
        for ( var i = toFix.length; i; ) {
            $.event.fixHooks[ toFix[--i] ] = $.event.mouseHooks;
        }
    }

    $.event.special.mousewheel = {
        setup: function() {
            if ( this.addEventListener ) {
                for ( var i = toBind.length; i; ) {
                    this.addEventListener( toBind[--i], handler, false );
                }
            } else {
                this.onmousewheel = handler;
            }
        },

        teardown: function() {
            if ( this.removeEventListener ) {
                for ( var i = toBind.length; i; ) {
                    this.removeEventListener( toBind[--i], handler, false );
                }
            } else {
                this.onmousewheel = null;
            }
        }
    };

    $.fn.extend({
        mousewheel: function(fn) {
            return fn ? this.bind("mousewheel", fn) : this.trigger("mousewheel");
        },

        unmousewheel: function(fn) {
            return this.unbind("mousewheel", fn);
        }
    });

    function handler(event) {
        var orgEvent = event || window.event,
            args = [].slice.call(arguments, 1),
            delta = 0,
            deltaX = 0,
            deltaY = 0,
            absDelta = 0,
            absDeltaXY = 0,
            fn;
        event = $.event.fix(orgEvent);
        event.type = "mousewheel";

        // Old school scrollwheel delta
        if ( orgEvent.wheelDelta ) { delta = orgEvent.wheelDelta; }
        if ( orgEvent.detail )     { delta = orgEvent.detail * -1; }

        // New school wheel delta (wheel event)
        if ( orgEvent.deltaY ) {
            deltaY = orgEvent.deltaY * -1;
            delta  = deltaY;
        }
        if ( orgEvent.deltaX ) {
            deltaX = orgEvent.deltaX;
            delta  = deltaX * -1;
        }

        // Webkit
        if ( orgEvent.wheelDeltaY !== undefined ) { deltaY = orgEvent.wheelDeltaY; }
        if ( orgEvent.wheelDeltaX !== undefined ) { deltaX = orgEvent.wheelDeltaX * -1; }

        // Look for lowest delta to normalize the delta values
        absDelta = Math.abs(delta);
        if ( !lowestDelta || absDelta < lowestDelta ) { lowestDelta = absDelta; }
        absDeltaXY = Math.max(Math.abs(deltaY), Math.abs(deltaX));
        if ( !lowestDeltaXY || absDeltaXY < lowestDeltaXY ) { lowestDeltaXY = absDeltaXY; }

        // Get a whole value for the deltas
        fn = delta > 0 ? 'floor' : 'ceil';
        delta  = Math[fn](delta / lowestDelta);
        deltaX = Math[fn](deltaX / lowestDeltaXY);
        deltaY = Math[fn](deltaY / lowestDeltaXY);

        // Add event and delta to the front of the arguments
        args.unshift(event, delta, deltaX, deltaY);

        return ($.event.dispatch || $.event.handle).apply(this, args);
    }

}));
<|endoftext|>


<commit_before>var LIVERELOAD_PORT = 35729;
var mountFolder = function (connect, dir) {
  return connect.static(require('path').resolve(dir));
};

module.exports = function(grunt) {
	grunt.initConfig({
		pkg: grunt.file.readJSON('package.json'),
		clean: {
            release:['build/dev/'],
            dev:['build/release/']
        },
		uglify: {
    		options: {
    	       banner: '/*! <%= pkg.name %> <%= grunt.template.today("yyyy-mm-dd") %> */\n'
    		},
    		build: {
                files: [{
                    expand: true,
                    flatten: true,
                    cwd: 'app/src/libs/',
        		    src: 'jquery/jquery.js',
        		    dest: 'build/dev/src/libs/',
                    ext: '.min.js'
        		  },
                  {
                    expand: true,
                    flatten: true,
                    cwd: 'app/src/libs/',
                    src: 'modernizr/modernizr.js',
                    dest: 'build/dev/src/libs/',
                    ext: '.min.js'
                  },
                  {
                    'build/dev/src/libs/requirejs-jquery.min.js': ['app/src/libs/requirejs-jquery/parts/require.js', 'app/src/libs/requirejs-jquery/parts/query.js']
                  }]
            }
		},
		copy: {
    	  dev: {
            files: [{
              expand: true,
              flatten: true,
              cwd: 'app/src/libs/',
              src: 'backbone/backbone-min.js',
              dest: 'build/dev/src/libs/',
              filter: 'isFile'
            },
            {
              expand: true,
              flatten: true,
              cwd: 'app/src/libs/',
              src: 'crafty/crafty.min.js',
              dest: 'build/dev/src/libs/',
              filter: 'isFile'
            },
            {
                expand: true,
                flatten: true,
                cwd: 'app/src/libs/',
                src: 'underscore/underscore-min.js',
                dest: 'build/dev/src/libs/',
                filter: 'isFile'
            },
            {
                expand: true,
                cwd: 'app/src/',
                src: ['**/*.js', '!libs/**'],
                dest: 'build/dev/src/',
                filter: 'isFile'
            },
            {
                expand: true,
                flatten: true,
                cwd: 'app/',
                src: 'index.html',
                dest: 'build/dev/',
                filter: 'isFile'
            }]
          }
        },
        connect: {
        	server: {
		      options: {
		        port: 8888,
		        hostname: 'localhost',
		        base: "build/dev"
		      }
		    },
	        livereload: {
	          options: {
	            middleware: function (connect) {
	              return [
	                require('connect-livereload')({port: LIVERELOAD_PORT}),
	                mountFolder(connect, '.')
	              ];
	            }
	          }
            }
        },
        open: {
	      server: {
	        path: 'http://localhost:<%= connect.server.options.port %>'
	      }
	    },
        watch: {
	      options: {
	        nospawn: true,
	        livereload: LIVERELOAD_PORT
	      },
	      livereload: {
	        files: [
	          'app/index.html'
	        ],
	        tasks: ['build']
	      }
	    }
	});

	grunt.loadNpmTasks('grunt-contrib-clean');
	grunt.loadNpmTasks('grunt-contrib-uglify');
	grunt.loadNpmTasks('grunt-contrib-copy');
	grunt.loadNpmTasks('grunt-contrib-connect');
	grunt.loadNpmTasks('grunt-contrib-watch');
	grunt.loadNpmTasks('grunt-open');

	grunt.registerTask('build', ['clean', 'uglify', 'copy']);
	grunt.registerTask('server', ['build', 'connect:server', 'open', 'watch']);
	grunt.registerTask('default', ['build', 'server']);
}
<commit_msg>Fixing bug associated with requirejs file names and minification<commit_after>var LIVERELOAD_PORT = 35729;
var mountFolder = function (connect, dir) {
  return connect.static(require('path').resolve(dir));
};

module.exports = function(grunt) {
	grunt.initConfig({
		pkg: grunt.file.readJSON('package.json'),
		clean: ['dist'],
		uglify: {
			build: {
				files: [{
                    expand: true,
                    cwd: 'app/src/',
                    src: ['**/*.js', '!libs/**/*'],
                    dest: 'dist/src/',
                    ext: 'a.js'
				},
				{
                    expand: true,
                    flatten: true,
                    cwd: 'app/src/libs/',
        		    src: ['jquery/jquery.js', 'modernizr/modernizr.js'],
        		    dest: 'dist/src/libs/',
                    ext: '.min.js'
        		},
                {
                    'dist/src/libs/requirejs-jquery.min.js': ['app/src/libs/requirejs-jquery/parts/require.js', 'app/src/libs/requirejs-jquery/parts/query.js']
                }]
			}
		},
		copy: {
    	  dist: {
            files: [{
              expand: true,
              flatten: true,
              cwd: 'app/src/libs/',
              src: ['backbone/backbone-min.js', 'backbone/backbone-min.map', 'underscore/underscore-min.js', 'underscore/underscore-min.map', 'crafty/crafty.min.js'],
              dest: 'dist/src/libs/',
              filter: 'isFile'
            }]
          }
        },
        connect: {
        	server: {
		      options: {
		        port: 8888,
		        hostname: 'localhost',
		        base: "app/"
		      }
		    },
	        livereload: {
	          options: {
	            middleware: function (connect) {
	              return [
	                require('connect-livereload')({port: LIVERELOAD_PORT}),
	                mountFolder(connect, '.')
	              ];
	            }
	          }
            }
        },
        open: {
	      server: {
	        path: 'http://localhost:<%= connect.server.options.port %>'
	      }
	    },
        watch: {
	      options: {
	        nospawn: true,
	        livereload: LIVERELOAD_PORT
	      },
	      livereload: {
	        files: [
	          'app/index.html'
	        ],
	        tasks: ['build']
	      }
	    }
	});

	grunt.loadNpmTasks('grunt-contrib-clean');
	grunt.loadNpmTasks('grunt-contrib-uglify');
	grunt.loadNpmTasks('grunt-contrib-copy');
	grunt.loadNpmTasks('grunt-contrib-connect');
	grunt.loadNpmTasks('grunt-contrib-watch');
	grunt.loadNpmTasks('grunt-open');

	grunt.registerTask('build:dev', ['clean', 'uglify', 'copy']);
	grunt.registerTask('server', ['build', 'connect:server', 'open', 'watch']);
	grunt.registerTask('default', ['build', 'server']);
}
<|endoftext|>