<commit_before>import template from 'babel-template';

const buildClassDecorator = template(`
  DECORATOR(CLASS_REF = INNER) || CLASS_REF;
`);

const buildPropertyDecorator = template(`
  DECORATOR(TARGET, PROPERTY, DESC = INNER) || DESC;
`);

const buildClassPrototype = template(`
  CLASS_REF.prototype;
`);

const buildGetDescriptor = template(`
    Object.getOwnPropertyDescriptor(TARGET, PROPERTY);
`);

const buildSetDescriptor = template(`
    DESC ? Object.defineProperty(TARGET, PROPERTY, DESC) : undefined;
`);

const buildGetObjectInitializer = template(`
    (TEMP = Object.getOwnPropertyDescriptor(TARGET, PROPERTY).value, {
        enumerable: true,
        configurable: true,
        writable: true,
        initializer: function(){
            return TEMP;
        }
    })
`);

const buildSetObjectInitializer = template(`
    (DESC.value = DESC.initializer ? DESC.initializer.call(TARGET) : undefined) &&
        Object.defineProperty(TARGET, PROPERTY, DESC);
`);

const buildGetClassInitializer = template(`
    ({
        enumerable: true,
        configurable: true,
        writable: true,
        initializer: INIT,
    })
`);

const buildSetClassInitializer = template(`
    INIT = DESC.initializer;
`);

export default function({types: t}){

    /**
     * Given a class expression with class-level decorators, create a new expression
     * with the proper decorated behavior.
     */
    function applyClassDecorators(classPath){
        const decorators = classPath.node.decorators || [];
        classPath.node.decorators = null;

        if (decorators.length === 0) return;

        const name = classPath.scope.generateDeclaredUidIdentifier('class');

        return decorators
            .map(dec => dec.expression)
            .reverse()
            .reduce(function(acc, decorator){
                return buildClassDecorator({
                    CLASS_REF: name,
                    DECORATOR: decorator,
                    INNER: acc,
                }).expression;
            }, classPath.node);
    }

    /**
     * Given a class expression with method-level decorators, create a new expression
     * with the proper decorated behavior.
     */
    function applyMethodDecorators(classPath){
        const hasMethodDecorators = classPath.node.body.body.some(function(node){
            return (node.decorators || []).length > 0;
        });

        if (!hasMethodDecorators) return;

        const name = classPath.scope.generateDeclaredUidIdentifier('class');

        const target = buildClassPrototype({
            CLASS_REF: name,
        }).expression;

        return t.sequenceExpression([
            t.assignmentExpression('=', name, classPath.node),
            applyTargetDecorators(classPath, name, target, classPath.node.body.body),
            name,
        ]);
    }

    /**
     * Given an object expression with property decorators, create a new expression
     * with the proper decorated behavior.
     */
    function applyObjectDecorators(path){
        const hasMethodDecorators = path.node.properties.some(function(node){
            return (node.decorators || []).length > 0;
        });

        if (!hasMethodDecorators) return;

        const name = path.scope.generateDeclaredUidIdentifier('obj');

        return t.sequenceExpression([
            t.assignmentExpression('=', name, path.node),
            applyTargetDecorators(path, name, name, path.node.properties),
            name,
        ]);
    }

    /**
     * A helper to pull out property decorators into a sequence expression.
     */
    function applyTargetDecorators(path, name, target, decoratedProps){
        const descName = path.scope.generateDeclaredUidIdentifier('desc');
        const valueTemp = path.scope.generateDeclaredUidIdentifier('value');

        return t.sequenceExpression(decoratedProps.reduce(function(acc, node){
            const decorators = node.decorators || [];
            node.decorators = null;

            if (decorators.length === 0) return acc;

            const property = t.stringLiteral(node.key.name);

            let buildDecoratorCall = function(descriptor, expr){
                return buildPropertyDecorator({
                    TARGET: target,
                    DECORATOR: expr,
                    DESC: descName,
                    INNER: descriptor,
                    PROPERTY: property,
                }).expression;
            };
            let buildDescriptorCreate;
            let buildDescriptorStore;

            if (t.isObjectProperty(node)){
                // Read value from object and store in temp to be read from initializer.
                buildDescriptorCreate = function(){
                    return buildGetObjectInitializer({
                        TEMP: path.scope.generateDeclaredUidIdentifier('init'),
                        TARGET: target,
                        PROPERTY: property
                    }).expression;
                };

                // Trigger initializer and set descriptor.
                buildDescriptorStore = function(){
                    return buildSetObjectInitializer({
                        TARGET: target,
                        PROPERTY: property,
                        DESC: descName,
                    }).expression;
                };
            } else if (t.isClassProperty(node)){
                let init = path.scope.generateDeclaredUidIdentifier('init');
                let oldInitializer;
                if (node.value){
                    // Move the initializer to a temp variable and reassign to new temp.
                    oldInitializer = node.value;
                    acc.push(t.assignmentExpression('=', init, t.functionExpression(null, [], t.blockStatement([
                        t.returnStatement(oldInitializer),
                    ]))));
                }
                node.value = t.callExpression(t.memberExpression(init, t.identifier('apply')), [t.thisExpression()]);

                // Create initializer that reads from new temp.
                buildDescriptorCreate = function(){
                    return buildGetClassInitializer({
                        INIT: oldInitializer ? init : t.nullLiteral(),
                    }).expression;
                };

                // Trigger initializer and set descriptor.
                buildDescriptorStore = function(){
                    return buildSetClassInitializer({
                        INIT: init,
                        DESC: descName,
                    }).expression;
                };
            } else {
                // Read descriptor normally.
                buildDescriptorCreate = function(){
                    return buildGetDescriptor({
                        TARGET: target,
                        PROPERTY: property,
                    }).expression;
                };

                // Store descriptor normally.
                buildDescriptorStore = function(){
                    return buildSetDescriptor({
                        TARGET: target,
                        PROPERTY: property,
                        DESC: descName,
                    }).expression;
                };
            }

            return acc.concat(
                decorators
                    .map(dec => dec.expression)
                    .reverse()
                    .reduce(buildDecoratorCall, buildDescriptorCreate()),
                buildDescriptorStore()
            );
        }, []))
    }

    return {
        inherits: require("babel-plugin-syntax-decorators"),

        visitor: {
            ExportDefaultDeclaration(path){
                if (!path.get("declaration").isClassDeclaration()) return;

                const {node} = path;
                const ref = node.declaration.id || path.scope.generateUidIdentifier("default");
                node.declaration.id = ref;

                // Split the class declaration and the export into two separate statements.
                path.replaceWith(node.declaration);
                path.insertAfter(t.exportNamedDeclaration(null, [t.exportSpecifier(ref, t.identifier('default'))]));
            },
            ClassDeclaration(path){
                const {node} = path;

                const ref = node.id || path.scope.generateUidIdentifier("class");

                path.replaceWith(t.variableDeclaration("let", [
                  t.variableDeclarator(ref, t.toExpression(node))
                ]));
            },
            ClassExpression(path){
                // Create a replacement for the class node if there is one. We do one pass to replace classes with
                // class decorators, and a second pass to process method decorators.
                const decoratedClass = applyClassDecorators(path) || applyMethodDecorators(path);

                if (decoratedClass) path.replaceWith(decoratedClass);
            },
            ObjectExpression(path){
                const decoratedObject = applyObjectDecorators(path);

                if (decoratedObject) path.replaceWith(decoratedObject);
            },
        }
    };
};
<commit_msg>Ensure returned decorator values are saved.<commit_after>import template from 'babel-template';

const buildClassDecorator = template(`
  DECORATOR(CLASS_REF = INNER) || CLASS_REF;
`);

const buildPropertyDecorator = template(`
  DESC = DECORATOR(TARGET, PROPERTY, INNER) || DESC;
`);

const buildClassPrototype = template(`
  CLASS_REF.prototype;
`);

const buildGetDescriptor = template(`
    Object.getOwnPropertyDescriptor(TARGET, PROPERTY);
`);

const buildSetDescriptor = template(`
    DESC ? Object.defineProperty(TARGET, PROPERTY, DESC) : undefined;
`);

const buildGetObjectInitializer = template(`
    (TEMP = Object.getOwnPropertyDescriptor(TARGET, PROPERTY).value, {
        enumerable: true,
        configurable: true,
        writable: true,
        initializer: function(){
            return TEMP;
        }
    })
`);

const buildSetObjectInitializer = template(`
    (DESC.value = DESC.initializer ? DESC.initializer.call(TARGET) : undefined) &&
        Object.defineProperty(TARGET, PROPERTY, DESC);
`);

const buildGetClassInitializer = template(`
    ({
        enumerable: true,
        configurable: true,
        writable: true,
        initializer: INIT,
    })
`);

const buildSetClassInitializer = template(`
    INIT = DESC.initializer;
`);

