<commit_before>import {Button} from 'widget/button'
import {ElementResizeDetector} from 'widget/elementResizeDetector'
import {Scrollable, ScrollableContainer} from 'widget/scrollable'
import {Subject} from 'rxjs'
import {compose} from 'compose'
import {delay} from 'rxjs/operators'
import {msg} from 'translate'
import Keybinding from 'widget/keybinding'
import PropTypes from 'prop-types'
import React from 'react'
import _ from 'lodash'
import styles from './list.module.css'
import withForwardedRef from 'ref'
import withSubscriptions from 'subscription'

const autoCenter$ = new Subject()

class _ScrollableList extends React.Component {
    render() {
        const {className, ...props} = this.props
        return (
            <ElementResizeDetector onResize={() => autoCenter$.next()}>
                <ScrollableContainer className={className}>
                    <Scrollable
                        className={styles.options}
                        direction='xy'>
                        {scrollable =>
                            <List
                                {...props}
                                scrollable={scrollable}
                            />}
                    </Scrollable>
                </ScrollableContainer>
            </ElementResizeDetector>
        )
    }
}
export const ScrollableList = compose(
    _ScrollableList,
    withSubscriptions(),
    withForwardedRef()
)

ScrollableList.propTypes = {
    options: PropTypes.arrayOf(
        PropTypes.shape({
            label: PropTypes.any,
            value: PropTypes.any
        })
    ).isRequired,
    onSelect: PropTypes.func.isRequired,
    air: PropTypes.any,
    alignment: PropTypes.oneOf(['left', 'center', 'right']),
    autoCenter: PropTypes.any,
    autoHighlight: PropTypes.any,
    className: PropTypes.string,
    keyboard: PropTypes.any,
    noResults: PropTypes.string,
    overScroll: PropTypes.any,
    selectedOption: PropTypes.any,
    tooltip: PropTypes.string,
    tooltipPlacement: PropTypes.oneOf(['left', 'right']),
    onCancel: PropTypes.func
}

ScrollableList.defaultProps = {
    alignment: 'left',
    tooltipPlacement: 'right'
}

class List extends React.Component {
    highlighted = React.createRef()
    selected = React.createRef()
    state = {
        highlightedOption: null,
        overrideHover: false
    }

    constructor(props) {
        super(props)
        const {forwardedRef} = props
        this.list = forwardedRef
            ? forwardedRef
            : React.createRef()
    }

    render() {
        const {scrollable: {containerHeight}, onCancel, keyboard} = this.props
        const keymap = {
            Escape: onCancel ? onCancel : null,
            Enter: () => this.selectHighlighted(),
            ArrowLeft: () => this.highlightPrevious(),
            ArrowRight: () => this.highlightNext(),
            ArrowUp: () => this.highlightPrevious(),
            ArrowDown: () => this.highlightNext(),
            Home: () => this.highlightFirst(),
            End: () => this.highlightLast()
        }
        return (
            <Keybinding keymap={keymap} disabled={keyboard === false}>
                {this.renderList(containerHeight)}
            </Keybinding>
        )
    }

    renderList(containerHeight = 0) {
        const {options, overScroll} = this.props
        return (

 autoCenter$.next(true)}
            >
                {this.renderOptions(options)}

        )
    }

    updateState(state, callback) {
        const updatedState = (prevState, state) =>
            _.isEqual(_.pick(prevState, _.keys(state)), state) ? null : state
        this.setState(
            prevState =>
                updatedState(prevState, _.isFunction(state) ? state(prevState) : state),
            callback
        )
    }

    renderOptions(options) {
        const {noResults} = this.props
        return options.length
            ? options.map((option, index) => this.renderOption(option, index))
            : this.renderOption({label: noResults || msg('widget.list.noResults')})
    }

    renderOption(option, index) {
        return option.value !== undefined && !option.disabled
            ? this.renderSelectableOption(option)
            : option.group
                ? this.renderGroup(option, index)
                : this.renderNonSelectableOption(option, index)
    }

    renderGroup(option, index) {
        const {alignment, air} = this.props
        return (

                <Button
                    chromeless
                    look='transparent'
                    air={air}
                    additionalClassName={styles.group}
                    label={option.render ? option.render() : option.label}
                    width='fill'
                    alignment={alignment}
                    disabled
                />

        )
    }

    renderNonSelectableOption(option, index) {
        const {alignment, air} = this.props
        return (

                <Button
                    chromeless
                    look='transparent'
                    air={air}
                    label={option.render ? option.render() : option.label}
                    width='fill'
                    alignment={alignment}
                    disabled
                />

        )
    }

    renderSelectableOption(option) {
        const {selectedOption, tooltipPlacement, alignment, air} = this.props
        const {overrideHover} = this.state
        const selected = this.isSelected(option)
        const highlighted = this.isHighlighted(option)
        const hover = overrideHover
            ? highlighted
            : null
        const ref = selected
            ? this.selected
            : highlighted
                ? this.highlighted
                : null
        return (

                <Button
                    chromeless={!selected}
                    look={selected ? 'selected' : 'highlight'}
                    air={air}
                    label={option.render ? option.render() : option.label}
                    tooltip={option.tooltip}
                    tooltipPlacement={tooltipPlacement}
                    hover={hover}
                    width='fill'
                    alignment={alignment}
                    disableTransitions
                    onMouseOver={() => this.highlightOption(option)}
                    onMouseOut={() => this.highlightOption(selectedOption)}
                    onClick={() => this.selectOption(option)}
                />

        )
    }

    isSelected(option) {
        const {selectedOption} = this.props
        return option === selectedOption
    }

    isSelectable(option) {
        return !option.group && option.value
    }

    isHighlighted(option) {
        const {highlightedOption} = this.state
        return highlightedOption && option && highlightedOption.value === option.value
    }

    selectHighlighted() {
        const {highlightedOption} = this.state
        if (highlightedOption) {
            this.selectOption(highlightedOption)
        }
    }

    cancel() {
        const {onCancel} = this.props
        onCancel && onCancel()
    }

    getSelectedOption() {
        const {options, selectedOption} = this.props
        return _.find(options, option => option === selectedOption)
    }

    getPreviousSelectableOption(option) {
        const {options} = this.props
        const index = _.indexOf(options, option)
        const previousIndex =
            index === -1
                ? options.length - 1
                : Math.max(index - 1, 0)
        return _.findLast(options, option => this.isSelectable(option), previousIndex) || option
    }

    getNextSelectableOption(option) {
        const {options} = this.props
        const nextIndex = Math.min(_.indexOf(options, option) + 1, options.length - 1)
        return _.find(options, option => this.isSelectable(option), nextIndex) || option
    }

    getFirstSelectableOption() {
        const {options} = this.props
        return _.find(options, option => this.isSelectable(option))
    }

    getLastSelectableOption() {
        const {options} = this.props
        return _.findLast(options, option => this.isSelectable(option))
    }

    highlightOption(highlightedOption) {
        this.setState({
            highlightedOption,
            overrideHover: false
        })
    }

    highlightPrevious() {
        this.setState(({highlightedOption}) => ({
            highlightedOption: this.getPreviousSelectableOption(highlightedOption),
            overrideHover: true
        }), this.scroll)
    }

    highlightNext() {
        this.setState(({highlightedOption}) => ({
            highlightedOption: this.getNextSelectableOption(highlightedOption),
            overrideHover: true
        }), this.scroll)
    }

    highlightFirst() {
        this.setState({
            highlightedOption: this.getFirstSelectableOption(),
            overrideHover: true
        }, this.scroll)
    }

    highlightLast() {
        this.setState({
            highlightedOption: this.getLastSelectableOption(),
            overrideHover: true
        }, this.scroll)
    }

    onHover(element) {
        if (element.parentElement.parentElement === this.list.current) {
            const optionValue = element.parentElement.getAttribute('data-option-value')
            this.highlightOptionByValue(optionValue)
        }
    }

    highlightOptionByValue(value) {
        const {options} = this.props
        const highlightedOption = _.find(options, option => option.value === value)
        if (highlightedOption) {
            this.setState({
                highlightedOption,
                overrideHover: true
            })
        }
    }

    scroll() {
        this.highlighted.current && this.highlighted.current.scrollIntoView({
            behavior: 'auto',
            block: 'nearest'
        })
    }

    selectOption(option) {
        const {onSelect} = this.props
        onSelect && onSelect(option)
    }

    highlightSelectedOption() {
        const {autoHighlight} = this.props
        const highlightedOption = this.getSelectedOption() || (autoHighlight && this.getFirstSelectableOption())
        this.setState({
            highlightedOption,
            overrideHover: true
        }, () => autoCenter$.next())
    }

    centerSelectedOption() {
        const {scrollable} = this.props
        scrollable.centerElement(this.selected.current)
    }

    initializeAutoCenter() {
        const {addSubscription, scrollable} = this.props
        addSubscription(
            // [HACK] Add delay to fix bug where iOS doesn't capture next tap event
            autoCenter$.pipe(delay(250)).subscribe(
                reset => reset
                    ? scrollable.reset(() => this.centerSelectedOption())
                    : this.centerSelectedOption()
            )
        )
        this.highlightSelectedOption()
    }

    componentDidMount() {
        this.initializeAutoCenter()
    }

    shouldComponentUpdate(nextProps, nextState) {
        if (!_.isEqual(nextProps, this.props)) {
            return true
        }
        if (nextState.overrideHover !== this.state.overrideHover) {
            return true
        }
        if (nextState.overrideHover && nextState.highlightedOption !== this.state.highlightedOption) {
            return true
        }
        return false
    }

    componentDidUpdate() {
        const {options} = this.props
        const {highlightedOption} = this.state
        if (!_.find(options, highlightedOption)) {
            this.highlightSelectedOption()
        }
    }
}
<commit_msg>Fixed List highlight of hovered option.<commit_after>import {Button} from 'widget/button'
import {ElementResizeDetector} from 'widget/elementResizeDetector'
import {Scrollable, ScrollableContainer} from 'widget/scrollable'
import {Subject} from 'rxjs'
import {compose} from 'compose'
import {delay} from 'rxjs/operators'
import {msg} from 'translate'
import Keybinding from 'widget/keybinding'
import PropTypes from 'prop-types'
import React from 'react'
import _ from 'lodash'
import styles from './list.module.css'
import withForwardedRef from 'ref'
import withSubscriptions from 'subscription'

const autoCenter$ = new Subject()

class _ScrollableList extends React.Component {
    render() {
        const {className, ...props} = this.props
        return (
            <ElementResizeDetector onResize={() => autoCenter$.next()}>
                <ScrollableContainer className={className}>
                    <Scrollable
                        className={styles.options}
                        direction='xy'>
                        {scrollable =>
                            <List
                                {...props}
                                scrollable={scrollable}
                            />}
                    </Scrollable>
                </ScrollableContainer>
            </ElementResizeDetector>
        )
    }
}
export const ScrollableList = compose(
    _ScrollableList,
    withSubscriptions(),
    withForwardedRef()
)