export default function({types: t}){

    /**
     * Given a class expression with class-level decorators, create a new expression
     * with the proper decorated behavior.
     */
    function applyClassDecorators(classPath){
        const decorators = classPath.node.decorators || [];
        classPath.node.decorators = null;

        if (decorators.length === 0) return;

        const name = classPath.scope.generateDeclaredUidIdentifier('class');

        return decorators
            .map(dec => dec.expression)
            .reverse()
            .reduce(function(acc, decorator){
                return buildClassDecorator({
                    CLASS_REF: name,
                    DECORATOR: decorator,
                    INNER: acc,
                }).expression;
            }, classPath.node);
    }

    /**
     * Given a class expression with method-level decorators, create a new expression
     * with the proper decorated behavior.
     */
    function applyMethodDecorators(classPath){
        const hasMethodDecorators = classPath.node.body.body.some(function(node){
            return (node.decorators || []).length > 0;
        });

        if (!hasMethodDecorators) return;

        const name = classPath.scope.generateDeclaredUidIdentifier('class');

        const target = buildClassPrototype({
            CLASS_REF: name,
        }).expression;

        return t.sequenceExpression([
            t.assignmentExpression('=', name, classPath.node),
            applyTargetDecorators(classPath, name, target, classPath.node.body.body),
            name,
        ]);
    }

    /**
     * Given an object expression with property decorators, create a new expression
     * with the proper decorated behavior.
     */
    function applyObjectDecorators(path){
        const hasMethodDecorators = path.node.properties.some(function(node){
            return (node.decorators || []).length > 0;
        });

        if (!hasMethodDecorators) return;

        const name = path.scope.generateDeclaredUidIdentifier('obj');

        return t.sequenceExpression([
            t.assignmentExpression('=', name, path.node),
            applyTargetDecorators(path, name, name, path.node.properties),
            name,
        ]);
    }

    /**
     * A helper to pull out property decorators into a sequence expression.
     */
    function applyTargetDecorators(path, name, target, decoratedProps){
        const descName = path.scope.generateDeclaredUidIdentifier('desc');
        const valueTemp = path.scope.generateDeclaredUidIdentifier('value');

        return t.sequenceExpression(decoratedProps.reduce(function(acc, node){
            const decorators = node.decorators || [];
            node.decorators = null;

            if (decorators.length === 0) return acc;

            const property = t.stringLiteral(node.key.name);

            let buildDecoratorCall = function(descriptor, expr){
                return buildPropertyDecorator({
                    TARGET: target,
                    DECORATOR: expr,
                    DESC: descName,
                    INNER: descriptor,
                    PROPERTY: property,
                }).expression;
            };
            let buildDescriptorCreate;
            let buildDescriptorStore;

            if (t.isObjectProperty(node)){
                // Read value from object and store in temp to be read from initializer.
                buildDescriptorCreate = function(){
                    return buildGetObjectInitializer({
                        TEMP: path.scope.generateDeclaredUidIdentifier('init'),
                        TARGET: target,
                        PROPERTY: property
                    }).expression;
                };

                // Trigger initializer and set descriptor.
                buildDescriptorStore = function(){
                    return buildSetObjectInitializer({
                        TARGET: target,
                        PROPERTY: property,
                        DESC: descName,
                    }).expression;
                };
            } else if (t.isClassProperty(node)){
                let init = path.scope.generateDeclaredUidIdentifier('init');
                let oldInitializer;
                if (node.value){
                    // Move the initializer to a temp variable and reassign to new temp.
                    oldInitializer = node.value;
                    acc.push(t.assignmentExpression('=', init, t.functionExpression(null, [], t.blockStatement([
                        t.returnStatement(oldInitializer),
                    ]))));
                }
                node.value = t.callExpression(t.memberExpression(init, t.identifier('apply')), [t.thisExpression()]);

                // Create initializer that reads from new temp.
                buildDescriptorCreate = function(){
                    return buildGetClassInitializer({
                        INIT: oldInitializer ? init : t.nullLiteral(),
                    }).expression;
                };

                // Trigger initializer and set descriptor.
                buildDescriptorStore = function(){
                    return buildSetClassInitializer({
                        INIT: init,
                        DESC: descName,
                    }).expression;
                };
            } else {
                // Read descriptor normally.
                buildDescriptorCreate = function(){
                    return buildGetDescriptor({
                        TARGET: target,
                        PROPERTY: property,
                    }).expression;
                };

                // Store descriptor normally.
                buildDescriptorStore = function(){
                    return buildSetDescriptor({
                        TARGET: target,
                        PROPERTY: property,
                        DESC: descName,
                    }).expression;
                };
            }

            return acc.concat(
                decorators
                    .map(dec => dec.expression)
                    .reverse()
                    .reduce(buildDecoratorCall, t.assignmentExpression('=', descName, buildDescriptorCreate())),
                buildDescriptorStore()
            );
        }, []))
    }

    return {
        inherits: require("babel-plugin-syntax-decorators"),

        visitor: {
            ExportDefaultDeclaration(path){
                if (!path.get("declaration").isClassDeclaration()) return;

                const {node} = path;
                const ref = node.declaration.id || path.scope.generateUidIdentifier("default");
                node.declaration.id = ref;

                // Split the class declaration and the export into two separate statements.
                path.replaceWith(node.declaration);
                path.insertAfter(t.exportNamedDeclaration(null, [t.exportSpecifier(ref, t.identifier('default'))]));
            },
            ClassDeclaration(path){
                const {node} = path;

                const ref = node.id || path.scope.generateUidIdentifier("class");

                path.replaceWith(t.variableDeclaration("let", [
                  t.variableDeclarator(ref, t.toExpression(node))
                ]));
            },
            ClassExpression(path){
                // Create a replacement for the class node if there is one. We do one pass to replace classes with
                // class decorators, and a second pass to process method decorators.
                const decoratedClass = applyClassDecorators(path) || applyMethodDecorators(path);

                if (decoratedClass) path.replaceWith(decoratedClass);
            },
            ObjectExpression(path){
                const decoratedObject = applyObjectDecorators(path);

                if (decoratedObject) path.replaceWith(decoratedObject);
            },
        }
    };
};
<|endoftext|>


<commit_before>import {queueingExec, spawnProccess} from './spawner';
import ParsedArgs from './parsed-args';

export default (args) => {
  const parsed = new ParsedArgs(args);
  const expandGlob = parsed.args[parsed.globIndex];
  const renameOutfile = parsed.args[parsed.outfileIndex];
  const files = expandGlob && expandGlob(parsed.globOptions);

  if (!expandGlob) {
    if (renameOutfile) parsed.args[parsed.outfileIndex] = renameOutfile();
    return spawnProccess(parsed.cmd, parsed.args);
  }

  if (!renameOutfile) {
    Array.prototype.splice.apply(parsed.args, [parsed.globIndex, 1].concat(files));
    return spawnProccess(parsed.cmd, parsed.args);
  }

  const fileArgs = files.map((file) => {
   const fileArgs = parsed.args.slice();
    fileArgs[parsed.globIndex] = file;
    fileArgs[parsed.outfileIndex] = renameOutfile(file, parsed.baseDir);
    return fileArgs;
  });

  if(fileArgs.length === 0) {
    console.error('glob-pattern unmatched!');
    process.exit(1);
  }

  if(parsed.cmd === 'watchify' || parsed.maxProcs === Infinity) return fileArgs.forEach((args) => spawnProccess(parsed.cmd, args));
  queueingExec(parsed.cmd, fileArgs, parsed.maxProcs);
  return undefined;
};
<commit_msg>fixed eslint errors<commit_after>import {queueingExec, spawnProccess} from './spawner';
import ParsedArgs from './parsed-args';

export default (args) => {
  const parsed = new ParsedArgs(args);
  const expandGlob = parsed.args[parsed.globIndex];
  const renameOutfile = parsed.args[parsed.outfileIndex];
  const files = expandGlob && expandGlob(parsed.globOptions);

  if (!expandGlob) {
    if (renameOutfile) parsed.args[parsed.outfileIndex] = renameOutfile();
    return spawnProccess(parsed.cmd, parsed.args);
  }

  if (!renameOutfile) {
    Array.prototype.splice.apply(parsed.args, [parsed.globIndex, 1].concat(files));
    return spawnProccess(parsed.cmd, parsed.args);
  }

  const fileArgs = files.map((file) => {
   const fileArgs = parsed.args.slice();
    fileArgs[parsed.globIndex] = file;
    fileArgs[parsed.outfileIndex] = renameOutfile(file, parsed.baseDir);
    return fileArgs;
  });

  if(fileArgs.length === 0) {
    console.error('glob-pattern unmatched!');
    process.exit(1);
  }

  if(parsed.cmd === 'watchify' || parsed.maxProcs === Infinity) return fileArgs.forEach((args) => spawnProccess(parsed.cmd, args));
  return queueingExec(parsed.cmd, fileArgs, parsed.maxProcs);
};
<|endoftext|>


<commit_before>import React from 'react'
import { render } from 'react-dom'
import { createStore, applyMiddleware } from 'redux'
import { Provider } from 'react-redux'
import thunk from 'redux-thunk'
import { createLogger } from 'redux-logger'
import reducer from './reducers'
import App from './containers/App'

// reducer
const middleware = [ thunk ]
if (process.env.NODE_ENV !== 'production') {
  middleware.push(createLogger())
}

const store = createStore(
  reducer,
  applyMiddleware(...middleware)
);

render(
  <Provider store={store}>
    <App />
  </Provider>,
  document.getElementById('root')
);
<commit_msg>applyMiddleware<commit_after>import React from 'react'
import { render } from 'react-dom'
import { createStore, applyMiddleware } from 'redux'
import { Provider } from 'react-redux'
import thunk from 'redux-thunk'
import { createLogger } from 'redux-logger'
import reducer from './reducers'
import App from './containers/App'

// reducer
const middleware = [ thunk ]
if (process.env.NODE_ENV !== 'production') {
  middleware.push(createLogger())
}

const store = createStore(
  reducer,
  // applyMiddlewareを使うことでdispatch関数をラップし、actionがreducerに到達する前にmiddlewareがキャッチできるようにする
  // http://qiita.com/pirosikick/items/d7f9e5e197a2e8aad62f
  applyMiddleware(...middleware)
);

render(
  <Provider store={store}>
    <App />
  </Provider>,
  document.getElementById('root')
);
<|endoftext|>


<commit_before>function merge(object, source) {
  if (typeof source === 'undefined' || source === null) {
    return object;
  }

  // eslint-disable-next-line no-var
  for (var v0, v1, k, keys = Object.keys(source), l = keys.length, i = 0; i < l; ++i) {
    k = keys[i], v1 = source[k];
    if (typeof v1 !== 'undefined') {
      v0 = object[k];
      if (
        typeof v1 === 'object' && v1 !== null &&
        typeof v0 === 'object' && v0 !== null
      ) {
        merge(v0, v1);
      } else {
        object[k] = v1;
      }
    }
  }

  return object;
}

export function Translation() {
  const dictionary = {};

  this.currentLocale = null;
  this.fallbackLocale = null;

  this.dictionary = () => dictionary;

  this.load = (locale, pairs) => {
    if (!(locale in dictionary)) {
      dictionary[locale] = {};
    }
    merge(dictionary[locale], pairs);
    return this;
  };

  this.loadRoot = (root) => {
    merge(dictionary, root);
    return this;
  };

  this.setLocale = (locale, dic) => {
    dictionary[locale] = dic;
    return this;
  };

  this.translate = (phrase, locale) => {
    if (!(locale in dictionary) || !(phrase in dictionary[locale])) {
      if (!this.fallbackLocale || locale === this.fallbackLocale) {
        return '';
      }

      return this.translate(phrase, this.fallbackLocale);
    }

    return dictionary[locale][phrase];
  };

  this.translateTo = locale => phrase =>
    this.translate(phrase, locale);

  this.translateCurrent = phrase =>
    this.translate(phrase, this.currentLocale || '');

  this.format = (phrase, locale, ...args) => {
    if (!(locale in dictionary) || !(phrase in dictionary[locale])) {
      if (!this.fallbackLocale || locale === this.fallbackLocale) {
        return '';
      }

      return this.format(phrase, this.fallbackLocale, ...args);
    }

    return dictionary[locale][phrase].replace(/%(\S)/g, (_, i) => {
      return args[i];
    });
  };

  this.formatTo = locale => (phrase, ...args) =>
    this.format(phrase, locale, ...args);

  this.formatCurrent = (phrase, ...args) =>
    this.format(phrase, this.currentLocale || '', ...args);
}

const t = new Translation();

export const {
  format,
  formatTo,
  formatCurrent,
  translate,
  translateTo,
  translateCurrent,
  setLocale,
  load,
  loadRoot,
  currentLocale,
  fallbackLocale
} = t;

export default t;
<commit_msg>Consider the singleton's methods exported manually deprecated<commit_after>function merge(object, source) {
  if (typeof source === 'undefined' || source === null) {
    return object;
  }

  // eslint-disable-next-line no-var
  for (var v0, v1, k, keys = Object.keys(source), l = keys.length, i = 0; i < l; ++i) {
    k = keys[i], v1 = source[k];
    if (typeof v1 !== 'undefined') {
      v0 = object[k];
      if (
        typeof v1 === 'object' && v1 !== null &&
        typeof v0 === 'object' && v0 !== null
      ) {
        merge(v0, v1);
      } else {
        object[k] = v1;
      }
    }
  }

  return object;
}

export function Translation() {
  const dictionary = {};

  this.currentLocale = null;
  this.fallbackLocale = null;

  this.dictionary = () => dictionary;

  this.load = (locale, pairs) => {
    if (!(locale in dictionary)) {
      dictionary[locale] = {};
    }
    merge(dictionary[locale], pairs);
    return this;
  };

  this.loadRoot = (root) => {
    merge(dictionary, root);
    return this;
  };

  this.setLocale = (locale, dic) => {
    dictionary[locale] = dic;
    return this;
  };

  this.translate = (phrase, locale) => {
    if (!(locale in dictionary) || !(phrase in dictionary[locale])) {
      if (!this.fallbackLocale || locale === this.fallbackLocale) {
        return '';
      }

      return this.translate(phrase, this.fallbackLocale);
    }

    return dictionary[locale][phrase];
  };

  this.translateTo = locale => phrase =>
    this.translate(phrase, locale);

  this.translateCurrent = phrase =>
    this.translate(phrase, this.currentLocale || '');

  this.format = (phrase, locale, ...args) => {
    if (!(locale in dictionary) || !(phrase in dictionary[locale])) {
      if (!this.fallbackLocale || locale === this.fallbackLocale) {
        return '';
      }

      return this.format(phrase, this.fallbackLocale, ...args);
    }

    return dictionary[locale][phrase].replace(/%(\S)/g, (_, i) => {
      return args[i];
    });
  };

  this.formatTo = locale => (phrase, ...args) =>
    this.format(phrase, locale, ...args);

  this.formatCurrent = (phrase, ...args) =>
    this.format(phrase, this.currentLocale || '', ...args);
}

const deprecated = (f) => {
  const g = function () {
    if (!this.calledBefore) {
      this.calledBefore = true;
      // eslint-disable-next-line no-console
      console.warn(
        'Deprecation warning: usage of t8on singleton\'s properties ' +
        'and methods imported manually is considered deprecated. ' +
        'All *named* exports except Translation will be removed ' +
        'in upcoming major release. Please export the singleton and call ' +
        'its methods directly, such as t.translate()'
      );
    }
    return f.apply(null, arguments);
  };

  return g;
};

const t = new Translation();

export const format = deprecated(t.format);
export const formatTo = deprecated(t.formatTo);
export const formatCurrent = deprecated(t.formatCurrent);

export const translate = deprecated(t.translate);
export const translateTo = deprecated(t.translateTo);
export const translateCurrent = deprecated(t.translateCurrent);

export const load = deprecated(t.load);
export const loadRoot = deprecated(t.loadRoot);
export const setLocale = deprecated(t.setLocale);

export const currentLocale = t.currentLocale;
export const fallbackLocale = t.fallbackLocale;

export default t;
<|endoftext|>


<commit_before>
import * as _ from 'lodash';
import $ from 'jquery';
import React from 'react';

import Autosuggest from 'react-autosuggest';

import '../styles/index.scss';

export class ReactAutosuggestGeocoder extends React.Component {
  static propTypes = {
    url: React.PropTypes.string.isRequired,
    apiKey: React.PropTypes.string.isRequired,
    fetchDelay: React.PropTypes.number.isRequired,
    onSuggestionSelected: React.PropTypes.func.isRequired,
    getSuggestionValue: React.PropTypes.func.isRequired,
    renderSuggestion: React.PropTypes.func.isRequired
  };

  static defaultProps = {
    url: "https://search.mapzen.com/v1",
    apiKey: null,
    fetchDelay: 150,
    getSuggestionValue: suggestion => suggestion.properties.label,
    renderSuggestion: suggestion => (

        {suggestion.properties.label}

    )
  };

  constructor(props) {
    super(props);

    this.state = {
      value: '',
      suggestions: [],
      selected: false
    };

    this._onSuggestionsFetchRequested = _.debounce(this.onSuggestionsFetchRequested, this.props.fetchDelay);
  }

  onChange = (event, { newValue }) => {
    this.setState({
      value: newValue,
      selected: false
    });
  };

  onSuggestionsFetchRequested = ({ value }) => {
    const url = this.props.url + "/autocomplete";
    return $.ajax({
      type: 'GET',
      url: url,
      data: {
        api_key: this.props.apiKey,
        sources: "openaddresses",
        text: value
      }
    })
    .then((data) => {
      this.setState({
        suggestions: _.uniqBy(data.features, (feature) => {
          return feature.properties.label;
        })
      });
    });
  };

  onSuggestionsClearRequested = () => {
    this.setState({
      suggestions: []
    });
  };

  onSuggestionSelected = (event, { suggestion, suggestionValue, suggestionIndex, sectionIndex, method }) => {
    const url = this.props.url + "/search";
    return $.ajax({
      type: 'GET',
      url: url,
      data: {
        api_key: this.props.apiKey,
        sources: "openaddresses",
        text: suggestionValue
      }
    })
    .then((data) => {
      this.setState({
        selected: true
      });
      return this.props.onSuggestionSelected(event, { search: data, suggestion, suggestionValue, suggestionIndex, sectionIndex, method })
    });
  };

  render() {
    const { suggestions, value } = this.state;
    const {
      inputProps,
      onSuggestionsFetchRequested,
      onSuggestionsClearRequested,
      onSuggestionSelected,
      fetchDelay,
      ...props
    } = this.props;

    return (
      <Autosuggest
        suggestions={suggestions}
        onSuggestionsFetchRequested={this._onSuggestionsFetchRequested}
        onSuggestionsClearRequested={this.onSuggestionsClearRequested}
        onSuggestionSelected={this.onSuggestionSelected}
        inputProps={_.defaults(inputProps || {}, {
          value: value,
          onChange: this.onChange
        })}
        {...props}
      />
    );
  }
}
<commit_msg>Update search text upon selection<commit_after>
import * as _ from 'lodash';
import $ from 'jquery';
import React from 'react';

import Autosuggest from 'react-autosuggest';

import '../styles/index.scss';

export class ReactAutosuggestGeocoder extends React.Component {
  static propTypes = {
    url: React.PropTypes.string.isRequired,
    apiKey: React.PropTypes.string.isRequired,
    fetchDelay: React.PropTypes.number.isRequired,
    onSuggestionSelected: React.PropTypes.func.isRequired,
    getSuggestionValue: React.PropTypes.func.isRequired,
    renderSuggestion: React.PropTypes.func.isRequired
  };

  static defaultProps = {
    url: "https://search.mapzen.com/v1",
    apiKey: null,
    fetchDelay: 150,
    getSuggestionValue: suggestion => suggestion.properties.label,
    renderSuggestion: suggestion => (

        {suggestion.properties.label}

    )
  };

  constructor(props) {
    super(props);

    this.state = {
      value: '',
      suggestions: [],
      selected: false
    };

    this._onSuggestionsFetchRequested = _.debounce(this.onSuggestionsFetchRequested, this.props.fetchDelay);
  }

  onChange = (event, { newValue }) => {
    this.setState({
      value: newValue,
      selected: false
    });
  };

  onSuggestionsFetchRequested = ({ value }) => {
    const url = this.props.url + "/autocomplete";
    return $.ajax({
      type: 'GET',
      url: url,
      data: {
        api_key: this.props.apiKey,
        sources: "openaddresses",
        text: value
      }
    })
    .then((data) => {
      this.setState({
        suggestions: _.uniqBy(data.features, (feature) => {
          return feature.properties.label;
        })
      });
    });
  };

  onSuggestionsClearRequested = () => {
    this.setState({
      suggestions: []
    });
  };

  onSuggestionSelected = (event, { suggestion, suggestionValue, suggestionIndex, sectionIndex, method }) => {
    const url = this.props.url + "/search";
    return $.ajax({
      type: 'GET',
      url: url,
      data: {
        api_key: this.props.apiKey,
        sources: "openaddresses",
        text: suggestionValue
      }
    })
    .then((data) => {
      this.setState({
        selected: true,
        value: suggestionValue
      });
      return this.props.onSuggestionSelected(event, { search: data, suggestion, suggestionValue, suggestionIndex, sectionIndex, method })
    });
  };

  render() {
    const { suggestions, value } = this.state;
    const {
      inputProps,
      onSuggestionsFetchRequested,
      onSuggestionsClearRequested,
      onSuggestionSelected,
      fetchDelay,
      ...props
    } = this.props;

    return (
      <Autosuggest
        suggestions={suggestions}
        onSuggestionsFetchRequested={this._onSuggestionsFetchRequested}
        onSuggestionsClearRequested={this.onSuggestionsClearRequested}
        onSuggestionSelected={this.onSuggestionSelected}
        inputProps={_.defaults(inputProps || {}, {
          value: value,
          onChange: this.onChange
        })}
        {...props}
      />
    );
  }
}
<|endoftext|>


<commit_before>const invariant = require('invariant');

let oldJasmineFns = {it, fit, xit, beforeEach, afterEach, beforeAll, afterAll};

function withAsync(fns) {
  return Object.keys(fns).reduce((memo, name) => {
    memo[name] = fns[name];
    memo[name].async = function(...args) {
      const callback = args.pop();
      invariant(typeof callback === 'function', `${name} must be provided a function!`);
      return (fns[name])(...args, done => {
        const promise = this::callback();
        invariant(promise && isFunction(promise.then), `${name} must return a promise!`);
        promise.then(done, done.fail);
      });
    };
    return memo;
  }, {});
}

module.exports = {
  install() {
    Object.assign(global, {...withAsync(oldJasmineFns)});
  },

  uninstall() {
    Object.assign(global, oldJasmineFns);
  }
};
<commit_msg>use a shared typeof check<commit_after>const invariant = require('invariant');

let oldJasmineFns = {it, fit, xit, beforeEach, afterEach, beforeAll, afterAll};

function isFunction(obj) {
  return typeof obj === 'function';
}

function withAsync(fns) {
  return Object.keys(fns).reduce((memo, name) => {
    memo[name] = fns[name];
    memo[name].async = function(...args) {
      const callback = args.pop();
      invariant(isFunction(callback), `${name} must be provided a function!`);
      return (fns[name])(...args, done => {
        const promise = this::callback();
        invariant(promise && isFunction(promise.then), `${name} must return a promise!`);
        promise.then(done, done.fail);
      });
    };
    return memo;
  }, {});
}

module.exports = {
  install() {
    Object.assign(global, {...withAsync(oldJasmineFns)});
  },

  uninstall() {
    Object.assign(global, oldJasmineFns);
  }
};
<|endoftext|>


<commit_before>// @flow
import React from 'react';
import { CustomFieldProps } from './types';
import ReduxFormFieldWrapper from './ReduxFormFieldWrapper';
import { Text, TextArea, Select, Checkbox, Radio } from './customSemanticInputs';

export const TextField = (props: CustomFieldProps) => (
  <ReduxFormFieldWrapper
    {...props}
    component={Text}
  />
);

export const TextAreaField = (props: CustomFieldProps) => (
  <ReduxFormFieldWrapper
    {...props}
    component={TextArea}
  />
);

export const SelectField = (props: CustomFieldProps) => (
  <ReduxFormFieldWrapper
    {...props}
    component={Select}
  />
);

export const MultiSelectField = (props: CustomFieldProps) => (
  <ReduxFormFieldWrapper
    {...props}
    search
    selection
    multiple
    component={Select}
    onBlur={(e, data) => {
      props.input.onChange(data.value);
      if (props.onBlur) {
        props.onBlur(e, data);
      }
    }}
  />
);

export const CheckboxField = (props: CustomFieldProps) => (
  <ReduxFormFieldWrapper
    {...props}
    component={Checkbox}
  />
);

export const ToggleField = (props: CustomFieldProps) => (
  <ReduxFormFieldWrapper
    {...props}
    toggle
    component={Checkbox}
  />
);

export const SliderField = (props: CustomFieldProps) => (
  <ReduxFormFieldWrapper
    {...props}
    slider
    component={Checkbox}
  />
);