ScrollableList.propTypes = {
    options: PropTypes.arrayOf(
        PropTypes.shape({
            label: PropTypes.any,
            value: PropTypes.any
        })
    ).isRequired,
    onSelect: PropTypes.func.isRequired,
    air: PropTypes.any,
    alignment: PropTypes.oneOf(['left', 'center', 'right']),
    autoCenter: PropTypes.any,
    autoHighlight: PropTypes.any,
    className: PropTypes.string,
    keyboard: PropTypes.any,
    noResults: PropTypes.string,
    overScroll: PropTypes.any,
    selectedOption: PropTypes.any,
    tooltip: PropTypes.string,
    tooltipPlacement: PropTypes.oneOf(['left', 'right']),
    onCancel: PropTypes.func
}

ScrollableList.defaultProps = {
    alignment: 'left',
    tooltipPlacement: 'right'
}

class List extends React.Component {
    highlighted = React.createRef()
    selected = React.createRef()
    state = {
        highlightedOption: null,
        overrideHover: false
    }

    constructor(props) {
        super(props)
        const {forwardedRef} = props
        this.list = forwardedRef
            ? forwardedRef
            : React.createRef()
    }

    render() {
        const {scrollable: {containerHeight}, onCancel, keyboard} = this.props
        const keymap = {
            Escape: onCancel ? onCancel : null,
            Enter: () => this.selectHighlighted(),
            ArrowLeft: () => this.highlightPrevious(),
            ArrowRight: () => this.highlightNext(),
            ArrowUp: () => this.highlightPrevious(),
            ArrowDown: () => this.highlightNext(),
            Home: () => this.highlightFirst(),
            End: () => this.highlightLast()
        }
        return (
            <Keybinding keymap={keymap} disabled={keyboard === false}>
                {this.renderList(containerHeight)}
            </Keybinding>
        )
    }

    renderList(containerHeight = 0) {
        const {options, overScroll} = this.props
        return (

 autoCenter$.next(true)}
            >
                {this.renderOptions(options)}

        )
    }

    updateState(state, callback) {
        const updatedState = (prevState, state) =>
            _.isEqual(_.pick(prevState, _.keys(state)), state) ? null : state
        this.setState(
            prevState =>
                updatedState(prevState, _.isFunction(state) ? state(prevState) : state),
            callback
        )
    }

    renderOptions(options) {
        const {noResults} = this.props
        return options.length
            ? options.map((option, index) => this.renderOption(option, index))
            : this.renderOption({label: noResults || msg('widget.list.noResults')})
    }

    renderOption(option, index) {
        return option.value !== undefined && !option.disabled
            ? this.renderSelectableOption(option)
            : option.group
                ? this.renderGroup(option, index)
                : this.renderNonSelectableOption(option, index)
    }

    renderGroup(option, index) {
        const {alignment, air} = this.props
        return (

                <Button
                    chromeless
                    look='transparent'
                    air={air}
                    additionalClassName={styles.group}
                    label={option.render ? option.render() : option.label}
                    width='fill'
                    alignment={alignment}
                    disabled
                />

        )
    }

    renderNonSelectableOption(option, index) {
        const {alignment, air} = this.props
        return (

                <Button
                    chromeless
                    look='transparent'
                    air={air}
                    label={option.render ? option.render() : option.label}
                    width='fill'
                    alignment={alignment}
                    disabled
                />

        )
    }

    renderSelectableOption(option) {
        const {selectedOption, tooltipPlacement, alignment, air} = this.props
        const {overrideHover} = this.state
        const selected = this.isSelected(option)
        const highlighted = this.isHighlighted(option)
        const hover = overrideHover
            ? highlighted
            : null
        const ref = selected
            ? this.selected
            : highlighted
                ? this.highlighted
                : null
        return (

                <Button
                    chromeless={!selected}
                    look={selected ? 'selected' : 'highlight'}
                    air={air}
                    label={option.render ? option.render() : option.label}
                    tooltip={option.tooltip}
                    tooltipPlacement={tooltipPlacement}
                    hover={hover}
                    width='fill'
                    alignment={alignment}
                    disableTransitions
                    onMouseOver={() => this.highlightOption(option)}
                    onMouseOut={() => this.highlightOption(selectedOption)}
                    onClick={() => this.selectOption(option)}
                />

        )
    }

    isSelected(option) {
        const {selectedOption} = this.props
        return option === selectedOption
    }

    isSelectable(option) {
        return !option.group && option.value
    }

    isHighlighted(option) {
        const {highlightedOption} = this.state
        return highlightedOption && option && highlightedOption.value === option.value
    }

    selectHighlighted() {
        const {highlightedOption} = this.state
        if (highlightedOption) {
            this.selectOption(highlightedOption)
        }
    }

    cancel() {
        const {onCancel} = this.props
        onCancel && onCancel()
    }

    getSelectedOption() {
        const {options, selectedOption} = this.props
        return _.find(options, option => option === selectedOption)
    }

    getPreviousSelectableOption(option) {
        const {options} = this.props
        const index = _.indexOf(options, option)
        const previousIndex =
            index === -1
                ? options.length - 1
                : Math.max(index - 1, 0)
        return _.findLast(options, option => this.isSelectable(option), previousIndex) || option
    }

    getNextSelectableOption(option) {
        const {options} = this.props
        const nextIndex = Math.min(_.indexOf(options, option) + 1, options.length - 1)
        return _.find(options, option => this.isSelectable(option), nextIndex) || option
    }

    getFirstSelectableOption() {
        const {options} = this.props
        return _.find(options, option => this.isSelectable(option))
    }

    getLastSelectableOption() {
        const {options} = this.props
        return _.findLast(options, option => this.isSelectable(option))
    }

    highlightOption(highlightedOption) {
        this.setState({
            highlightedOption,
            overrideHover: false
        })
    }

    highlightPrevious() {
        this.setState(({highlightedOption}) => ({
            highlightedOption: this.getPreviousSelectableOption(highlightedOption),
            overrideHover: true
        }), this.scroll)
    }

    highlightNext() {
        this.setState(({highlightedOption}) => ({
            highlightedOption: this.getNextSelectableOption(highlightedOption),
            overrideHover: true
        }), this.scroll)
    }

    highlightFirst() {
        this.setState({
            highlightedOption: this.getFirstSelectableOption(),
            overrideHover: true
        }, this.scroll)
    }

    highlightLast() {
        this.setState({
            highlightedOption: this.getLastSelectableOption(),
            overrideHover: true
        }, this.scroll)
    }

    onHover(element) {
        if (element.parentElement.parentElement === this.list.current) {
            const optionValue = element.parentElement.getAttribute('data-option-value')
            this.highlightOptionByValue(optionValue)
        }
    }

    highlightOptionByValue(value) {
        const {options} = this.props
        const highlightedOption = _.find(options, option => option.value === value)
        if (highlightedOption) {
            this.setState({
                highlightedOption,
                overrideHover: true
            })
        }
    }

    scroll() {
        this.highlighted.current && this.highlighted.current.scrollIntoView({
            behavior: 'auto',
            block: 'nearest'
        })
    }

    selectOption(option) {
        const {onSelect} = this.props
        onSelect && onSelect(option)
    }

    highlightSelectedOption() {
        const {autoHighlight} = this.props
        const highlightedOption = this.getSelectedOption() || (autoHighlight && this.getFirstSelectableOption())
        this.setState({
            highlightedOption,
            overrideHover: true
        }, () => autoCenter$.next())
    }

    centerSelectedOption() {
        const {scrollable} = this.props
        scrollable.centerElement(this.selected.current)
    }

    initializeAutoCenter() {
        const {addSubscription, scrollable} = this.props
        addSubscription(
            // [HACK] Add delay to fix bug where iOS doesn't capture next tap event
            autoCenter$.pipe(delay(250)).subscribe(
                reset => reset
                    ? scrollable.reset(() => this.centerSelectedOption())
                    : this.centerSelectedOption()
            )
        )
        this.highlightSelectedOption()
    }

    componentDidMount() {
        this.initializeAutoCenter()
    }

    shouldComponentUpdate(nextProps, nextState) {
        if (!_.isEqual(nextProps, this.props)) {
            return true
        }
        if (nextState.overrideHover !== this.state.overrideHover) {
            return true
        }
        if (nextState.overrideHover && nextState.highlightedOption !== this.state.highlightedOption) {
            return true
        }
        return false
    }

    componentDidUpdate() {
        const {options} = this.props
        const {highlightedOption} = this.state
        if (highlightedOption && !_.find(options, ({value}) => value === highlightedOption.value)) {
            this.highlightSelectedOption()
        }
    }
}
<|endoftext|>


<commit_before>var express = require('express');
var router = express.Router();
var bodyParser = require('body-parser');
var parseUrlEncoded = bodyParser.urlencoded({ extended: false });

var schools = [];

/* GET schools listing. */
router.route('/')
  .get(function(request, response) {

  })
  .post(parseUrlEncoded, function(request, response) {

  });

router.route('/:slug')
  .all(function(request, response) {

  })
  .get(function(request, response) {

  });

module.exports = router;
<commit_msg>added /schools/ and /schools/:slug<commit_after>var express = require('express');
var router = express.Router();
var bodyParser = require('body-parser');
var parseUrlEncoded = bodyParser.urlencoded({ extended: false });
var slug = require('../helpers/slug');
var model = require('../data/model');

/* GET schools listing. */
router.route('/')
  .get(function(request, response) {
    response.json(model.getAllSchools());
  })
  .post(parseUrlEncoded, function(request, response) {

  });

router.route('/:slug')
  .get(function(request, response) {
    var schoolSlug = request.params.slug;
    var school = model.getSchool(schoolSlug);
    if (school) {
      response.json(school);
    } else {
      response.status(404).send('School not found');
    }
  });

module.exports = router;
<|endoftext|>


<commit_before>var exported = {
  noflo: require('noflo'),
  underscore: require('underscore'),
  'coffee-script': require('coffee-script'),
  'child_process': null,
  'uuid': require('uuid'),
  'flowhub-registry': require('flowhub-registry'),
  'fbp-protocol-client': require('fbp-protocol-client'),
  'fbp-spec': require('fbp-spec'),
  'noflo-ui/src/JournalStore': require('../src/JournalStore'),
  'noflo-ui/runtimeinfo': require('../runtimeinfo/index.coffee'),
  'noflo-ui/collections': require('../src/collections.coffee'),
  'noflo-ui/projects': require('../src/projects.coffee'),
  'the-graph': require('the-graph')
};

window.TheGraph = exported['the-graph']; // expected by the-graph Polymer elements

window.require = function (moduleName) {
  if (typeof exported[moduleName] !== 'undefined') {
    return exported[moduleName];
  }
  throw new Error('Module ' + moduleName + ' not available');
};