export const RadioField = (props: CustomFieldProps) => (
  <ReduxFormFieldWrapper
    {...props}
    component={Radio}
  />
);
<commit_msg>Add a small comment about why we do the onChange inside the onBlur for multi select<commit_after>// @flow
import React from 'react';
import { CustomFieldProps } from './types';
import ReduxFormFieldWrapper from './ReduxFormFieldWrapper';
import { Text, TextArea, Select, Checkbox, Radio } from './customSemanticInputs';

export const TextField = (props: CustomFieldProps) => (
  <ReduxFormFieldWrapper
    {...props}
    component={Text}
  />
);

export const TextAreaField = (props: CustomFieldProps) => (
  <ReduxFormFieldWrapper
    {...props}
    component={TextArea}
  />
);

export const SelectField = (props: CustomFieldProps) => (
  <ReduxFormFieldWrapper
    {...props}
    component={Select}
  />
);

export const MultiSelectField = (props: CustomFieldProps) => (
  <ReduxFormFieldWrapper
    {...props}
    search
    selection
    multiple
    component={Select}
    onBlur={(e, data) => {
      // In the multi select field, we need to trigger on an onChange event to persist
      // the values that have been selected, since the onChange is not triggered while
      // the select box is open
      props.input.onChange(data.value);
      if (props.onBlur) {
        props.onBlur(e, data);
      }
    }}
  />
);

export const CheckboxField = (props: CustomFieldProps) => (
  <ReduxFormFieldWrapper
    {...props}
    component={Checkbox}
  />
);

export const ToggleField = (props: CustomFieldProps) => (
  <ReduxFormFieldWrapper
    {...props}
    toggle
    component={Checkbox}
  />
);

export const SliderField = (props: CustomFieldProps) => (
  <ReduxFormFieldWrapper
    {...props}
    slider
    component={Checkbox}
  />
);

export const RadioField = (props: CustomFieldProps) => (
  <ReduxFormFieldWrapper
    {...props}
    component={Radio}
  />
);
<|endoftext|>


<commit_before>'use strict';

var express = require('express');
var bodyParser = require('body-parser');
var slack = require('slack-notify')(process.env.SLACK_HOOK_URL);

var IMDb = require('./imdb.js');
var RottenTomatoes = require('./rottentomatoes.js');
var rt = new RottenTomatoes(process.env.RT_API_KEY);

var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

app.post('/', function (req, res) {
  var q = req.body.text;
  // Search RottenTomatoes
  rt.search(q, function(rtData) {
    if (!rtData) {
      res.status(404).send('Movie not found');
      return;
    }

    // Search IMDb
    var imdbCallback = function(imdbData) {

      // Build Slack response
      var fields = [{
        title: 'Rotten Tomatoes Rating',
        value: '<' + rtData.links.alternate + '|' + (rtData.ratings.critics_score >= 0 ? rtData.ratings.critics_score + '%' : '_No rating_') + '>',
        short: true
      }, {
        title: 'IMDb Rating',
        value: (imdbData ? '<http://www.imdb.com/title/tt' + imdbData.imdbId + '|' + (imdbData.rating ? imdbData.rating + ' (' + imdbData.votes + ' votes)' : '_No rating_') + '>' : '_Not found_'),
        short: true
      }];
      if ((imdbData && imdbData.year) || rtData.year) {
        fields.push({
          title: 'Year',
          value: (imdbData && imdbData.year ? imdbData.year : rtData.year),
          short: true
        });
      }
      if ((imdbData && imdbData.runtime) || rtData.runtime) {
        fields.push({
          title: 'Runtime',
          value: ((imdbData && imdbData.runtime) ? imdbData.runtime : rtData.runtime + ' min'),
          short: true
        });
      }

      // Send to Slack
      slack.send({
        username: 'moviebot',
        icon_emoji: ':movie_camera:',
        channel: req.body.channel_id,
        text: '_' + req.body.command + ' ' + req.body.text + '_',
        attachments: [{
          title: rtData.title,
          // title_link: rtData.links.alternate,
          color: '#FDEE00',
          image_url: (rtData.posters && rtData.posters.original !== 'http://d3biamo577v4eu.cloudfront.net/static/images/redesign/poster_default_thumb.gif' ? rtData.posters.original : null),
          fields: fields
        }]
      });

      res.send();
    };

    var imdbId = (rtData.alternate_ids ? rtData.alternate_ids.imdb : null);
    if (imdbId) {
      IMDb.search(imdbId, imdbCallback);
    } else {
      imdbCallback(null);
    }
  });
});

var port = process.env.PORT || 3000;
var server = app.listen(port, function () {
  var host = server.address().address;
  var port = server.address().port;
  console.log('App listening at http://%s:%s', host, port);
});<commit_msg>Sanitize response (II)<commit_after>'use strict';

var express = require('express');
var bodyParser = require('body-parser');
var slack = require('slack-notify')(process.env.SLACK_HOOK_URL);

var IMDb = require('./imdb.js');
var RottenTomatoes = require('./rottentomatoes.js');
var rt = new RottenTomatoes(process.env.RT_API_KEY);

var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

app.post('/', function (req, res) {
  var q = req.body.text;
  // Search RottenTomatoes
  rt.search(q, function(rtData) {
    if (!rtData) {
      res.status(404).send('Movie not found');
      return;
    }

    // Search IMDb
    var imdbCallback = function(imdbData) {

      // Build Slack response
      var fields = [{
        title: 'Rotten Tomatoes Rating',
        value: '<' + rtData.links.alternate + '|' + (rtData.ratings.critics_score >= 0 ? rtData.ratings.critics_score + '%' : 'No rating') + '>',
        short: true
      }, {
        title: 'IMDb Rating',
        value: (imdbData ? '<http://www.imdb.com/title/tt' + imdbData.imdbId + '|' + (imdbData.rating ? imdbData.rating + ' (' + imdbData.votes + ' votes)' : 'No rating') + '>' : 'Not found'),
        short: true
      }];
      if ((imdbData && imdbData.year) || rtData.year) {
        fields.push({
          title: 'Year',
          value: (imdbData && imdbData.year ? imdbData.year : rtData.year),
          short: true
        });
      }
      if ((imdbData && imdbData.runtime) || rtData.runtime) {
        fields.push({
          title: 'Runtime',
          value: ((imdbData && imdbData.runtime) ? imdbData.runtime : rtData.runtime + ' min'),
          short: true
        });
      }

      // Send to Slack
      slack.send({
        username: 'moviebot',
        icon_emoji: ':movie_camera:',
        channel: req.body.channel_id,
        text: '_' + req.body.command + ' ' + req.body.text + '_',
        attachments: [{
          title: rtData.title,
          // title_link: rtData.links.alternate,
          color: '#FDEE00',
          image_url: (rtData.posters && rtData.posters.original !== 'http://d3biamo577v4eu.cloudfront.net/static/images/redesign/poster_default_thumb.gif' ? rtData.posters.original : null),
          fields: fields
        }]
      });

      res.send();
    };

    var imdbId = (rtData.alternate_ids ? rtData.alternate_ids.imdb : null);
    if (imdbId) {
      IMDb.search(imdbId, imdbCallback);
    } else {
      imdbCallback(null);
    }
  });
});

var port = process.env.PORT || 3000;
var server = app.listen(port, function () {
  var host = server.address().address;
  var port = server.address().port;
  console.log('App listening at http://%s:%s', host, port);
});<|endoftext|>


<commit_before>// @flow
/* eslint-disable no-undef */

export type Effect<Action, Model> = {
  type: 'Wait',
  args: any[],
  fn: (...args: any[]) => Promise<any>,
} | {
  type: 'Call',
  args: any[],
  fn: (...args: any[]) => Generator<Effect<Action, Model>, any, any>,
} | {
  type: 'Impure',
  args: any[],
  fn: (...args: any[]) => any,
} | {
  type: 'All',
  ships: Generator<Effect<Action, Model>, any, any>[],
} | {
  type: 'Dispatch',
  action: Action,
} | {
  type: 'GetState',
};

export type t<Action, Model, A> = Generator<Effect<Action, Model>, A, any>;

function run<Action, Model, A>(
  dispatch: (action: Action) => void | Promise<void>,
  getState: () => Model,
  ship: t<Action, Model, A>,
  answer?: any)
  : Promise<A> {
  const result = ship.next(answer);
  if (result.done) {
    return Promise.resolve(result.value);
  }
  switch (result.value.type) {
  case 'Wait':
    return result.value.fn(...result.value.args).then(newAnswer =>
      run(dispatch, getState, ship, newAnswer)
    );
  case 'Call':
    return run(dispatch, getState, result.value.fn(...result.value.args)).then(newAnswer =>
      run(dispatch, getState, ship, newAnswer)
    );
  case 'Impure': {
    const newAnswer = result.value.fn(...result.value.args);
    return run(dispatch, getState, ship, newAnswer);
  }
  case 'All':
    return Promise.all(result.value.ships.map(currentShip =>
      run(dispatch, getState, currentShip))
    ).then(newAnswer =>
      run(dispatch, getState, ship, newAnswer)
    );
  case 'Dispatch':
    return Promise.resolve(dispatch(result.value.action)).then(() =>
      run(dispatch, getState, ship)
    );
  case 'GetState': {
    const newAnswer = getState();
    return run(dispatch, getState, ship, newAnswer);
  }
  default:
    return result.value;
  }
}

type ReduxStore<Action, Model> = {
  dispatch: (action: Action) => void | Promise<void>,
  getState: () => Model,
};

export function middleware<Action, Model>(
  actionToShip: (action: Action) => t<Action, Model, void>) {
  // eslint-disable-next-line no-unused-vars
  return (store: ReduxStore<Action, Model>) => (next: mixed) => (action: Action): Promise<void> => {
    const ship = actionToShip(action);
    return run(store.dispatch, store.getState, ship);
  };
}

export const wait:
  (<Action, Model, B>(
    promise: Promise<B>
  ) => t<Action, Model, B>) &
  (<Action, Model, A1, B>(
    fn: (arg1: A1) => Promise<B>,
    arg1: A1
  ) => t<Action, Model, B>) &
  (<Action, Model, A1, A2, B>(
    fn: (arg1: A1, arg2: A2) => Promise<B>,
    arg1: A1, arg2: A2
  ) => t<Action, Model, B>) &
  (<Action, Model, A1, A2, A3, B>(
    fn: (arg1: A1, arg2: A2, arg3: A3) => Promise<B>,
    arg1: A1, arg2: A2, arg3: A3
  ) => t<Action, Model, B>) &
  (<Action, Model, A1, A2, A3, A4, B>(
    fn: (arg1: A1, arg2: A2, arg3: A3, arg4: A4) => Promise<B>,
    arg1: A1, arg2: A2, arg3: A3, arg4: A4
  ) => t<Action, Model, B>) =
  function* (fn: any, ...args: any[]) {
    const result = yield {
      type: 'Wait',
      args,
      fn: args.length === 0 ? () => fn : fn,
    };
    return (result: any);
  };

export const call:
  (<Action, Model, B>(
    ship: t<Action, Model, B>
  ) => t<Action, Model, B>) &
  (<Action, Model, A1, B>(
    fn: (arg1: A1) => t<Action, Model, B>,
    arg1: A1
  ) => t<Action, Model, B>) &
  (<Action, Model, A1, A2, B>(
    fn: (arg1: A1, arg2: A2) => t<Action, Model, B>,
    arg1: A1, arg2: A2
  ) => t<Action, Model, B>) &
  (<Action, Model, A1, A2, A3, B>(
    fn: (arg1: A1, arg2: A2, arg3: A3) => t<Action, Model, B>,
    arg1: A1, arg2: A2, arg3: A3
  ) => t<Action, Model, B>) &
  (<Action, Model, A1, A2, A3, A4, B>(
    fn: (arg1: A1, arg2: A2, arg3: A3, arg4: A4) => t<Action, Model, B>,
    arg1: A1, arg2: A2, arg3: A3, arg4: A4
  ) => t<Action, Model, B>) =
  function* (fn: any, ...args: any[]) {
    const result = yield {
      type: 'Call',
      args,
      fn: args.length === 0 ? () => fn : fn,
    };
    return (result: any);
  };

export const impure:
  (<Action, Model, B>(
    value: B
  ) => t<Action, Model, B>) &
  (<Action, Model, A1, B>(
    fn: (arg1: A1) => B,
    arg1: A1
  ) => t<Action, Model, B>) &
  (<Action, Model, A1, A2, B>(
    fn: (arg1: A1, arg2: A2) => B,
    arg1: A1, arg2: A2
  ) => t<Action, Model, B>) &
  (<Action, Model, A1, A2, A3, B>(
    fn: (arg1: A1, arg2: A2, arg3: A3) => B,
    arg1: A1, arg2: A2, arg3: A3
  ) => t<Action, Model, B>) &
  (<Action, Model, A1, A2, A3, A4, B>(
    fn: (arg1: A1, arg2: A2, arg3: A3, arg4: A4) => B,
    arg1: A1, arg2: A2, arg3: A3, arg4: A4
  ) => t<Action, Model, B>) =
  function* (fn: any, ...args: any[]) {
    const result = yield {
      type: 'Call',
      args,
      fn: args.length === 0 ? () => fn : fn,
    };
    return (result: any);
  };

export const all:
  (<Action, Model, A>(
    ...ships: t<Action, Model, A>[]
  ) => t<Action, Model, A[]>) &
  (<Action, Model, A1, A2>(
    ship1: t<Action, Model, A1>,
    ship2: t<Action, Model, A2>
  ) => t<Action, Model, [A1, A2]>) &
  (<Action, Model, A1, A2, A3>(
    ship1: t<Action, Model, A1>,
    ship2: t<Action, Model, A2>,
    ship3: t<Action, Model, A3>
  ) => t<Action, Model, [A1, A2, A3]>) &
  (<Action, Model, A1, A2, A3, A4>(
    ship1: t<Action, Model, A1>,
    ship2: t<Action, Model, A2>,
    ship3: t<Action, Model, A3>,
    ship4: t<Action, Model, A4>
  ) => t<Action, Model, [A1, A2, A3, A4]>) =
  function* (...ships: any[]) {
    const result = yield {
      type: 'All',
      ships,
    };
    return (result: any);
  };

export function* dispatch<Action, Model>(action: Action): t<Action, Model, void> {
  yield {
    type: 'Dispatch',
    action,
  };
}

export function* getState<Action, Model>(): t<Action, Model, Model> {
  const model = yield {
    type: 'GetState',
  };
  return (model: any);
}
<commit_msg>Add map and delay<commit_after>// @flow
/* eslint-disable no-undef */

export type Effect<Action, Model> = {
  type: 'Wait',
  args: any[],
  fn: (...args: any[]) => Promise<any>,
} | {
  type: 'Call',
  args: any[],
  fn: (...args: any[]) => Generator<Effect<Action, Model>, any, any>,
} | {
  type: 'Impure',
  args: any[],
  fn: (...args: any[]) => any,
} | {
  type: 'All',
  ships: Generator<Effect<Action, Model>, any, any>[],
} | {
  type: 'Dispatch',
  action: Action,
} | {
  type: 'GetState',
};

export type t<Action, Model, A> = Generator<Effect<Action, Model>, A, any>;

function run<Action, Model, A>(
  dispatch: (action: Action) => void | Promise<void>,
  getState: () => Model,
  ship: t<Action, Model, A>,
  answer?: any)
  : Promise<A> {
  const result = ship.next(answer);
  if (result.done) {
    return Promise.resolve(result.value);
  }
  switch (result.value.type) {
  case 'Wait':
    return result.value.fn(...result.value.args).then(newAnswer =>
      run(dispatch, getState, ship, newAnswer)
    );
  case 'Call':
    return run(dispatch, getState, result.value.fn(...result.value.args)).then(newAnswer =>
      run(dispatch, getState, ship, newAnswer)
    );
  case 'Impure': {
    const newAnswer = result.value.fn(...result.value.args);
    return run(dispatch, getState, ship, newAnswer);
  }
  case 'All':
    return Promise.all(result.value.ships.map(currentShip =>
      run(dispatch, getState, currentShip))
    ).then(newAnswer =>
      run(dispatch, getState, ship, newAnswer)
    );
  case 'Dispatch':
    return Promise.resolve(dispatch(result.value.action)).then(() =>
      run(dispatch, getState, ship)
    );
  case 'GetState': {
    const newAnswer = getState();
    return run(dispatch, getState, ship, newAnswer);
  }
  default:
    return result.value;
  }
}

type ReduxStore<Action, Model> = {
  dispatch: (action: Action) => void | Promise<void>,
  getState: () => Model,
};

type ReduxMiddleware<Action, Model> =
  (store: ReduxStore<Action, Model>) =>
  (next: (action: Action) => any) =>
  (action: Action) =>
  any;

export function middleware<Action, Model>(
  actionToShip: (action: Action) => ?t<Action, Model, void>
): ReduxMiddleware<Action, Model> {
  return store => next => action => {
    const ship = actionToShip(action);
    if (ship) {
      return run(store.dispatch, store.getState, ship);
    }
    return next(action);
  };
}

function* untypedWait(fn: any, ...args: any[]) {
  const result = yield {
    type: 'Wait',
    args,
    fn: args.length === 0 ? () => fn : fn,
  };
  return (result: any);
}

export const wait:
  (<Action, Model, B>(
    promise: Promise<B>
  ) => t<Action, Model, B>) &
  (<Action, Model, A1, B>(
    fn: (arg1: A1) => Promise<B>,
    arg1: A1
  ) => t<Action, Model, B>) &
  (<Action, Model, A1, A2, B>(
    fn: (arg1: A1, arg2: A2) => Promise<B>,
    arg1: A1, arg2: A2
  ) => t<Action, Model, B>) &
  (<Action, Model, A1, A2, A3, B>(
    fn: (arg1: A1, arg2: A2, arg3: A3) => Promise<B>,
    arg1: A1, arg2: A2, arg3: A3
  ) => t<Action, Model, B>) &
  (<Action, Model, A1, A2, A3, A4, B>(
    fn: (arg1: A1, arg2: A2, arg3: A3, arg4: A4) => Promise<B>,
    arg1: A1, arg2: A2, arg3: A3, arg4: A4
  ) => t<Action, Model, B>) =
  untypedWait;

function* untypedCall(fn: any, ...args: any[]) {
  const result = yield {
    type: 'Call',
    args,
    fn: args.length === 0 ? () => fn : fn,
  };
  return (result: any);
}

export const call:
  (<Action, Model, B>(
    ship: t<Action, Model, B>
  ) => t<Action, Model, B>) &
  (<Action, Model, A1, B>(
    fn: (arg1: A1) => t<Action, Model, B>,
    arg1: A1
  ) => t<Action, Model, B>) &
  (<Action, Model, A1, A2, B>(
    fn: (arg1: A1, arg2: A2) => t<Action, Model, B>,
    arg1: A1, arg2: A2
  ) => t<Action, Model, B>) &
  (<Action, Model, A1, A2, A3, B>(
    fn: (arg1: A1, arg2: A2, arg3: A3) => t<Action, Model, B>,
    arg1: A1, arg2: A2, arg3: A3
  ) => t<Action, Model, B>) &
  (<Action, Model, A1, A2, A3, A4, B>(
    fn: (arg1: A1, arg2: A2, arg3: A3, arg4: A4) => t<Action, Model, B>,
    arg1: A1, arg2: A2, arg3: A3, arg4: A4
  ) => t<Action, Model, B>) =
  untypedCall;

function* untypedImpure(fn: any, ...args: any[]) {
  const result = yield {
    type: 'Impure',
    args,
    fn: args.length === 0 ? () => fn : fn,
  };
  return (result: any);
}

export const impure:
  (<Action, Model, B>(
    value: B
  ) => t<Action, Model, B>) &
  (<Action, Model, A1, B>(
    fn: (arg1: A1) => B,
    arg1: A1
  ) => t<Action, Model, B>) &
  (<Action, Model, A1, A2, B>(
    fn: (arg1: A1, arg2: A2) => B,
    arg1: A1, arg2: A2
  ) => t<Action, Model, B>) &
  (<Action, Model, A1, A2, A3, B>(
    fn: (arg1: A1, arg2: A2, arg3: A3) => B,
    arg1: A1, arg2: A2, arg3: A3
  ) => t<Action, Model, B>) &
  (<Action, Model, A1, A2, A3, A4, B>(
    fn: (arg1: A1, arg2: A2, arg3: A3, arg4: A4) => B,
    arg1: A1, arg2: A2, arg3: A3, arg4: A4
  ) => t<Action, Model, B>) =
  untypedImpure;

function* untypedAll(...ships: any[]) {
  const result = yield {
    type: 'All',
    ships,
  };
  return (result: any);
}

export const all:
  (<Action, Model, A>(
    ...ships: t<Action, Model, A>[]
  ) => t<Action, Model, A[]>) &
  (<Action, Model, A1, A2>(
    ship1: t<Action, Model, A1>,
    ship2: t<Action, Model, A2>
  ) => t<Action, Model, [A1, A2]>) &
  (<Action, Model, A1, A2, A3>(
    ship1: t<Action, Model, A1>,
    ship2: t<Action, Model, A2>,
    ship3: t<Action, Model, A3>
  ) => t<Action, Model, [A1, A2, A3]>) &
  (<Action, Model, A1, A2, A3, A4>(
    ship1: t<Action, Model, A1>,
    ship2: t<Action, Model, A2>,
    ship3: t<Action, Model, A3>,
    ship4: t<Action, Model, A4>
  ) => t<Action, Model, [A1, A2, A3, A4]>) =
  untypedAll;

export function* dispatch<Action, Model>(action: Action): t<Action, Model, void> {
  yield {
    type: 'Dispatch',
    action,
  };
}

export function* getState<Action, Model>(): t<Action, Model, Model> {
  const model = yield {
    type: 'GetState',
  };
  return (model: any);
}