window.addEventListener('WebComponentsReady', function() {
  var noflo = require('noflo');
  var runtime = require('noflo-runtime-webrtc');

  var baseDir = '/noflo-ui';
  var mainGraph = require('../graphs/main.fbp');

  var loadGraphs = function(callback) {
    noflo.graph.loadJSON(mainGraph, function (err, g) {
      if (err) {
        callback(err);
        return;
      }
      g.baseDir = baseDir;
      noflo.createNetwork(g, function (err, n) {
        if (err) {
          callback(err);
          return;
        }
        n.on('process-error', function (err) {
          console.error(err.error);
        });
        return callback();
      });
    });
  };
  var loadGraphsDebuggable = function(callback) {
    var secret = Math.random().toString(36).substring(7);
    noflo.graph.loadJSON(mainGraph, function (err, graph) {
      if (err) {
        callback(err);
        return;
      }
      graph.baseDir = baseDir;
      var runtimeOptions = {
        defaultGraph: graph,
        baseDir: graph.baseDir,
        permissions: {}
      };
      runtimeOptions.permissions[secret] = [
        'protocol:component',
        'protocol:runtime',
        'protocol:graph',
        'protocol:network',
        'component:getsource',
        'component:setsource'
      ];
      var rt = runtime(null, runtimeOptions, true);
      rt.start();
      var ide = 'http://app.flowhub.io';
      var debugUrl = ide+'#runtime/endpoint?'+encodeURIComponent('protocol=webrtc&address='+rt.signaller+'#'+rt.id+'&secret='+secret);
      var debugLink = document.getElementById('flowhub_debug_url');
      if (debugLink) {
        debugLink.href = debugUrl;
      } else {
        console.log(debugUrl);
      }
      rt.network.on('addnetwork', function () {
        return callback();
      });
    });
  };

  window.nofloStarted = false;
  var load = (false) ? loadGraphsDebuggable : loadGraphs;
  load(function(err) {
    if (err) {
      throw err;
    }
    document.body.classList.remove('loading');
    window.nofloStarted = true;
    setTimeout(function () {
      var loader = document.getElementById('loading');
      document.body.removeChild(loader);
    }, 400);
  });
});
<commit_msg>Mobile Safari doesn't have console.error<commit_after>var exported = {
  noflo: require('noflo'),
  underscore: require('underscore'),
  'coffee-script': require('coffee-script'),
  'child_process': null,
  'uuid': require('uuid'),
  'flowhub-registry': require('flowhub-registry'),
  'fbp-protocol-client': require('fbp-protocol-client'),
  'fbp-spec': require('fbp-spec'),
  'noflo-ui/src/JournalStore': require('../src/JournalStore'),
  'noflo-ui/runtimeinfo': require('../runtimeinfo/index.coffee'),
  'noflo-ui/collections': require('../src/collections.coffee'),
  'noflo-ui/projects': require('../src/projects.coffee'),
  'the-graph': require('the-graph')
};

window.TheGraph = exported['the-graph']; // expected by the-graph Polymer elements

window.require = function (moduleName) {
  if (typeof exported[moduleName] !== 'undefined') {
    return exported[moduleName];
  }
  throw new Error('Module ' + moduleName + ' not available');
};

window.addEventListener('WebComponentsReady', function() {
  var noflo = require('noflo');
  var runtime = require('noflo-runtime-webrtc');

  var baseDir = '/noflo-ui';
  var mainGraph = require('../graphs/main.fbp');

  var loadGraphs = function(callback) {
    noflo.graph.loadJSON(mainGraph, function (err, g) {
      if (err) {
        callback(err);
        return;
      }
      g.baseDir = baseDir;
      noflo.createNetwork(g, function (err, n) {
        if (err) {
          callback(err);
          return;
        }
        n.on('process-error', function (err) {
          if (typeof console.error === 'function') {
            console.error(err.error);
          } else {
            console.log(err.error);
          }
        });
        return callback();
      });
    });
  };
  var loadGraphsDebuggable = function(callback) {
    var secret = Math.random().toString(36).substring(7);
    noflo.graph.loadJSON(mainGraph, function (err, graph) {
      if (err) {
        callback(err);
        return;
      }
      graph.baseDir = baseDir;
      var runtimeOptions = {
        defaultGraph: graph,
        baseDir: graph.baseDir,
        permissions: {}
      };
      runtimeOptions.permissions[secret] = [
        'protocol:component',
        'protocol:runtime',
        'protocol:graph',
        'protocol:network',
        'component:getsource',
        'component:setsource'
      ];
      var rt = runtime(null, runtimeOptions, true);
      rt.start();
      var ide = 'http://app.flowhub.io';
      var debugUrl = ide+'#runtime/endpoint?'+encodeURIComponent('protocol=webrtc&address='+rt.signaller+'#'+rt.id+'&secret='+secret);
      var debugLink = document.getElementById('flowhub_debug_url');
      if (debugLink) {
        debugLink.href = debugUrl;
      } else {
        console.log(debugUrl);
      }
      rt.network.on('addnetwork', function () {
        return callback();
      });
    });
  };

  window.nofloStarted = false;
  var load = (false) ? loadGraphsDebuggable : loadGraphs;
  load(function(err) {
    if (err) {
      throw err;
    }
    document.body.classList.remove('loading');
    window.nofloStarted = true;
    setTimeout(function () {
      var loader = document.getElementById('loading');
      document.body.removeChild(loader);
    }, 400);
  });
});
<|endoftext|>


<commit_before>import { createApp, defineAsyncComponent } from 'vue';

import '@fontsource/kreon';

const app = createApp({
    mounted: function() {
        document.body.classList.add('cssLoading');
        setTimeout(() => document.body.classList.remove('cssLoading'), 0);
    },
    components: {
        PageRandom: defineAsyncComponent(() => import('./components/pageRandom.vue')),
        Pending: defineAsyncComponent(() => import('./components/pending.vue')),
        OrganizerForm: defineAsyncComponent(() => import('./components/organizer/form.vue')),
        DearSantaForm: defineAsyncComponent(() => import('./components/dearSantaForm.vue')),
        Dashboard: defineAsyncComponent(() => import('./components/dashboard.vue')),
        Faq: defineAsyncComponent(() => import('./components/faq.vue')),
        VueFetcher: defineAsyncComponent(() => import('./components/vueFetcher.vue'))
    }
});
app.mount('#main');

const lang = document.documentElement.lang.substr(0, 2);
import Locale from './vue-i18n-locales.generated.js';

import { createI18n } from 'vue-i18n';
const i18n = createI18n({
    locale: lang,
    messages: Locale,
    globalInjection: true
});

app.use(i18n);

import VuejsDialog from 'vuejs-dialog';
app.use(VueJsDialog);
<commit_msg>Comment test on vuejsdialog with vue3<commit_after>import { createApp, defineAsyncComponent } from 'vue';

import '@fontsource/kreon';

const app = createApp({
    mounted: function() {
        document.body.classList.add('cssLoading');
        setTimeout(() => document.body.classList.remove('cssLoading'), 0);
    },
    components: {
        PageRandom: defineAsyncComponent(() => import('./components/pageRandom.vue')),
        Pending: defineAsyncComponent(() => import('./components/pending.vue')),
        OrganizerForm: defineAsyncComponent(() => import('./components/organizer/form.vue')),
        DearSantaForm: defineAsyncComponent(() => import('./components/dearSantaForm.vue')),
        Dashboard: defineAsyncComponent(() => import('./components/dashboard.vue')),
        Faq: defineAsyncComponent(() => import('./components/faq.vue')),
        VueFetcher: defineAsyncComponent(() => import('./components/vueFetcher.vue'))
    }
});
app.mount('#main');

const lang = document.documentElement.lang.substr(0, 2);
import Locale from './vue-i18n-locales.generated.js';

import { createI18n } from 'vue-i18n';
const i18n = createI18n({
    locale: lang,
    messages: Locale,
    globalInjection: true
});

app.use(i18n);

//import VuejsDialog from 'vuejs-dialog';
//app.use(VueJsDialog);
<|endoftext|>


<commit_before>var gulp = require('gulp');
var gulpif = require('gulp-if');
var uglify = require('gulp-uglify');
var uglifycss = require('gulp-uglifycss');
var concat = require('gulp-concat');
var sass = require('gulp-sass');
var sourcemaps = require('gulp-sourcemaps');
var debug = require('gulp-debug');
var livereload = require('gulp-livereload');
var order = require('gulp-order');
var merge = require('merge-stream');
var env = process.env.GULP_ENV;

var rootPath = 'web/assets/';

var adminRootPath = rootPath + 'admin/';
var shopRootPath = rootPath + 'shop/';

var paths = {
    admin: {
        js: [
            'node_modules/jquery/dist/jquery.min.js',
            'node_modules/semantic-ui-css/semantic.min.js',
            'vendor/sylius/sylius/src/Sylius/Bundle/AdminBundle/Resources/private/js/**',
            'vendor/sylius/sylius/src/Sylius/Bundle/UiBundle/Resources/private/js/**',
            'vendor/sylius/sylius/src/Sylius/Bundle/ShippingBundle/Resources/public/js/**',
            'vendor/sylius/sylius/src/Sylius/Bundle/PromotionBundle/Resources/public/js/sylius-promotion.js',
            'vendor/sylius/sylius/src/Sylius/Bundle/UserBundle/Resources/public/js/sylius-user.js'
        ],
        sass: [
            'vendor/sylius/sylius/src/Sylius/Bundle/UiBundle/Resources/private/sass/**',
        ],
        css: [
            'node_modules/semantic-ui-css/semantic.min.css',
        ],
        img: [
            'vendor/sylius/sylius/src/Sylius/Bundle/UiBundle/Resources/private/img/**',
        ]
    },
    shop: {
        js: [
            'node_modules/jquery/dist/jquery.min.js',
            'node_modules/semantic-ui-css/semantic.min.js',
            'vendor/sylius/sylius/src/Sylius/Bundle/UiBundle/Resources/private/js/**',
            'vendor/sylius/sylius/src/Sylius/Bundle/ShopBundle/Resources/private/js/**'
        ],
        sass: [
            'vendor/sylius/sylius/src/Sylius/Bundle/UiBundle/Resources/private/sass/**',
        ],
        css: [
            'node_modules/semantic-ui-css/semantic.min.css',
        ],
        img: [
            'vendor/sylius/sylius/src/Sylius/Bundle/UiBundle/Resources/private/img/**',
        ]
    }
};

gulp.task('admin-js', function () {
    return gulp.src(paths.admin.js)
        .pipe(concat('app.js'))
        .pipe(gulpif(env === 'prod', uglify))
        .pipe(sourcemaps.write('./'))
        .pipe(gulp.dest(adminRootPath + 'js/'))
    ;
});

gulp.task('admin-css', function() {
    gulp.src(['node_modules/semantic-ui-css/themes/**/*']).pipe(gulp.dest(adminRootPath + 'css/themes/'));

    var cssStream = gulp.src(paths.admin.css)
        .pipe(concat('css-files.css'))
    ;

    var sassStream = gulp.src(paths.admin.sass)
        .pipe(sass())
        .pipe(concat('sass-files.scss'))
    ;

    return merge(cssStream, sassStream)
        .pipe(order(['css-files.css', 'sass-files.scss']))
        .pipe(concat('style.css'))
        .pipe(gulpif(env === 'prod', uglifycss))
        .pipe(sourcemaps.write('./'))
        .pipe(gulp.dest(adminRootPath + 'css/'))
        .pipe(livereload())
    ;
});

gulp.task('admin-img', function() {
    return gulp.src(paths.admin.img)
        .pipe(sourcemaps.write('./'))
        .pipe(gulp.dest(adminRootPath + 'img/'))
    ;
});

gulp.task('admin-watch', function() {
    livereload.listen();

    gulp.watch(paths.admin.js, ['admin-js']);
    gulp.watch(paths.admin.sass, ['admin-css']);
    gulp.watch(paths.admin.css, ['admin-css']);
    gulp.watch(paths.admin.img, ['admin-img']);
});

gulp.task('shop-js', function () {
    return gulp.src(paths.shop.js)
        .pipe(concat('app.js'))
        .pipe(gulpif(env === 'prod', uglify))
        .pipe(sourcemaps.write('./'))
        .pipe(gulp.dest(shopRootPath + 'js/'))
    ;
});

gulp.task('shop-css', function() {
    gulp.src(['node_modules/semantic-ui-css/themes/**/*']).pipe(gulp.dest(shopRootPath + 'css/themes/'));

    var cssStream = gulp.src(paths.shop.css)
        .pipe(concat('css-files.css'))
    ;

    var sassStream = gulp.src(paths.shop.sass)
        .pipe(sass())
        .pipe(concat('sass-files.scss'))
    ;

    return merge(cssStream, sassStream)
        .pipe(order(['css-files.css', 'sass-files.scss']))
        .pipe(concat('style.css'))
        .pipe(gulpif(env === 'prod', uglifycss))
        .pipe(sourcemaps.write('./'))
        .pipe(gulp.dest(shopRootPath + 'css/'))
        .pipe(livereload())
    ;
});

gulp.task('shop-img', function() {
    return gulp.src(paths.shop.img)
        .pipe(sourcemaps.write('./'))
        .pipe(gulp.dest(shopRootPath + 'img/'))
    ;
});

gulp.task('shop-watch', function() {
    livereload.listen();

    gulp.watch(paths.shop.js, ['shop-js']);
    gulp.watch(paths.shop.sass, ['shop-css']);
    gulp.watch(paths.shop.css, ['shop-css']);
    gulp.watch(paths.shop.img, ['shop-img']);
});

gulp.task('default', ['admin-js', 'admin-css', 'admin-img', 'shop-js', 'shop-css', 'shop-img']);
gulp.task('watch', ['admin-watch', 'shop-watch']);
<commit_msg>Fix Gulpfile<commit_after>var gulp = require('gulp');
var gulpif = require('gulp-if');
var uglify = require('gulp-uglify');
var uglifycss = require('gulp-uglifycss');
var concat = require('gulp-concat');
var sass = require('gulp-sass');
var sourcemaps = require('gulp-sourcemaps');
var debug = require('gulp-debug');
var livereload = require('gulp-livereload');
var order = require('gulp-order');
var merge = require('merge-stream');
var env = process.env.GULP_ENV;

var rootPath = 'web/assets/';

var adminRootPath = rootPath + 'admin/';
var shopRootPath = rootPath + 'shop/';

var paths = {
    admin: {
        js: [
            'node_modules/jquery/dist/jquery.min.js',
            'node_modules/semantic-ui-css/semantic.min.js',
            'vendor/sylius/sylius/src/Sylius/Bundle/AdminBundle/Resources/private/js/**',
            'vendor/sylius/sylius/src/Sylius/Bundle/UiBundle/Resources/private/js/**',
            'vendor/sylius/sylius/src/Sylius/Bundle/ShippingBundle/Resources/public/js/**',
            'vendor/sylius/sylius/src/Sylius/Bundle/PromotionBundle/Resources/public/js/sylius-promotion.js',
            'vendor/sylius/sylius/src/Sylius/Bundle/UserBundle/Resources/public/js/sylius-user.js'
        ],
        sass: [
            'vendor/sylius/sylius/src/Sylius/Bundle/UiBundle/Resources/private/sass/**',
        ],
        css: [
            'node_modules/semantic-ui-css/semantic.min.css',
        ],
        img: [
            'vendor/sylius/sylius/src/Sylius/Bundle/UiBundle/Resources/private/img/**',
        ]
    },
    shop: {
        js: [
            'node_modules/jquery/dist/jquery.min.js',
            'node_modules/semantic-ui-css/semantic.min.js',
            'vendor/sylius/sylius/src/Sylius/Bundle/UiBundle/Resources/private/js/**',
            'vendor/sylius/sylius/src/Sylius/Bundle/ShopBundle/Resources/private/js/**'
        ],
        sass: [
            'vendor/sylius/sylius/src/Sylius/Bundle/UiBundle/Resources/private/sass/**',
            'vendor/sylius/sylius/src/Sylius/Bundle/ShopBundle/Resources/private/scss/**',
        ],
        css: [
            'node_modules/semantic-ui-css/semantic.min.css',
        ],
        img: [
            'vendor/sylius/sylius/src/Sylius/Bundle/UiBundle/Resources/private/img/**',
        ]
    }
};

gulp.task('admin-js', function () {
    return gulp.src(paths.admin.js)
        .pipe(concat('app.js'))
        .pipe(gulpif(env === 'prod', uglify))
        .pipe(sourcemaps.write('./'))
        .pipe(gulp.dest(adminRootPath + 'js/'))
    ;
});

gulp.task('admin-css', function() {
    gulp.src(['node_modules/semantic-ui-css/themes/**/*']).pipe(gulp.dest(adminRootPath + 'css/themes/'));

    var cssStream = gulp.src(paths.admin.css)
        .pipe(concat('css-files.css'))
    ;

    var sassStream = gulp.src(paths.admin.sass)
        .pipe(sass())
        .pipe(concat('sass-files.scss'))
    ;

    return merge(cssStream, sassStream)
        .pipe(order(['css-files.css', 'sass-files.scss']))
        .pipe(concat('style.css'))
        .pipe(gulpif(env === 'prod', uglifycss))
        .pipe(sourcemaps.write('./'))
        .pipe(gulp.dest(adminRootPath + 'css/'))
        .pipe(livereload())
    ;
});

gulp.task('admin-img', function() {
    return gulp.src(paths.admin.img)
        .pipe(sourcemaps.write('./'))
        .pipe(gulp.dest(adminRootPath + 'img/'))
    ;
});

gulp.task('admin-watch', function() {
    livereload.listen();

    gulp.watch(paths.admin.js, ['admin-js']);
    gulp.watch(paths.admin.sass, ['admin-css']);
    gulp.watch(paths.admin.css, ['admin-css']);
    gulp.watch(paths.admin.img, ['admin-img']);
});

gulp.task('shop-js', function () {
    return gulp.src(paths.shop.js)
        .pipe(concat('app.js'))
        .pipe(gulpif(env === 'prod', uglify))
        .pipe(sourcemaps.write('./'))
        .pipe(gulp.dest(shopRootPath + 'js/'))
    ;
});

gulp.task('shop-css', function() {
    gulp.src(['node_modules/semantic-ui-css/themes/**/*']).pipe(gulp.dest(shopRootPath + 'css/themes/'));

    var cssStream = gulp.src(paths.shop.css)
        .pipe(concat('css-files.css'))
    ;

    var sassStream = gulp.src(paths.shop.sass)
        .pipe(sass())
        .pipe(concat('sass-files.scss'))
    ;

    return merge(cssStream, sassStream)
        .pipe(order(['css-files.css', 'sass-files.scss']))
        .pipe(concat('style.css'))
        .pipe(gulpif(env === 'prod', uglifycss))
        .pipe(sourcemaps.write('./'))
        .pipe(gulp.dest(shopRootPath + 'css/'))
        .pipe(livereload())
    ;
});

gulp.task('shop-img', function() {
    return gulp.src(paths.shop.img)
        .pipe(sourcemaps.write('./'))
        .pipe(gulp.dest(shopRootPath + 'img/'))
    ;
});

gulp.task('shop-watch', function() {
    livereload.listen();

    gulp.watch(paths.shop.js, ['shop-js']);
    gulp.watch(paths.shop.sass, ['shop-css']);
    gulp.watch(paths.shop.css, ['shop-css']);
    gulp.watch(paths.shop.img, ['shop-img']);
});

gulp.task('default', ['admin-js', 'admin-css', 'admin-img', 'shop-js', 'shop-css', 'shop-img']);
gulp.task('watch', ['default', 'admin-watch', 'shop-watch']);
<|endoftext|>


<commit_before>#!/usr/bin/env node
/* eslint no-console:"off" */
"use strict";

var path = require("path"),

    meow   = require("meow"),
    execa  = require("execa"),
    globby = require("globby"),
    series = require("promise-map-series"),

    types = require("../"),

    cli = meow(`
        Usage
            $ mithril-codemods [<file|glob> ...]

        Options
            --unsafe, -u    Use unsafe transforms
            --apply,  -a    Apply transforms (instead of a dry run)

        Examples
            mithril-codemods **/*.js
            mithril-codemods --apply **/*.js
    `, {
        boolean : [ "unsafe", "apply" ],
        alias   : {
            a : "apply",
            u : "unsafe"
        }
    }),

    transforms = types.safe;

if(!cli.input.length) {
    cli.showHelp(0);

    return;
}

if(cli.flags.unsafe) {
    transforms = transforms.concat(types.unsafe);
}

transforms = transforms.concat(types.warning);

globby(cli.input).then((paths) =>
    series(
        transforms,
        (transform) => {
            console.log(`${transform.name} running`);

            return execa(
                path.resolve(__dirname, "../node_modules/.bin/jscodeshift"),
                [ "-t", transform.file, cli.flags.apply ? "" : "-d" ].concat(paths),
                { stdio : "inherit" }
            )
            .then((result) => console.log(`${result.stdout}\n`))
            .catch(console.error.bind(console));
        }
    )
);
<commit_msg>docs: re-add CLI example<commit_after>#!/usr/bin/env node
/* eslint no-console:"off" */
"use strict";

var path = require("path"),

    meow   = require("meow"),
    execa  = require("execa"),
    globby = require("globby"),
    series = require("promise-map-series"),

    types = require("../"),

    cli = meow(`
        Usage
            $ mithril-codemods [<file|glob> ...]

        Options
            --unsafe, -u    Use unsafe transforms
            --apply,  -a    Apply transforms (instead of a dry run)

        Examples
            mithril-codemods **/*.js
            mithril-codemods --apply **/*.js
            mithril-codemods -ua some/specific/file.js
    `, {
        boolean : [ "unsafe", "apply" ],
        alias   : {
            a : "apply",
            u : "unsafe"
        }
    }),

    transforms = types.safe;

if(!cli.input.length) {
    cli.showHelp(0);

    return;
}

if(cli.flags.unsafe) {
    transforms = transforms.concat(types.unsafe);
}

transforms = transforms.concat(types.warning);

globby(cli.input).then((paths) =>
    series(
        transforms,
        (transform) => {
            console.log(`${transform.name} running`);

            return execa(
                path.resolve(__dirname, "../node_modules/.bin/jscodeshift"),
                [ "-t", transform.file, cli.flags.apply ? "" : "-d" ].concat(paths),
                { stdio : "inherit" }
            )
            .then((result) => console.log(`${result.stdout}\n`))
            .catch(console.error.bind(console));
        }
    )
);
<|endoftext|>