function* mapWithAnswer<Action1, Model1, Action2, Model2, A>(
  ship: t<Action1, Model1, A>,
  mapAction: (action1: Action1) => Action2,
  mapState: (state2: Model2) => Model1,
  answer?: any
): t<Action2, Model2, A> {
  console.debug('map ship entry', ship);
  const result = ship.next(answer);
  if (result.done) {
    return (result.value: any);
  }
  switch (result.value.type) {
  case 'Wait': {
    const newAnswer = yield result.value;
    return yield* mapWithAnswer(ship, mapAction, mapState, newAnswer);
  }
  case 'Impure': {
    const newAnswer = yield result.value;
    console.debug('map ship impure', ship);
    return yield* mapWithAnswer(ship, mapAction, mapState, newAnswer);
  }
  case 'Call': {
    const {value} = result;
    const newAnswer = yield {
      type: 'Call',
      args: value.args,
      fn: (...args) => mapWithAnswer(value.fn(args), mapAction, mapState),
    };
    return yield* mapWithAnswer(ship, mapAction, mapState, newAnswer);
  }
  case 'All': {
    const newAnswer = yield {
      type: 'All',
      ships: result.value.ships.map((currentShip) =>
        mapWithAnswer(currentShip, mapAction, mapState)),
    };
    return yield* mapWithAnswer(ship, mapAction, mapState, newAnswer);
  }
  case 'Dispatch':
    yield {
      type: 'Dispatch',
      action: mapAction(result.value.action),
    };
    return yield* mapWithAnswer(ship, mapAction, mapState);
  case 'GetState': {
    const newAnswer: any = yield {
      type: 'GetState',
    };
    return yield* mapWithAnswer(ship, mapAction, mapState, mapState(newAnswer));
  }
  default:
    return result.value;
  }
}

export function map<Action1, Model1, Action2, Model2, A>(
  ship: ?t<Action1, Model1, A>,
  mapAction: (action1: Action1) => Action2,
  mapState: (state2: Model2) => Model1
): ?t<Action2, Model2, A> {
  return ship && mapWithAnswer(ship, mapAction, mapState);
}

function delayPromise(ms: number): Promise<void> {
  return new Promise((resolve) => setTimeout(resolve, ms));
}

export function* delay<Action, Model>(ms: number): t<Action, Model, void> {
  yield* wait(delayPromise, ms);
}
<|endoftext|>


<commit_before>function traverseRenderedChildren(internalInstance, callback, argument) {
  callback(internalInstance, argument)

  if (internalInstance._renderedComponent) {
    traverseRenderedChildren(
      internalInstance._renderedComponent,
      callback,
      argument,
    )
  } else {
    for (const key in internalInstance._renderedChildren) {
      if (internalInstance._renderedChildren.hasOwnProperty(key)) {
        traverseRenderedChildren(
          internalInstance._renderedChildren[key],
          callback,
          argument,
        )
      }
    }
  }
}

function setPendingForceUpdate(internalInstance, shouldUpdate) {
  if (
    internalInstance._pendingForceUpdate === false &&
    shouldUpdate(internalInstance)
  ) {
    internalInstance._pendingForceUpdate = true
  }
}

function forceUpdateIfPending(internalInstance, onUpdate) {
  if (internalInstance._pendingForceUpdate === true) {
    const publicInstance = internalInstance._instance
    const { updater } = publicInstance

    if (typeof publicInstance.forceUpdate === 'function') {
      publicInstance.forceUpdate()
    } else if (updater && typeof updater.enqueueForceUpdate === 'function') {
      updater.enqueueForceUpdate(publicInstance)
    }
    onUpdate(internalInstance)
  }
}

function deepForceUpdateStack(instance, shouldUpdate, onUpdate) {
  const internalInstance = instance._reactInternalInstance
  traverseRenderedChildren(
    internalInstance,
    setPendingForceUpdate,
    shouldUpdate,
  )
  traverseRenderedChildren(internalInstance, forceUpdateIfPending, onUpdate)
}

export default function deepForceUpdate(
  instance,
  shouldUpdate = () => true,
  onUpdate = () => {},
) {
  const root = instance._reactInternalFiber || instance._reactInternalInstance
  if (typeof root.tag !== 'number') {
    // Traverse stack-based React tree.
    return deepForceUpdateStack(instance, shouldUpdate, onUpdate)
  }

  let node = root
  while (true) {
    if (node.stateNode !== null && typeof node.type === 'function' && shouldUpdate(node)) {
      const publicInstance = node.stateNode
      const { updater } = publicInstance
      if (typeof publicInstance.forceUpdate === 'function') {
        publicInstance.forceUpdate()
      } else if (updater && typeof updater.enqueueForceUpdate === 'function') {
        updater.enqueueForceUpdate(publicInstance)
      }
      onUpdate(node)
    }
    if (node.child) {
      node.child.return = node
      node = node.child
      continue
    }
    if (node === root) {
      return undefined
    }
    while (!node.sibling) {
      if (!node.return || node.return === root) {
        return undefined
      }
      node = node.return
    }
    node.sibling.return = node.return
    node = node.sibling
  }
}
<commit_msg>Revert "Revert "Disable shouldUpdate/onUpdate on master""<commit_after>function traverseRenderedChildren(internalInstance, callback, argument) {
  callback(internalInstance, argument)

  if (internalInstance._renderedComponent) {
    traverseRenderedChildren(
      internalInstance._renderedComponent,
      callback,
      argument,
    )
  } else {
    for (const key in internalInstance._renderedChildren) {
      if (internalInstance._renderedChildren.hasOwnProperty(key)) {
        traverseRenderedChildren(
          internalInstance._renderedChildren[key],
          callback,
          argument,
        )
      }
    }
  }
}

function setPendingForceUpdate(internalInstance, shouldUpdate) {
  if (
    internalInstance._pendingForceUpdate === false &&
    shouldUpdate(internalInstance)
  ) {
    internalInstance._pendingForceUpdate = true
  }
}

function forceUpdateIfPending(internalInstance, onUpdate) {
  if (internalInstance._pendingForceUpdate === true) {
    const publicInstance = internalInstance._instance
    const { updater } = publicInstance

    if (typeof publicInstance.forceUpdate === 'function') {
      publicInstance.forceUpdate()
    } else if (updater && typeof updater.enqueueForceUpdate === 'function') {
      updater.enqueueForceUpdate(publicInstance)
    }
    onUpdate(internalInstance)
  }
}

function deepForceUpdateStack(instance, shouldUpdate, onUpdate) {
  const internalInstance = instance._reactInternalInstance
  traverseRenderedChildren(
    internalInstance,
    setPendingForceUpdate,
    shouldUpdate,
  )
  traverseRenderedChildren(internalInstance, forceUpdateIfPending, onUpdate)
}

export default function deepForceUpdate(
  instance,
) {
  // TODO: this is temporarily disabled because it's not in 2.x release line.
  // See https://github.com/gaearon/react-deep-force-update/issues/8
  let shouldUpdate = () => true;
  let onUpdate = () => {};

  const root = instance._reactInternalFiber || instance._reactInternalInstance
  if (typeof root.tag !== 'number') {
    // Traverse stack-based React tree.
    return deepForceUpdateStack(instance, shouldUpdate, onUpdate)
  }

  let node = root
  while (true) {
    if (node.stateNode !== null && typeof node.type === 'function' && shouldUpdate(node)) {
      const publicInstance = node.stateNode
      const { updater } = publicInstance
      if (typeof publicInstance.forceUpdate === 'function') {
        publicInstance.forceUpdate()
      } else if (updater && typeof updater.enqueueForceUpdate === 'function') {
        updater.enqueueForceUpdate(publicInstance)
      }
      onUpdate(node)
    }
    if (node.child) {
      node.child.return = node
      node = node.child
      continue
    }
    if (node === root) {
      return undefined
    }
    while (!node.sibling) {
      if (!node.return || node.return === root) {
        return undefined
      }
      node = node.return
    }
    node.sibling.return = node.return
    node = node.sibling
  }
}
<|endoftext|>


<commit_before>#!/usr/bin/env node

const prompt = require('prompt')
const fs = require('fs')
const os = require('os')
const updateNotifier = require('update-notifier')
const pkg = require('../package.json')
const Session = require('../lib/session')
const siding = require('../lib/siding')

prompt.colors = false

const userDataFolder = `${os.homedir()}/.sincding`

data = (data = {}) => {
  console.log('Let\'s update your user data')
  if (data !== {}) {
    console.log(
      'For each prompt the value in () is the current one\n Press enter if you don\'t want to change it'
    )
  }
  const schema = {
    properties: {
      username: {
        pattern: /^[a-zA-Z\d]+$/,
        message: 'Username without @uc',
        required: true,
        default: data.username || ''
      },
      password: {
        required: true,
        hidden: true,
        replace: '*'
      },
      path: {
        required: true,
        default: data.path || '',
        conform: path => {
          if (!fs.existsSync(path)) {
            console.log('The provided path doesn\'t exist')
            return false
          }
          return true
        }
      },
      ignore: {
        pattern: /^[a-zA-Z\d ]+$/,
        message: 'Course acronyms separated by a space',
        default: (data.ignore || []).join(' ')
      }
    }
  }
  prompt.start()
  const saveData = (err, result) => {
    const data = Object.assign({}, result, {
      ignore: result.ignore.split(' ').map(a => a.toUpperCase())
    })
    if (!fs.existsSync(`${userDataFolder}`)) {
      fs.mkdirSync(`${userDataFolder}`)
    }
    const path = `${userDataFolder}/data.json`
    const dataJson = JSON.stringify(data)
    fs.writeFile(path, dataJson, 'utf8', run)
    console.log('Updated user data')
  }
  prompt.get(schema, saveData)
}

sync = data => {
  const session = new Session(data.username, data.password)
  siding.coursesList(session, data.ignore).then(courses => {
    console.log('\nFound courses')
    console.log(courses.map(c => c.path()))
    Promise.all(courses.map(course => course.scrap()))
      .then(courses => {
        console.log('\nFound:')
        const found = courses.map(c => ({
          name: c.name,
          folders: Object.keys(c.folders).length,
          files: Object.keys(c.files).length
        }))
        console.log(found)
        console.log('\nDownload:')
        const downloads = courses.map(c => ({
          name: c.name,
          folders: Object.keys(c.folders)
            .filter(id => c.folders[id].shouldCreate(data.path))
            .map(id => c.folders[id]),
          files: Object.keys(c.files)
            .filter(id => c.files[id].shouldDownload(data.path))
            .map(id => c.files[id])
        }))
        const downloadNumbers = downloads.map(download => ({
          name: download.name,
          folders: download.folders.length,
          files: download.files.length
        }))
        console.log(downloadNumbers)
        console.log('\nCreating missing folders...')
        courses.forEach(course => course.createFolder(data.path))
        downloads.forEach(d => d.folders.forEach(f => f.create(data.path)))
        console.log('\nStarting downloads, this may take a while...')
        const files = downloads
          .map(download => download.files)
          .reduce((total, arr) => total.concat(arr))
        Promise.all(files.map(file => file.download(data.path))).then(() =>
          console.log('\nFinished downloading!'))
      })
      .catch(error)
  })
}

exit = () => {
  console.log('Terminated sincding')
}

error = err => {
  const errorMessage = `
    --- Had an error ---
    ${error}

    --- Please report it to https://github.com/open-source-uc/sincding/issues
  `
  console.log(errorMessage)
}

options = {
  data: data,
  sync: sync,
  exit: exit
}

optionsDescriptions = {
  data: 'Update your user data',
  sync: 'Download sincding files',
  exit: 'Exit sincding'
}

run = () => {
  console.log('')
  // Load user data
  const userData = require(`${userDataFolder}/data.json`) || {}
  if (userData === {}) {
    data(userData)
  }
  // Show user data
  console.log('Current user data')
  console.log(`user: ${userData.username}`)
  console.log(`path: ${userData.path}`)
  console.log(`ignore: ${userData.ignore.join(' ')}`)
  console.log('')
  // If a command was supplied in the call, execute it
  const commandLine = options[process.argv[2]]
  if (commandLine) {
    console.log(`Executing \'${process.argv[2]}\' command`)
    process.argv[2] = ''
    return commandLine(userData)
  }
  // Show available commands
  console.log('Commands:')
  Object.keys(options).forEach(key => {
    console.log(` - ${key}: ${optionsDescriptions[key]}`)
  })
  // Prompt user for command
  prompt.start()
  runCommand = (err, result) => {
    if (!result || err) {
      console.log('\n')
      return exit()
    }
    const command = options[result.command]
    if (!command) {
      console.log('Not a valid command')
      return run()
    }
    // Execute selected command
    console.log(`Executing \'${result.command}\' command`)
    options[result.command](userData)
  }
  prompt.get(['command'], runCommand)
}