<commit_before>var querystring = require('querystring'),
    Url = require('url'),
    sys = require('sys'),
    forms = require('../../../node-forms/forms'),
    MongooseAdmin = require('../../mongoose-admin');

exports.login = function(req, res) {
    MongooseAdmin.singleton.login(req.body.username, req.body.password, function(err, adminUser) {
        if (err) {
            res.writeHead(500);
            res.end();
        } else {
            if (!adminUser) {
                res.writeHead(401);
                res.end();
            } else {
                req.session._mongooseAdminUser = adminUser.toSessionStore();
                res.writeHead(200, {"Content-Type": "application/json"});
                res.write("{}");
                res.end();
            }
        }
    });
};

exports.documents = function(req, res) {
    var adminUser = req.session._mongooseAdminUser ? MongooseAdmin.userFromSessionStore(req.session._mongooseAdminUser) : null;
    if (!adminUser) {
        res.writeHead(401, {"Content-Type": "application/json"});
        res.end();
        return;
    } else {
        var query = querystring.parse(Url.parse(req.url).query);
        MongooseAdmin.singleton.modelCounts(query.collection, function(err, totalCount) {
            if (err) {
                res.writeHead(500);
                res.end();
            } else {
                MongooseAdmin.singleton.listModelDocuments(query.collection, query.start, query.count, function(err, documents) {
                    if (err) {
                        res.writeHead(500);
                        res.end();
                    } else {
                        res.writeHead(200, {"Content-Type": "application/json"});
                        res.write(JSON.stringify({'totalCount': totalCount, 'documents': documents}));
                        res.end();
                    }
                });
            }
        });
    }
};

exports.checkDependencies = function(req,res)
{
    var modelName = req.body.model;
    var id = req.body.id;
    forms.checkDependecies(modelName,id,function(err,results)
    {
        var json = [];
        for(var i=0; i<results.length; i++)
        {
            json.push(results[i].name || results[i].title || results[i].toString());
        }
        res.json(json,200);
    });
};

exports.createDocument = function(req, res) {
    var adminUser = req.session._mongooseAdminUser ? MongooseAdmin.userFromSessionStore(req.session._mongooseAdminUser) : null;
    if (!adminUser) {
        res.writeHead(401, {"Content-Type": "application/json"});
        res.end();
        return;
    } else {
        MongooseAdmin.singleton.createDocument(req,adminUser, req.params.collectionName, req.body, function(err, document) {
            if (err) {
                if(typeof(err)=='object')
                {
                    res.json(err,400);
                }
                else
                {
                    res.writeHead(500);
                    res.end();
                }
            } else {
                res.writeHead(201, {"Content-Type": "application/json"});
                res.write(JSON.stringify({"collection": req.params.collectionName}));
                res.end();
            }
        });
    }
};

exports.updateDocument = function(req, res) {
    var adminUser = req.session._mongooseAdminUser ? MongooseAdmin.userFromSessionStore(req.session._mongooseAdminUser) : null;
    if (!adminUser) {
        res.writeHead(401, {"Content-Type": "application/json"});
        res.end();
        return;
    } else {
        MongooseAdmin.singleton.updateDocument(req,adminUser, req.params.collectionName, req.body._id, req.body, function(err, document) {
            if (err) {
                res.writeHead(500);
                res.end();
            } else {
                res.writeHead(200, {"Content-Type": "application/json"});
                res.write(JSON.stringify({"collection": req.params.collectionName}));
                res.end();
            }
        });
    }
};

exports.orderDocuments = function(req,res)
{
    var adminUser = req.session._mongooseAdminUser ? MongooseAdmin.userFromSessionStore(req.session._mongooseAdminUser) : null;
    if (!adminUser) {
        res.writeHead(401, {"Content-Type": "application/json"});
        res.end();
        return;
    } else {
        MongooseAdmin.singleton.orderDocuments(adminUser, req.params.collectionName, req.body, function(err) {
            if (err) {
                res.writeHead(500);
                res.end();
            } else {
                res.writeHead(200, {"Content-Type": "application/json"});
                res.write(JSON.stringify({"collection": req.params.collectionName}));
                res.end();
            }
        });
    }
};

exports.deleteDocument = function(req, res) {
    var adminUser = req.session._mongooseAdminUser ? MongooseAdmin.userFromSessionStore(req.session._mongooseAdminUser) : null;
    if (!adminUser) {
        res.writeHead(401, {"Content-Type": "application/json"});
        res.end();
        return;
    } else {
        var query = querystring.parse(Url.parse(req.url).query);
        MongooseAdmin.singleton.deleteDocument(adminUser, req.params.collectionName, query.document_id, function(err) {
            if (err) {
                res.writeHead(500);
                res.end();
            } else {
                res.writeHead(200, {"Content-Type": "application/json"});
                res.write(JSON.stringify({"collection": req.params.collectionName}));
                res.end();
            }
        });
    }
};

exports.linkedDocumentsList = function(req, res) {
    var adminUser = req.session._mongooseAdminUser ? MongooseAdmin.userFromSessionStore(req.session._mongooseAdminUser) : null;
    if (!adminUser) {
        res.writeHead(401, {"Content-Type": "application/json"});
        res.end();
        return;
    } else {
        MongooseAdmin.singleton.getModel(req.params.collectionName, function(err, model, fields, options) {
            if (err) {
                res.writeHead(500);
                res.end();
            } else {
                MongooseAdmin.singleton.listModelDocuments(req.params.collectionName, 0, 500, function(err, documents) {
                    if (err) {
                        res.writeHead(500);
                        res.end();
                    } else {
                        var result = [];
                        documents.forEach(function(document) {
                            var d = {'_id': document._id};
                            options.list.forEach(function(listField) {
                                d[listField] = document[listField];
                            });
                            result.push(d);
                        });

                        res.writeHead(200, {"Content-Type": "application/json"});
                        res.write(JSON.stringify(result));
                        res.end();
                    }
                });
            }
        });
    }
}
<commit_msg>require j-forms<commit_after>var querystring = require('querystring'),
    Url = require('url'),
    sys = require('sys'),
    forms = require('j-forms').forms,
    MongooseAdmin = require('../../mongoose-admin');

exports.login = function(req, res) {
    MongooseAdmin.singleton.login(req.body.username, req.body.password, function(err, adminUser) {
        if (err) {
            res.writeHead(500);
            res.end();
        } else {
            if (!adminUser) {
                res.writeHead(401);
                res.end();
            } else {
                req.session._mongooseAdminUser = adminUser.toSessionStore();
                res.writeHead(200, {"Content-Type": "application/json"});
                res.write("{}");
                res.end();
            }
        }
    });
};

exports.documents = function(req, res) {
    var adminUser = req.session._mongooseAdminUser ? MongooseAdmin.userFromSessionStore(req.session._mongooseAdminUser) : null;
    if (!adminUser) {
        res.writeHead(401, {"Content-Type": "application/json"});
        res.end();
        return;
    } else {
        var query = querystring.parse(Url.parse(req.url).query);
        MongooseAdmin.singleton.modelCounts(query.collection, function(err, totalCount) {
            if (err) {
                res.writeHead(500);
                res.end();
            } else {
                MongooseAdmin.singleton.listModelDocuments(query.collection, query.start, query.count, function(err, documents) {
                    if (err) {
                        res.writeHead(500);
                        res.end();
                    } else {
                        res.writeHead(200, {"Content-Type": "application/json"});
                        res.write(JSON.stringify({'totalCount': totalCount, 'documents': documents}));
                        res.end();
                    }
                });
            }
        });
    }
};

exports.checkDependencies = function(req,res)
{
    var modelName = req.body.model;
    var id = req.body.id;
    forms.checkDependecies(modelName,id,function(err,results)
    {
        var json = [];
        for(var i=0; i<results.length; i++)
        {
            json.push(results[i].name || results[i].title || results[i].toString());
        }
        res.json(json,200);
    });
};

exports.createDocument = function(req, res) {
    var adminUser = req.session._mongooseAdminUser ? MongooseAdmin.userFromSessionStore(req.session._mongooseAdminUser) : null;
    if (!adminUser) {
        res.writeHead(401, {"Content-Type": "application/json"});
        res.end();
        return;
    } else {
        MongooseAdmin.singleton.createDocument(req,adminUser, req.params.collectionName, req.body, function(err, document) {
            if (err) {
                if(typeof(err)=='object')
                {
                    res.json(err,400);
                }
                else
                {
                    res.writeHead(500);
                    res.end();
                }
            } else {
                res.writeHead(201, {"Content-Type": "application/json"});
                res.write(JSON.stringify({"collection": req.params.collectionName}));
                res.end();
            }
        });
    }
};

exports.updateDocument = function(req, res) {
    var adminUser = req.session._mongooseAdminUser ? MongooseAdmin.userFromSessionStore(req.session._mongooseAdminUser) : null;
    if (!adminUser) {
        res.writeHead(401, {"Content-Type": "application/json"});
        res.end();
        return;
    } else {
        MongooseAdmin.singleton.updateDocument(req,adminUser, req.params.collectionName, req.body._id, req.body, function(err, document) {
            if (err) {
                res.writeHead(500);
                res.end();
            } else {
                res.writeHead(200, {"Content-Type": "application/json"});
                res.write(JSON.stringify({"collection": req.params.collectionName}));
                res.end();
            }
        });
    }
};

exports.orderDocuments = function(req,res)
{
    var adminUser = req.session._mongooseAdminUser ? MongooseAdmin.userFromSessionStore(req.session._mongooseAdminUser) : null;
    if (!adminUser) {
        res.writeHead(401, {"Content-Type": "application/json"});
        res.end();
        return;
    } else {
        MongooseAdmin.singleton.orderDocuments(adminUser, req.params.collectionName, req.body, function(err) {
            if (err) {
                res.writeHead(500);
                res.end();
            } else {
                res.writeHead(200, {"Content-Type": "application/json"});
                res.write(JSON.stringify({"collection": req.params.collectionName}));
                res.end();
            }
        });
    }
};

exports.deleteDocument = function(req, res) {
    var adminUser = req.session._mongooseAdminUser ? MongooseAdmin.userFromSessionStore(req.session._mongooseAdminUser) : null;
    if (!adminUser) {
        res.writeHead(401, {"Content-Type": "application/json"});
        res.end();
        return;
    } else {
        var query = querystring.parse(Url.parse(req.url).query);
        MongooseAdmin.singleton.deleteDocument(adminUser, req.params.collectionName, query.document_id, function(err) {
            if (err) {
                res.writeHead(500);
                res.end();
            } else {
                res.writeHead(200, {"Content-Type": "application/json"});
                res.write(JSON.stringify({"collection": req.params.collectionName}));
                res.end();
            }
        });
    }
};