updateNotifier({pkg}).notify()
console.log('Welcome to sincding!')
console.log(`Version ${pkg.version}`)
run()
<commit_msg>Data update message<commit_after>#!/usr/bin/env node

const prompt = require('prompt')
const fs = require('fs')
const os = require('os')
const updateNotifier = require('update-notifier')
const pkg = require('../package.json')
const Session = require('../lib/session')
const siding = require('../lib/siding')

prompt.colors = false

const userDataFolder = `${os.homedir()}/.sincding`

data = (data = {}) => {
  console.log('Let\'s update your user data')
  if (data !== {}) {
    console.log(
      ' For each prompt the value in () is the current one\n Press enter if you don\'t want to change it'
    )
  }
  const schema = {
    properties: {
      username: {
        pattern: /^[a-zA-Z\d]+$/,
        message: 'Username without @uc',
        required: true,
        default: data.username || ''
      },
      password: {
        required: true,
        hidden: true,
        replace: '*'
      },
      path: {
        required: true,
        default: data.path || '',
        conform: path => {
          if (!fs.existsSync(path)) {
            console.log('The provided path doesn\'t exist')
            return false
          }
          return true
        }
      },
      ignore: {
        pattern: /^[a-zA-Z\d ]+$/,
        message: 'Course acronyms separated by a space',
        default: (data.ignore || []).join(' ')
      }
    }
  }
  prompt.start()
  const saveData = (err, result) => {
    const data = Object.assign({}, result, {
      ignore: result.ignore.split(' ').map(a => a.toUpperCase())
    })
    if (!fs.existsSync(`${userDataFolder}`)) {
      fs.mkdirSync(`${userDataFolder}`)
    }
    const path = `${userDataFolder}/data.json`
    const dataJson = JSON.stringify(data)
    fs.writeFile(path, dataJson, 'utf8', run)
    console.log('Updated user data')
  }
  prompt.get(schema, saveData)
}

sync = data => {
  const session = new Session(data.username, data.password)
  siding.coursesList(session, data.ignore).then(courses => {
    console.log('\nFound courses')
    console.log(courses.map(c => c.path()))
    Promise.all(courses.map(course => course.scrap()))
      .then(courses => {
        console.log('\nFound:')
        const found = courses.map(c => ({
          name: c.name,
          folders: Object.keys(c.folders).length,
          files: Object.keys(c.files).length
        }))
        console.log(found)
        console.log('\nDownload:')
        const downloads = courses.map(c => ({
          name: c.name,
          folders: Object.keys(c.folders)
            .filter(id => c.folders[id].shouldCreate(data.path))
            .map(id => c.folders[id]),
          files: Object.keys(c.files)
            .filter(id => c.files[id].shouldDownload(data.path))
            .map(id => c.files[id])
        }))
        const downloadNumbers = downloads.map(download => ({
          name: download.name,
          folders: download.folders.length,
          files: download.files.length
        }))
        console.log(downloadNumbers)
        console.log('\nCreating missing folders...')
        courses.forEach(course => course.createFolder(data.path))
        downloads.forEach(d => d.folders.forEach(f => f.create(data.path)))
        console.log('\nStarting downloads, this may take a while...')
        const files = downloads
          .map(download => download.files)
          .reduce((total, arr) => total.concat(arr))
        Promise.all(files.map(file => file.download(data.path))).then(() =>
          console.log('\nFinished downloading!'))
      })
      .catch(error)
  })
}

exit = () => {
  console.log('Terminated sincding')
}

error = err => {
  const errorMessage = `
    --- Had an error ---
    ${error}

    --- Please report it to https://github.com/open-source-uc/sincding/issues
  `
  console.log(errorMessage)
}

options = {
  data: data,
  sync: sync,
  exit: exit
}

optionsDescriptions = {
  data: 'Update your user data',
  sync: 'Download sincding files',
  exit: 'Exit sincding'
}

run = () => {
  console.log('')
  // Load user data
  const userData = require(`${userDataFolder}/data.json`) || {}
  if (userData === {}) {
    data(userData)
  }
  // Show user data
  console.log('Current user data')
  console.log(`user: ${userData.username}`)
  console.log(`path: ${userData.path}`)
  console.log(`ignore: ${userData.ignore.join(' ')}`)
  console.log('')
  // If a command was supplied in the call, execute it
  const commandLine = options[process.argv[2]]
  if (commandLine) {
    console.log(`Executing \'${process.argv[2]}\' command`)
    process.argv[2] = ''
    return commandLine(userData)
  }
  // Show available commands
  console.log('Commands:')
  Object.keys(options).forEach(key => {
    console.log(` - ${key}: ${optionsDescriptions[key]}`)
  })
  // Prompt user for command
  prompt.start()
  runCommand = (err, result) => {
    if (!result || err) {
      console.log('\n')
      return exit()
    }
    const command = options[result.command]
    if (!command) {
      console.log('Not a valid command')
      return run()
    }
    // Execute selected command
    console.log(`Executing \'${result.command}\' command`)
    options[result.command](userData)
  }
  prompt.get(['command'], runCommand)
}

updateNotifier({pkg}).notify()
console.log('Welcome to sincding!')
console.log(`Version ${pkg.version}`)
run()
<|endoftext|>


<commit_before>import makeHandler from './handler'

export default function slack (config, dispatch) {
  const instance = init(config.token)
  const handler = makeHandler(instance)
  return forward(handler)
}
<commit_msg>import init<commit_after>import init from './init'
import makeHandler from './handler'

export default function slack (config, dispatch) {
  const instance = init(config.token)
  const handler = makeHandler(instance)
  return forward(handler)
}
<|endoftext|>


<commit_before>import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';

import App from './components/app';
import reducers from './reducers';

const createStoreWithMiddleware = applyMiddleware()(createStore);

ReactDOM.render(
  <Provider store={createStoreWithMiddleware(reducers)}>
    <App />
  </Provider>
  , document.querySelector('.container'));
<commit_msg>Hooked redux-promise middleware<commit_after>import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';
import ReduxPromise from 'redux-promise';

import App from './components/app';
import reducers from './reducers';

const createStoreWithMiddleware = applyMiddleware(ReduxPromise)(createStore);

ReactDOM.render(
  <Provider store={createStoreWithMiddleware(reducers)}>
    <App />
  </Provider>
  , document.querySelector('.container'));
<|endoftext|>


<commit_before>/* global document, window UMS_CONFIG */
import React from 'react';
import ReactDOM from 'react-dom';
import { Router, hashHistory } from 'react-router';
import {
    Publications,
    Core,
    UMS,
    Provider as CoreProvider,
} from 'oicr-ui-core';
import UserDashboard from './modules/UserDashboard';

// Load store.
const store = require('../site/store').default;

if (window.UMS_CONFIG) UMS.setConfig(window.UMS_CONFIG);

// Get User Session, Invoke once
UMS.getUserInfo()(store.dispatch);

// Render UMS
const target = document.getElementById('app-user-services');
if (target) {
    ReactDOM.render(
        <CoreProvider store={store}>
            <Router history={hashHistory}>
                <UMS.Route path="/dashboard" component={UserDashboard} />
                <UMS.BaseRoutes />
            </Router>
        </CoreProvider>,
        target
    );
}

// Render User Menu
const targetUserMenu = document.getElementById('app-user-nav');
if (targetUserMenu) {
    ReactDOM.render(
        <CoreProvider store={store}>
            <UMS.Components.UserNavMenu rootPath="/user" />
        </CoreProvider>,
        targetUserMenu
    );
}

/**
 * Render view/edit tab for admin user.
 * This will be rendered after pubmed publications are rendered.
 */
const config = Core.getConfig();
if (config.CMUI_ENABLED) {
    const targetEditable = document.getElementById('editButton');
    if (targetEditable) {
        ReactDOM.render(
            <Core.Provider store={store}>
                <Core.Components.ContentPageWrapper
                    viewDOM={targetEditable.innerHTML}
                    rootPath="/user/#/dashboard"
                    eventKey={3}
                    path={targetEditable.getAttribute('data-path')}
                    isPublic={targetEditable.getAttribute('data-is-public')}
                />
            </Core.Provider>,
            targetEditable
        );
    }
}
<commit_msg>Admin Dashboard Fix<commit_after>/* global document, window UMS_CONFIG */
import React from 'react';
import ReactDOM from 'react-dom';
import { Router, hashHistory } from 'react-router';
import {
    Publications,
    Core,
    UMS,
    Provider as CoreProvider,
} from 'oicr-ui-core';
import UserDashboard from './modules/UserDashboard';

// Load store.
const store = require('../site/store').default;

const client = Core.initApolloClient(true, store);

if (window.UMS_CONFIG) UMS.setConfig(window.UMS_CONFIG);

// Get User Session, Invoke once
UMS.getUserInfo()(store.dispatch);

// Render UMS
const target = document.getElementById('app-user-services');
if (target) {
    ReactDOM.render(
        <CoreProvider store={store} client={client}>
            <Router history={hashHistory}>
                <UMS.Route path="/dashboard" component={UserDashboard} />
                <UMS.BaseRoutes />
            </Router>
        </CoreProvider>,
        target
    );
}

// Render User Menu
const targetUserMenu = document.getElementById('app-user-nav');
if (targetUserMenu) {
    ReactDOM.render(
        <CoreProvider store={store}>
            <UMS.Components.UserNavMenu rootPath="/user" />
        </CoreProvider>,
        targetUserMenu
    );
}

/**
 * Render view/edit tab for admin user.
 * This will be rendered after pubmed publications are rendered.
 */
const config = Core.getConfig();
if (config.CMUI_ENABLED) {
    const targetEditable = document.getElementById('editButton');
    if (targetEditable) {
        ReactDOM.render(
            <Core.Provider store={store}>
                <Core.Components.ContentPageWrapper
                    viewDOM={targetEditable.innerHTML}
                    rootPath="/user/#/dashboard"
                    eventKey={3}
                    path={targetEditable.getAttribute('data-path')}
                    isPublic={targetEditable.getAttribute('data-is-public')}
                />
            </Core.Provider>,
            targetEditable
        );
    }
}
<|endoftext|>


<commit_before>#!/usr/bin/env node

/**
 * Cinema4D commandline Render Utilities
 * Rendering projects via terminal. This is useful for automation...
 *
 * @author: Paul Vollmer
 */

/**
 * Module dependencies.
 */
var program = require('commander');
var pkg = require('../package.json');
var utils = require('../src/utils.js');
var c4d = require('../src/index.js');

/**
 * The cli options.
 */