exports.linkedDocumentsList = function(req, res) {
    var adminUser = req.session._mongooseAdminUser ? MongooseAdmin.userFromSessionStore(req.session._mongooseAdminUser) : null;
    if (!adminUser) {
        res.writeHead(401, {"Content-Type": "application/json"});
        res.end();
        return;
    } else {
        MongooseAdmin.singleton.getModel(req.params.collectionName, function(err, model, fields, options) {
            if (err) {
                res.writeHead(500);
                res.end();
            } else {
                MongooseAdmin.singleton.listModelDocuments(req.params.collectionName, 0, 500, function(err, documents) {
                    if (err) {
                        res.writeHead(500);
                        res.end();
                    } else {
                        var result = [];
                        documents.forEach(function(document) {
                            var d = {'_id': document._id};
                            options.list.forEach(function(listField) {
                                d[listField] = document[listField];
                            });
                            result.push(d);
                        });

                        res.writeHead(200, {"Content-Type": "application/json"});
                        res.write(JSON.stringify(result));
                        res.end();
                    }
                });
            }
        });
    }
}
<|endoftext|>


<commit_before>import {Button} from 'widget/button'
import {Content, SectionLayout, TopBar} from 'widget/sectionLayout'
import {connect, select} from 'store'
import {isMobile} from 'widget/userAgent'
import {msg} from 'translate'
import PropTypes from 'prop-types'
import React from 'react'
import TabContent from './tabContent'
import Tooltip from 'widget/tooltip'
import actionBuilder from 'action-builder'
import guid from 'guid'
import styles from './tabs.module.css'

export const addTab = statePath => {
    const id = guid()
    const tab = {id, placeholder: msg('widget.tabs.newTab')}
    actionBuilder('ADD_TAB')
        .push([statePath, 'tabs'], tab)
        .set([statePath, 'selectedTabId'], id)
        .dispatch()
    return tab
}

const getTabIndex = (id, statePath) =>
    select([statePath, 'tabs'])
        .findIndex(tab => tab.id === id)

const toTabPath = (id, statePath) =>
    [statePath, 'tabs', getTabIndex(id, statePath)].join('.')

const renameTab = (id, title, tabPath, onTitleChanged) => {
    actionBuilder('RENAME_TAB')
        .set([tabPath, 'title'], title)
        .dispatch()
    setTimeout(() => onTitleChanged && onTitleChanged(select(tabPath)), 0)
}

export const closeTab = (id, statePath) => {
    const updateSelectedTab = (root, stateBuilder) => {
        if (root.selectedTabId !== id)
            return
        const tabs = root.tabs
        const tabIndex = tabs.findIndex(tab => tab.id === id)
        const first = tabIndex === 0
        const last = tabIndex === tabs.length - 1
        let nextSelectedId = null
        if (!last)
            nextSelectedId = tabs[tabIndex + 1].id
        else if (!first)
            nextSelectedId = tabs[tabIndex - 1].id
        return stateBuilder.set([statePath, 'selectedTabId'], nextSelectedId)
    }

    actionBuilder('CLOSE_TAB')
        .withState(statePath, updateSelectedTab)
        .delValueByTemplate([statePath, 'tabs'], {id})
        .dispatch()
}

export const selectTab = (id, statePath) => {
    actionBuilder('SELECT_TAB')
        .set([statePath, 'selectedTabId'], id)
        .dispatch()
}

const mapStateToProps = (state, ownProps) => ({
    tabs: select([ownProps.statePath, 'tabs']) || [],
    selectedTabId: select([ownProps.statePath, 'selectedTabId'])
})

class Tabs extends React.Component {
    constructor(props) {
        super(props)
        const {tabs, statePath} = props
        if (tabs.length === 0)
            addTab(statePath)
    }

    renderTab(tab) {
        const {selectedTabId, statePath, onTitleChanged} = this.props
        return (
            <Tab
                key={tab.id}
                id={tab.id}
                title={tab.title}
                placeholder={tab.placeholder}
                selected={tab.id === selectedTabId}
                statePath={statePath}
                onTitleChanged={onTitleChanged}
            />
        )
    }

    renderTabContent(tab) {
        const {selectedTabId, children} = this.props
        return (
            <TabContent key={tab.id} tab={tab} selected={tab.id === selectedTabId}>
                {children}
            </TabContent>
        )
    }

    renderTabs() {
        const {selectedTabId, tabActions} = this.props
        return (
            <React.Fragment>

                    {this.props.tabs.map(tab => this.renderTab(tab))}

                    {this.renderAddButton()}
                    {tabActions(selectedTabId)}

            </React.Fragment>
        )
    }

    renderAddButton() {
        const {statePath} = this.props
        return (
            <Button
                chromeless
                size='large'
                shape='circle'
                icon='plus'
                tooltip={msg('widget.tabs.addTab.tooltip')}
                tooltipPlacement='bottom'
                onClick={() => addTab(statePath)}/>
        )
    }

    render() {
        return (
            <SectionLayout className={styles.container}>
                <TopBar padding={false} label={msg('home.sections.process')}>
                    {this.renderTabs()}
                </TopBar>
                <Content>

                        {this.props.tabs.map(tab => this.renderTabContent(tab))}

                </Content>
            </SectionLayout>
        )
    }

    componentDidUpdate() {
        const {tabs, statePath} = this.props
        if (tabs.length === 0)
            addTab(statePath)
    }
}

Tabs.propTypes = {
    statePath: PropTypes.string.isRequired,
    children: PropTypes.any,
    selectedTabId: PropTypes.string,
    tabActions: PropTypes.func,
    tabs: PropTypes.array,
    onTitleChanged: PropTypes.func
}

export default connect(mapStateToProps)(Tabs)

class Tab extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            editing: false,
            title: null
        }
        this.titleInput = React.createRef()
    }

    onTitleChange(e) {
        const value = e.target.value.replace(/[^\w-.]/g, '_')
        e.target.value = value
        this.setState(prevState => ({...prevState, title: value}))
    }

    saveTitle() {
        const {id, statePath, onTitleChanged} = this.props
        const tabPath = toTabPath(id, statePath)
        const selectTab = () => select(tabPath)
        const prevTitle = selectTab().title
        const title = this.titleInput.current.value
        if (prevTitle === title || (!prevTitle && !title))
            return
        renameTab(id, title, tabPath, onTitleChanged)
        this.setState(
            state => ({...state, editing: false})
        )
    }

    renderCloseButton() {
        const {id, statePath} = this.props
        return (
            <Button
                chromeless
                look='cancel'
                size='small'
                shape='circle'
                icon='times'
                onClick={() => closeTab(id, statePath)}/>
        )
    }

    render() {
        let {id, title, placeholder, selected, statePath} = this.props
        title = this.state.title || title
        return (
            <Tooltip
                msg={title || placeholder}
                placement='bottom'
                delay={1}>

 selectTab(id, statePath)}>

                        {title || placeholder}
                        {selected
                            ? (
                                <input
                                    ref={this.titleInput}
                                    className={styles.title}
                                    defaultValue={title}
                                    placeholder={placeholder}
                                    autoFocus={!title && !isMobile()}
                                    spellCheck={false}
                                    autoComplete='off'
                                    onKeyDown={e => {
                                        if (['Enter', 'Escape'].includes(e.key)) {
                                            e.target.blur()
                                        }
                                    }}
                                    onChange={e => this.onTitleChange(e)}
                                    onBlur={() => this.saveTitle()}/>
                            ) : null
                        }

                        {this.renderCloseButton()}

            </Tooltip>
        )
    }

    scrollSelectedTabIntoView() {
        const element = this.titleInput.current
        element && element.scrollIntoView({inline: 'start'})
    }

    componentDidMount() {
        this.scrollSelectedTabIntoView()
    }

    componentDidUpdate(prevProps, prevState) {
        const {selected} = this.props
        selected && this.scrollSelectedTabIntoView()
        if (!prevState.editing && this.state.editing)
            this.titleInput.current.select()
    }
}

Tab.propTypes = {
    id: PropTypes.string,
    placeholder: PropTypes.string,
    selected: PropTypes.any,
    statePath: PropTypes.string,
    title: PropTypes.string,
    onTitleChanged: PropTypes.func
}

const NewTab = ({onAdd}) =>

        +

NewTab.propTypes = {
    onAdd: PropTypes.func
}
<commit_msg>Implemented workaround for scrollIntoView behavior.<commit_after>import {Button} from 'widget/button'
import {Content, SectionLayout, TopBar} from 'widget/sectionLayout'
import {connect, select} from 'store'
import {isMobile} from 'widget/userAgent'
import {msg} from 'translate'
import PropTypes from 'prop-types'
import React from 'react'
import TabContent from './tabContent'
import Tooltip from 'widget/tooltip'
import actionBuilder from 'action-builder'
import guid from 'guid'
import styles from './tabs.module.css'

export const addTab = statePath => {
    const id = guid()
    const tab = {id, placeholder: msg('widget.tabs.newTab')}
    actionBuilder('ADD_TAB')
        .push([statePath, 'tabs'], tab)
        .set([statePath, 'selectedTabId'], id)
        .dispatch()
    return tab
}

const getTabIndex = (id, statePath) =>
    select([statePath, 'tabs'])
        .findIndex(tab => tab.id === id)

const toTabPath = (id, statePath) =>
    [statePath, 'tabs', getTabIndex(id, statePath)].join('.')

const renameTab = (id, title, tabPath, onTitleChanged) => {
    actionBuilder('RENAME_TAB')
        .set([tabPath, 'title'], title)
        .dispatch()
    setTimeout(() => onTitleChanged && onTitleChanged(select(tabPath)), 0)
}

export const closeTab = (id, statePath) => {
    const updateSelectedTab = (root, stateBuilder) => {
        if (root.selectedTabId !== id)
            return
        const tabs = root.tabs
        const tabIndex = tabs.findIndex(tab => tab.id === id)
        const first = tabIndex === 0
        const last = tabIndex === tabs.length - 1
        let nextSelectedId = null
        if (!last)
            nextSelectedId = tabs[tabIndex + 1].id
        else if (!first)
            nextSelectedId = tabs[tabIndex - 1].id
        return stateBuilder.set([statePath, 'selectedTabId'], nextSelectedId)
    }

    actionBuilder('CLOSE_TAB')
        .withState(statePath, updateSelectedTab)
        .delValueByTemplate([statePath, 'tabs'], {id})
        .dispatch()
}

export const selectTab = (id, statePath) => {
    actionBuilder('SELECT_TAB')
        .set([statePath, 'selectedTabId'], id)
        .dispatch()
}

const mapStateToProps = (state, ownProps) => ({
    tabs: select([ownProps.statePath, 'tabs']) || [],
    selectedTabId: select([ownProps.statePath, 'selectedTabId'])
})

class Tabs extends React.Component {
    constructor(props) {
        super(props)
        const {tabs, statePath} = props
        if (tabs.length === 0)
            addTab(statePath)
    }

    renderTab(tab) {
        const {selectedTabId, statePath, onTitleChanged} = this.props
        return (
            <Tab
                key={tab.id}
                id={tab.id}
                title={tab.title}
                placeholder={tab.placeholder}
                selected={tab.id === selectedTabId}
                statePath={statePath}
                onTitleChanged={onTitleChanged}
            />
        )
    }