program
  .version(pkg.version)
  .option('-r, --render [filepath]', 'specify a file to render')
  .option('-f, --frame [from,to,step]', 'specify start frame, end frame and frame step. "to" and "step" are optional')
  .option('-i, --oimage [imagename]', 'override the image output path for rendering')
  .option('-m, --omultipass [imagename]', 'override the multipass output path for rendering')
  .option('-a, --oformat [imageformat]', 'override the image output format to TIFF/TGA/BMP/IFF/JPG/PICT/PSD/PSB/RLA/RPF/B3D')
  .option('-e, --oresolution [width,height]', 'override output image size')
  .option('-t, --threads [threadcnt]', 'specify number of threads (0 for auto-detection)')
  .option('-g, --gui', 'start with user interface')
  .option('-s, --silent', 'silent mode. don\'t output anything')
  .option('-c, --report [filepath]', 'save the CINEMA 4D stdout to a text file. if no filepath is set, write file to the current working directory')
program.on('--help', function() {
  console.log('  Description:');
  console.log('');
  console.log('    '+pkg.description);
  console.log('');
  console.log('  Examples:');
  console.log('');
  console.log('    # render a file');
  console.log('    $ c4d --render /path/to/your/file.c4d');
  console.log('');
  console.log('    # render a file and override the resolution');
  console.log('    $ c4d --render /path/to/your/file.c4d -oresolution 1500,1000');
  console.log('');
});
program.parse(process.argv);

/**
 * If no option are set. print out the help.
 */
if (program.render == undefined) {
  program.help();
}
/**
 * If the render option is set, lets render some nice images.
 */
else {
  if (program.render) {
    c4d.render({
      filepath: program.render,
      frame: program.frame,
      oimage: program.oimage,
      omultipass: program.omultipass,
      oformat: program.oformat,
      oresolution: program.oresolution,
      threads: program.threads,
      gui: program.gui,
      silent: program.silent,
      report: program.report
    });
  }
}
<commit_msg>bin/c4d-cli.js added more examples<commit_after>#!/usr/bin/env node

/**
 * Cinema4D commandline Render Utilities
 * Rendering projects via terminal. This is useful for automation...
 *
 * @author: Paul Vollmer
 */

/**
 * Module dependencies.
 */
var program = require('commander');
var pkg = require('../package.json');
var utils = require('../src/utils.js');
var c4d = require('../src/index.js');

/**
 * The cli options.
 */
program
  .version(pkg.version)
  .option('-r, --render [filepath]', 'specify a file to render')
  .option('-f, --frame [from,to,step]', 'specify start frame, end frame and frame step. "to" and "step" are optional')
  .option('-i, --oimage [imagename]', 'override the image output path for rendering')
  .option('-m, --omultipass [imagename]', 'override the multipass output path for rendering')
  .option('-a, --oformat [imageformat]', 'override the image output format to TIFF/TGA/BMP/IFF/JPG/PICT/PSD/PSB/RLA/RPF/B3D')
  .option('-e, --oresolution [width,height]', 'override output image size')
  .option('-t, --threads [threadcnt]', 'specify number of threads (0 for auto-detection)')
  .option('-g, --gui', 'start with user interface')
  .option('-s, --silent', 'silent mode. don\'t output anything')
  .option('-c, --report [filepath]', 'save the CINEMA 4D stdout to a json file. if no filepath is set, write file to the current working directory')
program.on('--help', function() {
  console.log('  Description:');
  console.log('');
  console.log('    '+pkg.description);
  console.log('');
  console.log('  Examples:');
  console.log('');
  console.log('    # render a file');
  console.log('    $ c4d --render /path/to/your/file.c4d');
  console.log('');
  console.log('    # render a file and override the resolution');
  console.log('    $ c4d --render /path/to/your/file.c4d --oresolution 1500,1000');
  console.log('');
  console.log('    # render a file from frame 0 to 100');
  console.log('    $ c4d --render /path/to/your/file.c4d --frame 0,100');
  console.log('');
  console.log('    # render a file and save a report');
  console.log('    $ c4d --render /path/to/your/file.c4d --report');
  console.log('');
});
program.parse(process.argv);

/**
 * If no option are set. print out the help.
 */
if (program.render == undefined) {
  program.help();
}
/**
 * If the render option is set, lets render some nice images.
 */
else {
  if (program.render) {
    c4d.render({
      filepath: program.render,
      frame: program.frame,
      oimage: program.oimage,
      omultipass: program.omultipass,
      oformat: program.oformat,
      oresolution: program.oresolution,
      threads: program.threads,
      gui: program.gui,
      silent: program.silent,
      report: program.report
    });
  }
}
<|endoftext|>


<commit_before>import path from 'path';
import os from 'os';
import mkdirp from 'mkdirp';
import md5 from 'md5';
import randomPort from 'random-port';
import { EasyZip } from 'easy-zip';
import rimraf from 'rimraf';
import magic from './whiten';

export default function whiten(modules, registry, cb) {
    if (!registry || typeof registry !== 'string') {
        cb = typeof registry === 'function' ? registry : undefined;
        registry = "npm";
    }
    let tempDir = path.join(os.tmpdir(), "whiten-" + md5(new Date().toString()));
    console.log("Downloading to " + tempDir);
    let storageDir = path.join(tempDir, "storage");
    mkdirp.sync(storageDir);
    mkdirp.sync(path.join(tempDir, "temp"));
    randomPort(port => {
        magic(registry, modules, tempDir, port, (err, stdout, stderr) => {
            if (err) {
                console.err(err);
            } else {
                let zip = new EasyZip();
                zip.zipFolder(storageDir, () => {
                    cb(zip);
                    rimraf(tempDir, (error) => {
                        if (error) {
                            console.error(error);
                        }
                    });
                });
            }
        });
    });
}
<commit_msg>deletes sinopia db file<commit_after>import path from 'path';
import os from 'os';
import mkdirp from 'mkdirp';
import md5 from 'md5';
import randomPort from 'random-port';
import { EasyZip } from 'easy-zip';
import rimraf from 'rimraf';
import magic from './whiten';

export default function whiten(modules, registry, cb) {
    if (!registry || typeof registry !== 'string') {
        cb = typeof registry === 'function' ? registry : undefined;
        registry = "npm";
    }
    let tempDir = path.join(os.tmpdir(), "whiten-" + md5(new Date().toString()));
    console.log("Downloading to " + tempDir);
    let storageDir = path.join(tempDir, "storage");
    mkdirp.sync(storageDir);
    mkdirp.sync(path.join(tempDir, "temp"));
    randomPort(port => {
        magic(registry, modules, tempDir, port, (err, stdout, stderr) => {
            if (err) {
                console.err(err);
            } else {
                rimraf.sync(path.join(storageDir, '.sinopia-db.json'));
                let zip = new EasyZip();
                zip.zipFolder(storageDir, () => {
                    cb(zip);
                    rimraf(tempDir, (error) => {
                        if (error) {
                            console.error(error);
                        }
                    });
                });
            }
        });
    });
}
<|endoftext|>


<commit_before><commit_msg>Various<commit_after><|endoftext|>


<commit_before>#!/usr/bin/env node --harmony

"use strict";

const logger = require('./logger');
const application = require('./application');
const items = require('./items');
const i18n = require('./i18n');

let args = {}, command = temp;

if (process.argv.length > 2) {
    process.argv.map((arg, index) => {
        if (index < 2) {
            return;
        }

        if (index === 2) {
            switch (arg) {
                case 'set-version':
                case 'ver':
                    command = application.setVersion;
                    break;
                case 'items-check':
                case 'items-c':
                    command = items.check;
                    break;
                case 'items-import':
                case 'items-i':
                    command = items.import;
                    break;
                case 'items-save':
                case 'items-s':
                    command = items.save;
                    break;
                case 'i18n-export':
                case 'i18n-e':
                    command = i18n.export;
                    break;
                case 'i18n-import':
                case 'i18n-i':
                    command = i18n.import;
                    break;
                case 'i18n-sync':
                case 'i18n-s':
                    command = i18n.sync;
                    break;
                case 'i18n-set':
                    command = i18n.set;
                    break;
                case 'i18n-remove':
                case 'i18n-rm':
                    command = i18n.remove;
                    break;
                case 'temp':
                    command = temp;
                    break;
                default:
                    logger.fatal(`command '${arg}' not found`);
                    break;
            }

            return;
        }

        if (arg.indexOf('-') === 0) {
            args[arg[1]] = arg.slice(2);
            if (args[arg[1]] === '') {
                args[arg[1]] = true;
            }
        }
    });
}

try {
    command(args);
} catch (e) {
    logger.fatal(e);
}

function temp() {
    logger.fatal(`command not realised`);
}
<commit_msg>migration<commit_after>#!/usr/bin/env node --harmony

"use strict";

const logger = require('./logger');
const application = require('./application');
const items = require('./items');
const i18n = require('./i18n');

let args = {}, command = temp;

if (process.argv.length > 2) {
    process.argv.map((arg, index) => {
        if (index < 2) {
            return;
        }

        if (index === 2) {
            switch (arg) {
                case 'set-version':
                case 'ver':
                    command = application.setVersion;
                    break;
                case 'items-check':
                case 'items-c':
                    command = items.check;
                    break;
                case 'items-import':
                case 'items-i':
                    command = items.import;
                    break;
                case 'items-save':
                case 'items-s':
                    command = items.save;
                    break;
                case 'i18n-export':
                case 'i18n-e':
                    command = i18n.export;
                    break;
                case 'i18n-import':
                case 'i18n-i':
                    command = i18n.import;
                    break;
                case 'i18n-sync':
                case 'i18n-s':
                    command = i18n.sync;
                    break;
                case 'i18n-set':
                    command = i18n.set;
                    break;
                case 'i18n-remove':
                case 'i18n-rm':
                    command = i18n.remove;
                    break;
                case 'temp':
                    command = temp;
                    break;
                default:
                    logger.fatal(`command '${arg}' not found`);
                    break;
            }

            return;
        }

        if (arg.indexOf('-') === 0) {
            args[arg[1]] = arg.slice(2);
            if (args[arg[1]] === '') {
                args[arg[1]] = true;
            }
        }
    });
}

try {
    command(args);
} catch (e) {
    logger.fatal(e);
}

function temp() {
    logger.fatal(`command not realised`);
}

function migrate() {
    const fs = require('fs');
    const itemsTools = require('./items');
    const items = require('./../src/data/items.json');

    let output = {}, uid, assoc = {getNew: {}, getOld: {},}, i18n, i18nNew;

    Object.values(items).map((item) => {
        uid = itemsTools.makeUid(item.type, item.name, item.hero);
        assoc.getNew[item.uid] = uid;
        assoc.getOld[uid] = item.uid;

        if (['SPRAY', 'ICON',].indexOf(item.type) !== -1) {
            fs.renameSync(
                `./../src/assets/${item.type.toLowerCase()}s/${item.uid}.png`,
                `./../src/assets/${item.type.toLowerCase()}s/${uid}.png`
            );
        }

        item.uid = uid;
        output[item.uid] = item;
    });

    fs.readdirSync('./../src/i18n/').map((file) => {
        if (file.indexOf('.json') !== -1) {
            i18nNew = {};
            i18n = require(`./../src/i18n/${file}`);
            for (let i in i18n.items) if (i18n.items.hasOwnProperty(i)) {
                i18nNew[assoc.getNew[i]] = i18n.items[i];
            }
            i18n.items = i18nNew;
            fs.writeFileSync(`./../src/i18n/${file}`, JSON.stringify(i18n, null, 2));
        }
    });

    fs.writeFileSync('./../src/data/assoc.json', JSON.stringify(assoc, null, 2));
    fs.writeFileSync('./../src/data/items.json', JSON.stringify(output, null, 2));
}
<|endoftext|>