    renderTabContent(tab) {
        const {selectedTabId, children} = this.props
        return (
            <TabContent key={tab.id} tab={tab} selected={tab.id === selectedTabId}>
                {children}
            </TabContent>
        )
    }

    renderTabs() {
        const {selectedTabId, tabActions} = this.props
        return (
            <React.Fragment>

                    {this.props.tabs.map(tab => this.renderTab(tab))}

                    {this.renderAddButton()}
                    {tabActions(selectedTabId)}

            </React.Fragment>
        )
    }

    renderAddButton() {
        const {statePath} = this.props
        return (
            <Button
                chromeless
                size='large'
                shape='circle'
                icon='plus'
                tooltip={msg('widget.tabs.addTab.tooltip')}
                tooltipPlacement='bottom'
                onClick={() => addTab(statePath)}/>
        )
    }

    render() {
        return (
            <SectionLayout className={styles.container}>
                <TopBar padding={false} label={msg('home.sections.process')}>
                    {this.renderTabs()}
                </TopBar>
                <Content>

                        {this.props.tabs.map(tab => this.renderTabContent(tab))}

                </Content>
            </SectionLayout>
        )
    }

    componentDidUpdate() {
        const {tabs, statePath} = this.props
        if (tabs.length === 0)
            addTab(statePath)
    }
}

Tabs.propTypes = {
    statePath: PropTypes.string.isRequired,
    children: PropTypes.any,
    selectedTabId: PropTypes.string,
    tabActions: PropTypes.func,
    tabs: PropTypes.array,
    onTitleChanged: PropTypes.func
}

export default connect(mapStateToProps)(Tabs)

class Tab extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            editing: false,
            title: null
        }
        this.titleInput = React.createRef()
    }

    onTitleChange(e) {
        const value = e.target.value.replace(/[^\w-.]/g, '_')
        e.target.value = value
        this.setState(prevState => ({...prevState, title: value}))
    }

    saveTitle() {
        const {id, statePath, onTitleChanged} = this.props
        const tabPath = toTabPath(id, statePath)
        const selectTab = () => select(tabPath)
        const prevTitle = selectTab().title
        const title = this.titleInput.current.value
        if (prevTitle === title || (!prevTitle && !title))
            return
        renameTab(id, title, tabPath, onTitleChanged)
        this.setState(
            state => ({...state, editing: false})
        )
    }

    renderCloseButton() {
        const {id, statePath} = this.props
        return (
            <Button
                chromeless
                look='cancel'
                size='small'
                shape='circle'
                icon='times'
                onClick={() => closeTab(id, statePath)}/>
        )
    }

    render() {
        let {id, title, placeholder, selected, statePath} = this.props
        title = this.state.title || title
        return (
            <Tooltip
                msg={title || placeholder}
                placement='bottom'
                delay={1}>

 selectTab(id, statePath)}>

                        {title || placeholder}
                        {selected
                            ? (
                                <input
                                    ref={this.titleInput}
                                    className={styles.title}
                                    defaultValue={title}
                                    placeholder={placeholder}
                                    autoFocus={!title && !isMobile()}
                                    spellCheck={false}
                                    autoComplete='off'
                                    onKeyDown={e => {
                                        if (['Enter', 'Escape'].includes(e.key)) {
                                            e.target.blur()
                                        }
                                    }}
                                    onChange={e => this.onTitleChange(e)}
                                    onBlur={() => this.saveTitle()}/>
                            ) : null
                        }

                        {this.renderCloseButton()}

            </Tooltip>
        )
    }

    scrollSelectedTabIntoView() {
        const element = this.titleInput.current
        element && element.scrollIntoView({inline: 'nearest', behavior: 'smooth'})
    }

    componentDidMount() {
        this.scrollSelectedTabIntoView()
    }

    componentDidUpdate(prevProps, prevState) {
        const {selected} = this.props
        selected && prevProps.selected !== selected && this.scrollSelectedTabIntoView()
        if (!prevState.editing && this.state.editing)
            this.titleInput.current.select()
    }
}

Tab.propTypes = {
    id: PropTypes.string,
    placeholder: PropTypes.string,
    selected: PropTypes.any,
    statePath: PropTypes.string,
    title: PropTypes.string,
    onTitleChanged: PropTypes.func
}

const NewTab = ({onAdd}) =>

        +

NewTab.propTypes = {
    onAdd: PropTypes.func
}
<|endoftext|>


<commit_before>var mapnik = require('../');
var assert = require('assert');
var path = require('path');
var fs = require('fs');
var existsSync = require('fs').existsSync || require('path').existsSync;

mapnik.register_datasource(path.join(mapnik.settings.paths.input_plugins,'gdal.input'));

describe('reading GeoTIFF in threads', function() {
    // puts unnatural and odd load on opening geotiff
    it('should be able to open geotiff various ways without crashing', function(done) {
        var ds = new mapnik.Datasource({'type':'gdal','file':'./test/data/vector_tile/natural_earth.tif'});
        var map = new mapnik.Map(256, 256);
        map.load('./test/data/vector_tile/raster_layer.xml',{},function(err,map) { if (err) throw err; });
        assert.ok(ds);
        var fs = ds.featureset();
        assert.ok(fs);
        mapnik.register_datasource(path.join(mapnik.settings.paths.input_plugins,'gdal.input'));
        var vtile = new mapnik.VectorTile(0, 0, 0);
        var map = new mapnik.Map(256, 256);
        map.load('./test/data/vector_tile/raster_layer.xml',{},function(err,map) { if (err) throw err; });
        map.render(vtile,{},function(err,vtile) {
            if (err) throw err;
        });
        var map2 = new mapnik.Map(256, 256);
        map2.load('./test/data/vector_tile/raster_layer.xml',{},function(err,map) { if (err) throw err; });
        var map3 = new mapnik.Map(256, 256);
        map3.load('./test/data/vector_tile/raster_layer.xml',{},function(err,map) { if (err) throw err; });
        map3.render(vtile,{},function(err,vtile) {
            if (err) throw err;
            done();
        });
    });
});
<commit_msg>try harder to prompt crash by registering inline<commit_after>var mapnik = require('../');
var assert = require('assert');
var path = require('path');
var fs = require('fs');
var existsSync = require('fs').existsSync || require('path').existsSync;

describe('reading GeoTIFF in threads', function() {
    // puts unnatural and odd load on opening geotiff
    it('should be able to open geotiff various ways without crashing', function(done) {
        mapnik.register_datasource(path.join(mapnik.settings.paths.input_plugins,'gdal.input'));
        var ds = new mapnik.Datasource({'type':'gdal','file':'./test/data/vector_tile/natural_earth.tif'});
        var map = new mapnik.Map(256, 256);
        map.load('./test/data/vector_tile/raster_layer.xml',{},function(err,map) { if (err) throw err; });
        assert.ok(ds);
        var fs = ds.featureset();
        assert.ok(fs);
        mapnik.register_datasource(path.join(mapnik.settings.paths.input_plugins,'gdal.input'));
        var vtile = new mapnik.VectorTile(0, 0, 0);
        var map = new mapnik.Map(256, 256);
        map.load('./test/data/vector_tile/raster_layer.xml',{},function(err,map) { if (err) throw err; });
        mapnik.register_datasource(path.join(mapnik.settings.paths.input_plugins,'gdal.input'));
        map.render(vtile,{},function(err,vtile) {
            if (err) throw err;
        });
        var map2 = new mapnik.Map(256, 256);
        map2.load('./test/data/vector_tile/raster_layer.xml',{},function(err,map) { if (err) throw err; });
        var map3 = new mapnik.Map(256, 256);
        map3.load('./test/data/vector_tile/raster_layer.xml',{},function(err,map) { if (err) throw err; });
        map3.render(vtile,{},function(err,vtile) {
            if (err) throw err;
            done();
        });
    });
});
<|endoftext|>


<commit_before>'use strict';

var express = require('express');
var path = require('path');

var swagger = function(app) {
  app.get('/swagger', express.static('../swagger-ui'));
};

module.exports = swagger;
<commit_msg>Removed redundant file<commit_after><|endoftext|>


<commit_before>// Sets the require.js configuration for your application.
require.config({
    // 3rd party script alias names (Easier to type "jquery" than "libs/jquery-1.7.2.min")
    paths: {

        // Core Libraries
        "modernizr": "libs/modernizr",
        "jquery": "libs/jquery",
        "underscore": "libs/underscore",
        "backbone": "libs/backbone",
        "handlebars": "libs/Handlebars",
        "hbs": "libs/hbs",
        "json2": "libs/json2",
        "i18nprecompile": "libs/i18nprecompile",
        "leaflet": "libs/leaflet",
        "time_domain": "libs/time_domain",
        "fastclick": "libs/fastclick",
        "backbone.queryparams": "libs/backbone.queryparams",
        "backbone.subroute": "libs/backbone.subroute",
        "backbone.hal": "libs/backbone.hal"
    },

    // Sets the configuration for your third party scripts that are not AMD compatible
    shim: {
        "backbone": {
            "deps": ["underscore", "jquery"],
            "exports": "Backbone"  //attaches "Backbone" to the window object
        },
        "underscore": {
            "exports": "_"
        },
        "backbone.queryparams": {
            "deps": ["backbone"]
        },
        "leaflet": {
            "exports": "L"
        },
        "time_domain": {
            "exports": "TimeDomain"
        },
        "handlebars": {
            "exports": "Handlebars"
        },
        "json2": {
            "exports": "JSON"
        }
    },

    hbs: {
        templateExtension: 'handlebars',
        disableI18n: true,
        helperPathCallback: function(name) {return 'templates/helpers/' + name;}
    }
});

require(['modernizr','jquery','backbone', 'router', 'fastclick', 'backbone.queryparams'], function(Modernizr, $, Backbone, MoxieRouter, FastClick) {
    moxieRouter = new MoxieRouter();
    $.ajaxSetup({ headers: { 'Accept': 'application/hal+json;q=1.0, application/json;q=0.9, */*; q=0.01' } });
    Backbone.history.start();
    $('#home a').click(function(ev) {
        ev.preventDefault();
        $('body').toggleClass('is-sidebar-active');
        return false;
    });
    $('.overlay').click(function(ev) {
        $('body').toggleClass('is-sidebar-active');
    });
    $('#sidebar a').click(function(ev) {
        $('body').toggleClass('is-sidebar-active');
    });
    window.addEventListener('load', function() {
        new FastClick(document.body);
    }, false);
});
<commit_msg>Multiple selectors for sidebar toggle.<commit_after>// Sets the require.js configuration for your application.
require.config({
    // 3rd party script alias names (Easier to type "jquery" than "libs/jquery-1.7.2.min")
    paths: {

        // Core Libraries
        "modernizr": "libs/modernizr",
        "jquery": "libs/jquery",
        "underscore": "libs/underscore",
        "backbone": "libs/backbone",
        "handlebars": "libs/Handlebars",
        "hbs": "libs/hbs",
        "json2": "libs/json2",
        "i18nprecompile": "libs/i18nprecompile",
        "leaflet": "libs/leaflet",
        "time_domain": "libs/time_domain",
        "fastclick": "libs/fastclick",
        "backbone.queryparams": "libs/backbone.queryparams",
        "backbone.subroute": "libs/backbone.subroute",
        "backbone.hal": "libs/backbone.hal"
    },

    // Sets the configuration for your third party scripts that are not AMD compatible
    shim: {
        "backbone": {
            "deps": ["underscore", "jquery"],
            "exports": "Backbone"  //attaches "Backbone" to the window object
        },
        "underscore": {
            "exports": "_"
        },
        "backbone.queryparams": {
            "deps": ["backbone"]
        },
        "leaflet": {
            "exports": "L"
        },
        "time_domain": {
            "exports": "TimeDomain"
        },
        "handlebars": {
            "exports": "Handlebars"
        },
        "json2": {
            "exports": "JSON"
        }
    },

    hbs: {
        templateExtension: 'handlebars',
        disableI18n: true,
        helperPathCallback: function(name) {return 'templates/helpers/' + name;}
    }
});

require(['modernizr','jquery','backbone', 'router', 'fastclick', 'backbone.queryparams'], function(Modernizr, $, Backbone, MoxieRouter, FastClick) {
    moxieRouter = new MoxieRouter();
    $.ajaxSetup({ headers: { 'Accept': 'application/hal+json;q=1.0, application/json;q=0.9, */*; q=0.01' } });
    Backbone.history.start();
    $('#home a').click(function(ev) {
        ev.preventDefault();
        $('body').toggleClass('is-sidebar-active');
        return false;
    });
    $('.overlay, #sidebar a').click(function(ev) {
        $('body').toggleClass('is-sidebar-active');
    });
    window.addEventListener('load', function() {
        new FastClick(document.body);
    }, false);
});
<|endoftext|>


<commit_before>'use strict'
const slapp = require('../slackSetup.js').slapp
const getRadius = require('../radius.js').getRadius
const tinyurl = require('tinyurl');
const request = require('request')
const where = require('node-where')

// route functions
const snapsByGeo = require('./routes/snapsByGeoRoute.js').snapsByGeo
const routeFuncs = require('./routes/routesIndex.js')
const yes = require('./routes/yes.js').yes
const addressToGeo = require('./routes/addressToGeo.js').addressToGeo
const appDl = require('./routes/appDlRoute.js').appDl
const teamSettings = require('../teamSettings.js').teamSettings

const notify = require('./notifySlash.js').notify

let newTeam = false

//db imports
const firebase    = require('../firebaseSetup.js'),
      db = firebase.db,
      snaps = firebase.snaps,
      tags = firebase.tags,
      users = firebase.users,
      slackDb = firebase.slackDb

let jayBtns={
  text: "",
  attachments: [{
    text: 'How can I help?',
    fallback: 'Where to today?',
    callback_id: 'jaywalk_callback',
    color: 'good',
    actions: [
      {
        name: 'answer',
        text: 'Find deals',
        type: 'button',
        value: 'address'
      },{
        name: 'answer',
        text: 'Settings',
        type: 'button',
        value: 'settings'
      },{
        name: 'answer',
        text: 'Download app',
        type: 'button',
        value: 'app'
      }
    ]
  }]
}

let newTeamCallback = (newOld,msg,state)=>{
  if(newTeam==true){
    msg.route('setup', state,30)
  }else if (newTeam==false){
    msg.route('main', state,30)
  }
}

 //text:`Welcom to Jaywalk! To get better results, please enter the address or your buisness name and city.`
const jaywalk = function() {
  let state = { requested: Date.now() }
  let teamId = ''
  let teamInfo = {}
  let answer

  slapp.command('/jaywalk', (msg, text) => {
    teamInfo = slackDb
      .child(msg.body.team_id)
      .once("value")
      .then(function(obj){
        if(obj.val()==null){
          newTeam=true
          newTeamCallback(newTeam,msg)
        }else{
          newTeam=false
          newTeamCallback(newTeam,msg,state)
          teamInfo = obj.val()
        }
      })
      // .then(function(){ // wait for database check for new users
      //   console.log('.then',newTeam)

      // })
  })

// slapp.action('jaywalk_callback', 'answer', (msg, value) => {

  .route('requestToDatabase', (msg, state) => {
    if(msg.body.actions==undefined){      // try callback then remove this
      msg.route('requestToDatabase', state, 30)
    }else{
      answer = msg.body.actions[0].value
      if(answer == 'app'){
        appDl(teamInfo,msg,state)
      }else if(answer == 'address'){
        yes(teamInfo,msg,state)
        //https://jaywalk-geo.herokuapp.com/geoloc.htm
        // .route('handleGeoLoc', state, 60)
      }else if(answer == 'settings'){
        teamSettings(teamInfo,msg,state)
      }else if(answer == 'notifications'){
        notify(teamInfo,msg,state)
      }else{ //handle error
        return msg
          .say("Whoops, you just have to pick a button...")
          .say('Click a button!')
          .route('requestToDatabase', state, 60)
      }
    } //end else(actions undefined checker)
  }) //end .route('requestToDatabase')
  // }) //end callback
  .route('main', (msg,state) => {
    msg
      .say(jayBtns)
      .route('requestToDatabase', state, 30)
  })//end .route(main)
  .route('setup', (msg,state) => {
    let teamObj={
      team_id: msg.body.team_id,
      team_name: msg.body.team_domain,
      location:"",
      lat:"",
      lng:"",
      slack_token: msg.body.token, //given at auth
      bot_token: "ahjsabjklsdbjkl",
      webhook: "msg.body.incoming_webhook", //given at auth
      channel_id: "msg.body.channel_id",
      channel_name: "msg.body.channel_name",}
    teamInfo.team_id = msg.body.team_id
    slackDb.child(msg.body.team_id).set(teamObj)
    msg.say({text:'setup mode goes here'})
  })//end .route(setup)
  .route('relaventAsk', (msg,state) => {
    msg.say({text: 'relaventAsk'})
    routeFuncs.relaventAsk(msg,state)
  })//end .route(relaventAsk)
  .route('address_geo', (msg,state) => {
    let text = (msg.body.event && msg.body.event.text) || ''
    where.is(text,function(err,result){
      /*
        result.get('')=>
        address,streetNumber, street,streetAddress,city,region,
        regionCode, postalCode, country, countryCode, lat, lng
      */
      if (result) {
        let lat = result.get('lat')
        let lng = result.get('lng')
        snapsByGeo(lat,lng,msg,state)
      }
    })
  })
}
module.exports = {
  jaywalk:jaywalk(),
  jayBtns:jayBtns
}

<commit_msg>route from callback<commit_after>'use strict'
const slapp = require('../slackSetup.js').slapp
const getRadius = require('../radius.js').getRadius
const tinyurl = require('tinyurl');
const request = require('request')
const where = require('node-where')

// route functions
const snapsByGeo = require('./routes/snapsByGeoRoute.js').snapsByGeo
const routeFuncs = require('./routes/routesIndex.js')
const yes = require('./routes/yes.js').yes
const addressToGeo = require('./routes/addressToGeo.js').addressToGeo
const appDl = require('./routes/appDlRoute.js').appDl
const teamSettings = require('../teamSettings.js').teamSettings

const notify = require('./notifySlash.js').notify

let newTeam = false

//db imports
const firebase    = require('../firebaseSetup.js'),
      db = firebase.db,
      snaps = firebase.snaps,
      tags = firebase.tags,
      users = firebase.users,
      slackDb = firebase.slackDb

let jayBtns={
  text: "",
  attachments: [{
    text: 'How can I help?',
    fallback: 'Where to today?',
    callback_id: 'jaywalk_callback',
    color: 'good',
    actions: [
      {
        name: 'answer',
        text: 'Find deals',
        type: 'button',
        value: 'address'
      },{
        name: 'answer',
        text: 'Settings',
        type: 'button',
        value: 'settings'
      },{
        name: 'answer',
        text: 'Download app',
        type: 'button',
        value: 'app'
      }
    ]
  }]
}

let newTeamCallback = (msg,state)=>{
      let teamObj={
      team_id: msg.body.team_id,
      team_name: msg.body.team_domain,
      location:"",
      lat:"",
      lng:"",
      slack_token: msg.body.token, //given at auth
      bot_token: "ahjsabjklsdbjkl",
      webhook: "msg.body.incoming_webhook", //given at auth
      channel_id: "msg.body.channel_id",
      channel_name: "msg.body.channel_name",}
    teamInfo.team_id = msg.body.team_id
    slackDb.child(msg.body.team_id).set(teamObj)
    msg.say({text:'setup mode goes here'})
}
let oldTeamCallback = (msg,state)=>{
      msg
      .say(jayBtns)
      .route('requestToDatabase', state, 30)
}

 //text:`Welcom to Jaywalk! To get better results, please enter the address or your buisness name and city.`
const jaywalk = function() {
  let state = { requested: Date.now() }
  let teamId = ''
  let teamInfo = {}
  let answer

  slapp.command('/jaywalk', (msg, text) => {
    teamInfo = slackDb
      .child(msg.body.team_id)
      .once("value")
      .then(function(obj){
        if(obj.val()==null){
          newTeamCallback(msg,state)
        }else{
          oldTeamCallback(msg,state)
          teamInfo = obj.val()
        }
      })
  })

// slapp.action('jaywalk_callback', 'answer', (msg, value) => {

  .route('requestToDatabase', (msg, state) => {
    if(msg.body.actions==undefined){      // try callback then remove this
      msg.route('requestToDatabase', state, 30)
    }else{
      answer = msg.body.actions[0].value
      if(answer == 'app'){
        appDl(teamInfo,msg,state)
      }else if(answer == 'address'){
        yes(teamInfo,msg,state)
        //https://jaywalk-geo.herokuapp.com/geoloc.htm
        // .route('handleGeoLoc', state, 60)
      }else if(answer == 'settings'){
        teamSettings(teamInfo,msg,state)
      }else if(answer == 'notifications'){
        notify(teamInfo,msg,state)
      }else{ //handle error
        return msg
          .say("Whoops, you just have to pick a button...")
          .say('Click a button!')
          .route('requestToDatabase', state, 60)
      }
    } //end else(actions undefined checker)
  }) //end .route('requestToDatabase')
  // }) //end callback
  .route('main', (msg,state) => {

  })//end .route(main)
  .route('setup', (msg,state) => {

  })//end .route(setup)
  .route('relaventAsk', (msg,state) => {
    msg.say({text: 'relaventAsk'})
    routeFuncs.relaventAsk(msg,state)
  })//end .route(relaventAsk)
  .route('address_geo', (msg,state) => {
    let text = (msg.body.event && msg.body.event.text) || ''
    where.is(text,function(err,result){
      /*
        result.get('')=>
        address,streetNumber, street,streetAddress,city,region,
        regionCode, postalCode, country, countryCode, lat, lng
      */
      if (result) {
        let lat = result.get('lat')
        let lng = result.get('lng')
        snapsByGeo(lat,lng,msg,state)
      }
    })
  })
}
module.exports = {
  jaywalk:jaywalk(),
  jayBtns:jayBtns
}

<|endoftext|>