<commit_before>'use strict';

var forEach = require('lodash/collection/forEach');

/**
 * A handler that implements reversible replacing of shapes.
 * Internally the old shape will be removed and the new shape will be added.
 *
 *
 * @class
 * @constructor
 *
 * @param {canvas} Canvas
 */
function ReplaceShapeHandler(modeling, rules) {
  this._modeling = modeling;
  this._rules = rules;
}

ReplaceShapeHandler.$inject = [ 'modeling', 'rules' ];

module.exports = ReplaceShapeHandler;

////// api /////////////////////////////////////////

/**
 * Replaces a shape with an replacement Element.
 *
 * The newData object should contain type, x, y.
 *
 * If possible also the incoming/outgoing connection
 * will be restored.
 *
 * @param {Object} context
 */
 ReplaceShapeHandler.prototype.preExecute = function(context) {

  var modeling = this._modeling;

  var oldShape = context.oldShape,
      newData = context.newData,
      newShape;

  var pos = {
    x: newData.x,
    y: newData.y
  };

  newShape = context.newShape = modeling.createShape(newData, pos, oldShape.parent);

  return context.newShape;
};

ReplaceShapeHandler.prototype.execute = function(context) {

  var modeling = this._modeling,
         rules = this._rules;

  var oldShape = context.oldShape,
      newShape = context.newShape,
      incoming = oldShape.incoming.slice(),
      outgoing = oldShape.outgoing.slice();

  forEach(incoming, function(connection) {
    var lastIndex = connection.waypoints.length - 1;
    if (canConnect(connection.source, newShape)) {
      modeling.reconnectEnd(connection, newShape, connection.waypoints[lastIndex]);
    }
  });

  forEach(outgoing, function(connection) {
    if (canConnect(newShape, connection.target)) {
      modeling.reconnectStart(connection, newShape, connection.waypoints[0]);
    }
  });

  function canConnect(source, target) {

    return rules.allowed('connection.create', {
      source: source,
      target: target
    });
  }
};

ReplaceShapeHandler.prototype.postExecute = function(context) {

  var modeling = this._modeling;

  var oldShape = context.oldShape;

  modeling.removeShape(oldShape);
};

ReplaceShapeHandler.prototype.revert = function(context) {
};
<commit_msg>fix(modeling): reconnect during replace via pre-execute<commit_after>'use strict';

var forEach = require('lodash/collection/forEach');

/**
 * A handler that implements reversible replacing of shapes.
 * Internally the old shape will be removed and the new shape will be added.
 *
 *
 * @class
 * @constructor
 *
 * @param {canvas} Canvas
 */
function ReplaceShapeHandler(modeling, rules) {
  this._modeling = modeling;
  this._rules = rules;
}

ReplaceShapeHandler.$inject = [ 'modeling', 'rules' ];

module.exports = ReplaceShapeHandler;

////// api /////////////////////////////////////////

/**
 * Replaces a shape with an replacement Element.
 *
 * The newData object should contain type, x, y.
 *
 * If possible also the incoming/outgoing connection
 * will be restored.
 *
 * @param {Object} context
 */
 ReplaceShapeHandler.prototype.preExecute = function(context) {

  var modeling = this._modeling,
      rules = this._rules;

  var oldShape = context.oldShape,
      newData = context.newData,
      newShape;

  function canConnect(source, target) {

    return rules.allowed('connection.create', {
      source: source,
      target: target
    });
  }

  // (1) place a new shape at the given position

  var position = {
    x: newData.x,
    y: newData.y
  };

  newShape = context.newShape = context.newShape || modeling.createShape(newData, position, oldShape.parent);

  // (2) reconnect connections to the new shape (where allowed)

  var incoming = oldShape.incoming.slice(),
      outgoing = oldShape.outgoing.slice();

  forEach(incoming, function(connection) {
    var lastIndex = connection.waypoints.length - 1;
    if (canConnect(connection.source, newShape)) {
      modeling.reconnectEnd(connection, newShape, connection.waypoints[lastIndex]);
    }
  });

  forEach(outgoing, function(connection) {
    if (canConnect(newShape, connection.target)) {
      modeling.reconnectStart(connection, newShape, connection.waypoints[0]);
    }
  });
};

ReplaceShapeHandler.prototype.postExecute = function(context) {
  var modeling = this._modeling;

  var oldShape = context.oldShape;

  modeling.removeShape(oldShape);
};

ReplaceShapeHandler.prototype.execute = function(context) { };

ReplaceShapeHandler.prototype.revert = function(context) {};
<|endoftext|>


<commit_before>var CHARME_URL = 'http://charme-test.cems.rl.ac.uk/sparql';

// Template SPARQL query for finding the number of citations attached to a dataset
var FIND_NUM_CITATIONS = 'PREFIX oa: <http://www.w3.org/ns/oa#> ' +
                         'PREFIX cito: <http://purl.org/spar/cito/> ' +
                         'SELECT (COUNT(?citer) as ?numOfCitations) ' +
                         'WHERE { ' +
                            'GRAPH <http://localhost:3333/privateds/data/submitted> { ' +
                               '?anno a oa:Annotation . ' +
                               '?anno cito:hasCitedEntity <${uri}> . ' +
                               '?anno cito:hasCitingEntity ?citer . ' +
                             '}' +
                         '}';

var FIND_CITATIONS = 'PREFIX oa: <http://www.w3.org/ns/oa#> ' +
                         'PREFIX cito: <http://purl.org/spar/cito/> ' +
                         'SELECT ?publication ' +
                         'WHERE { ' +
                            'GRAPH <http://localhost:3333/privateds/data/submitted> { ' +
                               '?cite a <http://purl.org/spar/cito/CitationAct> . ' +
                               '?cite cito:hasCitedEntity <${dataset}> . ' +
                               '?cite cito:hasCitingEntity ?publication . ' +
                             '}' +
                         '}';

// For the hack we use a global variable to hold the datasets that have been returned
// from the server.
var datasets = null;

// Called when the window is loaded
window.onload = function() {
  // Does nothing yet
}

// Called when the Search button is clicked
function searchButtonClicked() {
  // At the moment we ignore the search string!
  // We load the list of datasets from the server. In a real system we would call a
  // web service here, but for now we just load a static file from GitHub!
  $.ajax({
    url: 'datasets.json',
    type: 'GET',
    crossDomain: true,
    dataType: 'json',
    success: function(response) {
      datasets = response.datasets;
      updateDatasets();
    },
    error: function (xhr, status) {
      alert('error status = ' + status);
    }
  });
}

// Updates the datasets on the left-hand list
function updateDatasets() {
  // Clear the existing list of datasets
  $('#datasets li').remove();
  // Add each dataset to the list of datasets
  for (var i = 0; i < datasets.length; i++) {
    var dataset = datasets[i];
    $('#datasets ul').append("
" + dataset.title + "
");
  }
  // Turn the list of datasets into a selector
  createSelector('#datasets li');
}

// Creates a selector widget, given the identifier of a list
function createSelector(selector) {
  var $options = $(selector);
  $options.click(function(e) {
    // get the selected dataset
    var $li = $(e.target);
    // deselect all list items, then select the clicked one
    $options.removeClass('selected');
    $li.addClass('selected');

    // Get the dataset that has been selected
    var datasetId = $('#datasets li.selected').attr('datasetid');
    var dataset = datasets[datasetId];

    // Use the dataset's title to update the title of the Annotations window
    $('#datasetid').text(dataset.title);
    $('#datasetabstract').text(dataset.abstract);
    $('#dataseturi').html("" + dataset.uri + "");

    // Create the query string we want to use
    var queryString = FIND_CITATIONS.replace('${dataset}', dataset.uri);
    //alert(queryString);

    // Query the server, calling the given function on success
    queryServer(queryString, function(response) {
      alert(response.results.bindings.length + ' citations');
    });

  });
}

// Queries the CHARMe node with the given query string. Server returns JSON, which is
// then passed to the given callback function
function queryServer(query, callback) {
  $.ajax({
    url: CHARME_URL,
    data: 'query=' + encodeURIComponent(query) + '&output=json',
    type: 'GET',
    crossDomain: true,
    dataType: 'json',
    success: callback,
    error: function (xhr, status) {
      alert('error status = ' + status);
    }
  });
}
<commit_msg>Add function to get citation from DOI<commit_after>var CHARME_URL = 'http://charme-test.cems.rl.ac.uk/sparql';

// Template SPARQL query for finding the number of citations attached to a dataset
var FIND_NUM_CITATIONS = 'PREFIX oa: <http://www.w3.org/ns/oa#> ' +
                         'PREFIX cito: <http://purl.org/spar/cito/> ' +
                         'SELECT (COUNT(?citer) as ?numOfCitations) ' +
                         'WHERE { ' +
                            'GRAPH <http://localhost:3333/privateds/data/submitted> { ' +
                               '?anno a oa:Annotation . ' +
                               '?anno cito:hasCitedEntity <${uri}> . ' +
                               '?anno cito:hasCitingEntity ?citer . ' +
                             '}' +
                         '}';

var FIND_CITATIONS = 'PREFIX oa: <http://www.w3.org/ns/oa#> ' +
                         'PREFIX cito: <http://purl.org/spar/cito/> ' +
                         'SELECT ?publication ' +
                         'WHERE { ' +
                            'GRAPH <http://localhost:3333/privateds/data/submitted> { ' +
                               '?cite a <http://purl.org/spar/cito/CitationAct> . ' +
                               '?cite cito:hasCitedEntity <${dataset}> . ' +
                               '?cite cito:hasCitingEntity ?publication . ' +
                             '}' +
                         '}';

// For the hack we use a global variable to hold the datasets that have been returned
// from the server.
var datasets = null;

// Called when the window is loaded
window.onload = function() {
  // Does nothing yet
}

// Called when the Search button is clicked
function searchButtonClicked() {
  // At the moment we ignore the search string!
  // We load the list of datasets from the server. In a real system we would call a
  // web service here, but for now we just load a static file from GitHub!
  $.ajax({
    url: 'datasets.json',
    type: 'GET',
    crossDomain: true,
    dataType: 'json',
    success: function(response) {
      datasets = response.datasets;
      updateDatasets();
    },
    error: function (xhr, status) {
      alert('error status = ' + status);
    }
  });
}

// Updates the datasets on the left-hand list
function updateDatasets() {
  // Clear the existing list of datasets
  $('#datasets li').remove();
  // Add each dataset to the list of datasets
  for (var i = 0; i < datasets.length; i++) {
    var dataset = datasets[i];
    $('#datasets ul').append("
" + dataset.title + "
");
  }
  // Turn the list of datasets into a selector
  createSelector('#datasets li');
}

// Creates a selector widget, given the identifier of a list
function createSelector(selector) {
  var $options = $(selector);
  $options.click(function(e) {
    // get the selected dataset
    var $li = $(e.target);
    // deselect all list items, then select the clicked one
    $options.removeClass('selected');
    $li.addClass('selected');

    // Get the dataset that has been selected
    var datasetId = $('#datasets li.selected').attr('datasetid');
    var dataset = datasets[datasetId];

    // Use the dataset's title to update the title of the Annotations window
    $('#datasetid').text(dataset.title);
    $('#datasetabstract').text(dataset.abstract);
    $('#dataseturi').html("" + dataset.uri + "");

    // Create the query string we want to use
    var queryString = FIND_CITATIONS.replace('${dataset}', dataset.uri);
    //alert(queryString);

    // Query the server, calling the given function on success
    queryServer(queryString, function(data) {
      console.log(data);
      citationFromDOI(data.results.bindings[0].publication.value.split(":")[1]);
    });

  });
}

// Queries the CHARMe node with the given query string. Server returns JSON, which is
// then passed to the given callback function
function queryServer(query, callback) {
  $.ajax({
    url: CHARME_URL,
    data: 'query=' + encodeURIComponent(query) + '&output=json',
    type: 'GET',
    crossDomain: true,
    dataType: 'json',
    success: callback,
    error: function (xhr, status) {
      alert('error status = ' + status);
    }
  });
}

function citationFromDOI(doi) {
  $.ajax({
    url: 'http://dx.doi.org/' + doi,
    type: 'GET',
    headers: {"Accept": "application/vnd.citationstyles.csl+json;q=1.0"},
    success: function(data) { console.log(data); }
  });
}
<|endoftext|>


<commit_before>/**
 * @file DraggableListItem component
 * @author liangxiaojun(liangxiaojun@derbysoft.com)
 */

import React, {Component} from 'react';
import PropTypes from 'prop-types';

// Components
import {Draggable} from 'react-beautiful-dnd';
import Checkbox from '../Checkbox';
import Radio from '../Radio';
import CircularLoading from '../CircularLoading';
import TipProvider from '../TipProvider';

// Statics
import Theme from '../Theme';

// Vendors
import classNames from 'classnames';
import Util from '../_vendors/Util';
import Position from '../_statics/Position';
import SelectMode from '../_statics/SelectMode';

class DraggableListItem extends Component {

    static SelectMode = SelectMode;
    static Theme = Theme;

    constructor(props, ...restArgs) {
        super(props, ...restArgs);
    }

    handleCheckboxChange = checked => {
        if (checked) {
            this.props.onSelect?.();
        } else {
            this.props.onDeselect?.();
        }
    };

    handleRadioChange = () => {
        if (!this.props.checked) {
            this.props.onSelect?.();
        }
    };

    handleClick = e => {

        e.preventDefault();

        const {disabled, isLoading, readOnly} = this.props;

        if (disabled || isLoading || readOnly) {
            return;
        }

        this.props.onClick?.(e);

        switch (this.props.selectMode) {
            case SelectMode.MULTI_SELECT:
                this.handleCheckboxChange(!this.props.checked);
                return;
            case SelectMode.SINGLE_SELECT:
                this.handleRadioChange();
                return;
        }

    };

    render() {

        const {

                index, className, style, theme, data, text, desc, title, iconCls, rightIconCls, tip, tipPosition,
                disabled, isLoading, renderer, itemRenderer, readOnly, isDragDisabled, anchorIconCls,

                checked, selectTheme, selectMode, radioUncheckedIconCls, radioCheckedIconCls,
                checkboxUncheckedIconCls, checkboxCheckedIconCls, checkboxIndeterminateIconCls,

                onMouseEnter, onMouseLeave

            } = this.props,

            loadingIconPosition = (rightIconCls && !iconCls) ? 'right' : 'left';

        return (
            <Draggable key={index}
                       draggableId={'' + index}
                       index={index}
                       isDragDisabled={isDragDisabled}>
                {
                    (dragProvided, dragSnapshot) => (

                                <TipProvider className="block"
                                             tipContent={tip}
                                             position={tipPosition}>

                                    <div className={classNames('draggable-list-item', {
                                        [`theme-${theme}`]: theme,
                                        activated: checked,
                                        dragging: dragSnapshot.isDragging,
                                        [className]: className
                                    })}
                                         style={style}
                                         disabled={disabled || isLoading}
                                         readOnly={readOnly}
                                         title={title}
                                         onClick={this.handleClick}
                                         onMouseEnter={onMouseEnter}
                                         onMouseLeave={onMouseLeave}>

                                        {
                                            selectMode === SelectMode.SINGLE_SELECT &&
                                            (radioUncheckedIconCls || radioCheckedIconCls) ?
                                                <Radio className="draggable-list-item-select"
                                                       theme={selectTheme}
                                                       checked={checked}
                                                       disabled={disabled || isLoading}
                                                       uncheckedIconCls={radioUncheckedIconCls}
                                                       checkedIconCls={radioCheckedIconCls}
                                                       disableTouchRipple={true}/>
                                                :
                                                null
                                        }

                                        {
                                            selectMode === SelectMode.MULTI_SELECT ?
                                                <Checkbox className="draggable-list-item-select"
                                                          theme={selectTheme}
                                                          checked={checked}
                                                          disabled={disabled || isLoading}
                                                          uncheckedIconCls={checkboxUncheckedIconCls}
                                                          checkedIconCls={checkboxCheckedIconCls}
                                                          indeterminateIconCls={checkboxIndeterminateIconCls}
                                                          disableTouchRipple={true}/>
                                                :
                                                null
                                        }

                                        {
                                            isLoading && loadingIconPosition === 'left' ?

                                                    <CircularLoading className="button-loading-icon"
                                                                     size="small"/>

                                                :
                                                (
                                                    iconCls ?
                                                        <i className={`button-icon button-icon-left ${iconCls}`}
                                                           aria-hidden="true"/>
                                                        :
                                                        null
                                                )
                                        }

                                        {
                                            itemRenderer && typeof itemRenderer === 'function' ?
                                                itemRenderer(data, index)
                                                :
                                                (
                                                    renderer && typeof renderer === 'function' ?
                                                        renderer(data, index)
                                                        :
                                                        (
                                                            desc ?

                                                                        {text}

                                                                        {desc}

                                                                :
                                                                text
                                                        )
                                                )
                                        }

                                        {
                                            isLoading && loadingIconPosition === 'right' ?
                                                <CircularLoading
                                                    className="button-icon button-icon-right button-loading-icon"
                                                    size="small"/>
                                                :
                                                (
                                                    rightIconCls ?
                                                        <i className={`button-icon button-icon-right ${rightIconCls}`}
                                                           aria-hidden="true"/>
                                                        :
                                                        null
                                                )
                                        }

                                        <i className={`${anchorIconCls} draggable-list-item-anchor`}
                                           aria-hidden="true"/>

                                </TipProvider>

                            {dragProvided.placeholder}

                    )
                }
            </Draggable>
        );

    }
}

DraggableListItem.propTypes = {

    index: PropTypes.number,

    className: PropTypes.string,
    style: PropTypes.object,
    theme: PropTypes.oneOf(Util.enumerateValue(Theme)),

    selectTheme: PropTypes.oneOf(Util.enumerateValue(Theme)),
    selectMode: PropTypes.oneOf(Util.enumerateValue(SelectMode)),

    data: PropTypes.oneOfType([PropTypes.string, PropTypes.number, PropTypes.object]),
    value: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
    text: PropTypes.any,
    desc: PropTypes.string,
    title: PropTypes.string,

    disabled: PropTypes.bool,
    isLoading: PropTypes.bool,
    checked: PropTypes.bool,
    readOnly: PropTypes.bool,

    iconCls: PropTypes.string,
    rightIconCls: PropTypes.string,

    tip: PropTypes.string,
    tipPosition: PropTypes.oneOf(Util.enumerateValue(Position)),

    radioUncheckedIconCls: PropTypes.string,
    radioCheckedIconCls: PropTypes.string,
    checkboxUncheckedIconCls: PropTypes.string,
    checkboxCheckedIconCls: PropTypes.string,
    checkboxIndeterminateIconCls: PropTypes.string,

    isDragDisabled: PropTypes.bool,
    anchorIconCls: PropTypes.string,

    itemRenderer: PropTypes.func,
    renderer: PropTypes.func,

    onClick: PropTypes.func,
    onSelect: PropTypes.func,
    onDeselect: PropTypes.func,
    onMouseEnter: PropTypes.func,
    onMouseLeave: PropTypes.func

};

DraggableListItem.defaultProps = {

    index: 0,

    theme: Theme.DEFAULT,

    selectTheme: Theme.DEFAULT,
    selectMode: SelectMode.SINGLE_SELECT,

    disabled: false,
    isLoading: false,
    checked: false,
    readOnly: false,

    tipPosition: Position.BOTTOM,

    checkboxUncheckedIconCls: 'far fa-square',
    checkboxCheckedIconCls: 'fas fa-check-square',
    checkboxIndeterminateIconCls: 'fas fa-minus-square',

    isDragDisabled: false,
    anchorIconCls: 'fas fa-bars'

};

export default DraggableListItem;
<commit_msg>update DraggableListItem<commit_after>/**
 * @file DraggableListItem component
 * @author liangxiaojun(liangxiaojun@derbysoft.com)
 */

import React, {Component} from 'react';
import PropTypes from 'prop-types';

// Components
import {Draggable} from 'react-beautiful-dnd';
import Checkbox from '../Checkbox';
import Radio from '../Radio';
import CircularLoading from '../CircularLoading';
import TipProvider from '../TipProvider';

// Statics
import Theme from '../Theme';

// Vendors
import classNames from 'classnames';
import Util from '../_vendors/Util';
import Position from '../_statics/Position';
import SelectMode from '../_statics/SelectMode';

class DraggableListItem extends Component {

    static SelectMode = SelectMode;
    static Theme = Theme;

    constructor(props, ...restArgs) {
        super(props, ...restArgs);
    }

    handleCheckboxChange = checked => {
        if (checked) {
            this.props.onSelect?.();
        } else {
            this.props.onDeselect?.();
        }
    };

    handleRadioChange = () => {
        if (!this.props.checked) {
            this.props.onSelect?.();
        }
    };

    handleClick = e => {

        e.preventDefault();

        const {disabled, isLoading, readOnly} = this.props;

        if (disabled || isLoading || readOnly) {
            return;
        }

        this.props.onClick?.(e);

        switch (this.props.selectMode) {
            case SelectMode.MULTI_SELECT:
                this.handleCheckboxChange(!this.props.checked);
                return;
            case SelectMode.SINGLE_SELECT:
                this.handleRadioChange();
                return;
        }

    };

    render() {

        const {

                index, className, style, theme, data, text, desc, title, iconCls, rightIconCls, tip, tipPosition,
                disabled, isLoading, renderer, itemRenderer, readOnly, isDragDisabled, anchorIconCls,

                checked, selectTheme, selectMode, radioUncheckedIconCls, radioCheckedIconCls,
                checkboxUncheckedIconCls, checkboxCheckedIconCls, checkboxIndeterminateIconCls,

                onMouseEnter, onMouseLeave

            } = this.props,

            loadingIconPosition = (rightIconCls && !iconCls) ? 'right' : 'left';

        return (
            <Draggable key={index}
                       draggableId={'' + index}
                       index={index}
                       isDragDisabled={isDragDisabled}>
                {
                    (dragProvided, dragSnapshot) => (

                                <TipProvider className="block"
                                             tipContent={tip}
                                             position={tipPosition}>

                                    <div className={classNames('draggable-list-item', {
                                        [`theme-${theme}`]: theme,
                                        activated: checked,
                                        dragging: dragSnapshot.isDragging,
                                        'drag-disabled': isDragDisabled,
                                        [className]: className
                                    })}
                                         style={style}
                                         disabled={disabled || isLoading}
                                         readOnly={readOnly}
                                         title={title}
                                         onClick={this.handleClick}
                                         onMouseEnter={onMouseEnter}
                                         onMouseLeave={onMouseLeave}>

                                        {
                                            selectMode === SelectMode.SINGLE_SELECT &&
                                            (radioUncheckedIconCls || radioCheckedIconCls) ?
                                                <Radio className="draggable-list-item-select"
                                                       theme={selectTheme}
                                                       checked={checked}
                                                       disabled={disabled || isLoading}
                                                       uncheckedIconCls={radioUncheckedIconCls}
                                                       checkedIconCls={radioCheckedIconCls}
                                                       disableTouchRipple={true}/>
                                                :
                                                null
                                        }

                                        {
                                            selectMode === SelectMode.MULTI_SELECT ?
                                                <Checkbox className="draggable-list-item-select"
                                                          theme={selectTheme}
                                                          checked={checked}
                                                          disabled={disabled || isLoading}
                                                          uncheckedIconCls={checkboxUncheckedIconCls}
                                                          checkedIconCls={checkboxCheckedIconCls}
                                                          indeterminateIconCls={checkboxIndeterminateIconCls}
                                                          disableTouchRipple={true}/>
                                                :
                                                null
                                        }

                                        {
                                            isLoading && loadingIconPosition === 'left' ?

                                                    <CircularLoading className="button-loading-icon"
                                                                     size="small"/>

                                                :
                                                (
                                                    iconCls ?
                                                        <i className={`button-icon button-icon-left ${iconCls}`}
                                                           aria-hidden="true"/>
                                                        :
                                                        null
                                                )
                                        }

                                        {
                                            itemRenderer && typeof itemRenderer === 'function' ?
                                                itemRenderer(data, index)
                                                :
                                                (
                                                    renderer && typeof renderer === 'function' ?
                                                        renderer(data, index)
                                                        :
                                                        (
                                                            desc ?

                                                                        {text}

                                                                        {desc}

                                                                :
                                                                text
                                                        )
                                                )
                                        }

                                        {
                                            isLoading && loadingIconPosition === 'right' ?
                                                <CircularLoading
                                                    className="button-icon button-icon-right button-loading-icon"
                                                    size="small"/>
                                                :
                                                (
                                                    rightIconCls ?
                                                        <i className={`button-icon button-icon-right ${rightIconCls}`}
                                                           aria-hidden="true"/>
                                                        :
                                                        null
                                                )
                                        }

                                        <i className={`${anchorIconCls} draggable-list-item-anchor`}
                                           aria-hidden="true"/>

                                </TipProvider>

                            {dragProvided.placeholder}

                    )
                }
            </Draggable>
        );

    }
}

DraggableListItem.propTypes = {

    index: PropTypes.number,

    className: PropTypes.string,
    style: PropTypes.object,
    theme: PropTypes.oneOf(Util.enumerateValue(Theme)),

    selectTheme: PropTypes.oneOf(Util.enumerateValue(Theme)),
    selectMode: PropTypes.oneOf(Util.enumerateValue(SelectMode)),

    data: PropTypes.oneOfType([PropTypes.string, PropTypes.number, PropTypes.object]),
    value: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
    text: PropTypes.any,
    desc: PropTypes.string,
    title: PropTypes.string,

    disabled: PropTypes.bool,
    isLoading: PropTypes.bool,
    checked: PropTypes.bool,
    readOnly: PropTypes.bool,

    iconCls: PropTypes.string,
    rightIconCls: PropTypes.string,

    tip: PropTypes.string,
    tipPosition: PropTypes.oneOf(Util.enumerateValue(Position)),

    radioUncheckedIconCls: PropTypes.string,
    radioCheckedIconCls: PropTypes.string,
    checkboxUncheckedIconCls: PropTypes.string,
    checkboxCheckedIconCls: PropTypes.string,
    checkboxIndeterminateIconCls: PropTypes.string,

    isDragDisabled: PropTypes.bool,
    anchorIconCls: PropTypes.string,

    itemRenderer: PropTypes.func,
    renderer: PropTypes.func,

    onClick: PropTypes.func,
    onSelect: PropTypes.func,
    onDeselect: PropTypes.func,
    onMouseEnter: PropTypes.func,
    onMouseLeave: PropTypes.func

};

DraggableListItem.defaultProps = {

    index: 0,

    theme: Theme.DEFAULT,

    selectTheme: Theme.DEFAULT,
    selectMode: SelectMode.SINGLE_SELECT,

    disabled: false,
    isLoading: false,
    checked: false,
    readOnly: false,

    tipPosition: Position.BOTTOM,

    checkboxUncheckedIconCls: 'far fa-square',
    checkboxCheckedIconCls: 'fas fa-check-square',
    checkboxIndeterminateIconCls: 'fas fa-minus-square',

    isDragDisabled: false,
    anchorIconCls: 'fas fa-bars'

};

export default DraggableListItem;
<|endoftext|>


<commit_before>// x - coordinate of this body - Number
// y - coordinate of this body - Number
// speed - in tick by frame
// sprites - array of images (sprite of one image)
class Body {
    constructor(context, x, y, sprites, speed, soundEffect) {
        this._startTime = 0;
        // validate speed
        this._speed = speed;
        this.spriteNumber = 0;
        // validate sprites
        this.x = x;
        this.y = y;
        this.sprites = sprites;
        // validate context
        this.context = context;
        this.isAlive = true;
        this.soundEffect = soundEffect;
    }
    get x() {
        return this._x;
    }
    set x(x) {
        Validator.Number(x);
        this._x = x;
    }
    get y() {
        return this._y;
    }
    set y(y) {
        Validator.Number(y);
        this._y = y;
    }

    get sprites() {
        return this._sprites
    }

    set sprites(sprites) {
        // Validate image
        Validator.NotNullArray(sprites);
        this._sprites = sprites;
    }

    // methods
    indexSprite(index) {
        index = index >= this.sprites.length ? 0 : index;
        this.context.drawImage(this.sprites[index].img, this.x, this.y)
        // this.tryStroke(); // this command show the red contour - collising contour
        return this
    }

    nextSprite() {
        this.indexSprite(this.spriteNumber);
        if (!this._getTime()) {
            this.spriteNumber += 1;
        }
        this.spriteNumber = this.spriteNumber >= this.sprites.length ? 0 : this.spriteNumber;
        return this
    }

    isOn(otherBody) {
        if (!this.isAlive) {
            return false
        }
        let polygon = [];
        otherBody.sprites[otherBody.spriteNumber].cut
            .forEach(x => polygon.push([x[0] + otherBody.x, x[1] + otherBody.y]));

        //check if every point of cutting contour overlap from two object
        for (let index = 0; index < this.sprites[this.spriteNumber].cut.length; index++) {
            let element = this.sprites[this.spriteNumber].cut[index].slice();
            element[0] += this.x; element[1] += this.y;
            if (this._isPointInPoligon(element, polygon)) {
                return true
            }
        }
        return false
    }

    _getTime() {
        this._startTime++;

        if (this._startTime < this._speed) {
            return true
        }

        this._startTime = 0;
        return false;
    }

    tryStroke() {
        this.context.beginPath();
        this.context.moveTo(this.x + this.sprites[0].cut[0][0], this.y + this.sprites[0].cut[0][1]);
        this.sprites[0].cut.forEach(x => this.context.lineTo(this.x + x[0], this.y + x[1]));
        this.context.closePath();
        this.context.strokeStyle = "red";
        this.context.stroke();
    }

    _isPointInPoligon(point, vs) {
        // ray-casting algorithm based on
        // http://www.ecse.rpi.edu/Homepages/wrf/Research/Short_Notes/pnpoly.html

        var x = point[0], y = point[1];

        var inside = false;
        for (var i = 0, j = vs.length - 1; i < vs.length; j = i++) {
            var xi = vs[i][0], yi = vs[i][1];
            var xj = vs[j][0], yj = vs[j][1];

            var intersect = ((yi > y) != (yj > y))
                && (x < (xj - xi) * (y - yi) / (yj - yi) + xi);
            if (intersect) inside = !inside;
        }
        return inside;
    };
}<commit_msg>minor code improvements<commit_after>// x - coordinate of this body - Number
// y - coordinate of this body - Number
// speed - in tick by frame
// sprites - array of images (sprite of one image)
class Body {
    constructor(context, x, y, sprites, speed, soundEffect) {
        this._startTime = 0;
        // validate speed
        this._speed = speed;
        this.spriteNumber = 0;
        // validate sprites
        this.x = x;
        this.y = y;
        this.sprites = sprites;
        // validate context
        this.context = context;
        this.isAlive = true;
        this.soundEffect = soundEffect;
    }
    get x() {
        return this._x;
    }
    set x(x) {
        Validator.Number(x);
        this._x = x;
    }
    get y() {
        return this._y;
    }
    set y(y) {
        Validator.Number(y);
        this._y = y;
    }

    get sprites() {
        return this._sprites
    }

    set sprites(sprites) {
        // Validate image
        Validator.NotNullArray(sprites);
        this._sprites = sprites;
    }

    // methods
    indexSprite(index) {
        this.context.drawImage(this.sprites[index].img, this.x, this.y)
        // this.drawCollisionStroke(); // this command show the red contour - collising contour
        return this
    }

    nextSprite() {
        if (!this._getTime()) {
            this.spriteNumber += 1;
        }
        this.spriteNumber %= this.sprites.length;
        this.indexSprite(this.spriteNumber);
        return this
    }

    isOn(otherBody) {
        if (!this.isAlive) {
            return false
        }

        //precalculate collision contour of otherBody to glabal coordinates
        let polygon = [];
        otherBody.sprites[otherBody.spriteNumber].cut
            .forEach(x => polygon.push([x[0] + otherBody.x, x[1] + otherBody.y]));

        //check if at least one point of this collision contour
        //is inside of otherBody's collision contour
        for (let i = 0; i < this.sprites[this.spriteNumber].cut.length; i++) {
            let element = this.sprites[this.spriteNumber].cut[i].slice();
            element[0] += this.x; // set cutting x
            element[1] += this.y; // set cutting y
            if (this._isPointInPoligon(element, polygon)) {
                return true
            }
        }

        return false
    }

    _getTime() {
        this._startTime++;

        if (this._startTime < this._speed) {
            return true
        }

        this._startTime = 0;
        return false;
    }

    drawCollisionStroke() {
        this.context.beginPath();
        this.context.moveTo
            (
            this.x + this.sprites[0].cut[0][0],
            this.y + this.sprites[0].cut[0][1]
            );
        this.sprites[0].cut.
            forEach(x => this.context.lineTo(this.x + x[0], this.y + x[1]));
        this.context.closePath();
        this.context.strokeStyle = "red";
        this.context.stroke();
    }

    _isPointInPoligon(point, vs) {
        // ray-casting algorithm based on
        // http://www.ecse.rpi.edu/Homepages/wrf/Research/Short_Notes/pnpoly.html

        var x = point[0], y = point[1];

        var inside = false;
        for (var i = 0, j = vs.length - 1; i < vs.length; j = i++) {
            var xi = vs[i][0], yi = vs[i][1];
            var xj = vs[j][0], yj = vs[j][1];

            var intersect = ((yi > y) != (yj > y))
                && (x < (xj - xi) * (y - yi) / (yj - yi) + xi);
            if (intersect) inside = !inside;
        }
        return inside;
    };
}<|endoftext|>


<commit_before>var Statique = require("statique")
  , Start = require("./start")
  , Http = require("http")
  , Url = require("url")
  , Lien = require("lien")
  , Config = Bloggify.getConfig()
  , Theme = require("./theme")
  ;

var server = new Lien({
    host: Config.host
  , port: Config.port
  , root: Config.content
  , cache: Config.fileCache
});

Bloggify.initPlugins(function () {
    Theme(Config.content + Config.theme, function (err, themeObj) {
        if (err) { throw err; }

        server._sServer.setErrors(themeObj.errors);

        // Error pages
        server.page.add(/\/[4-9][0-9][0-9]\/?/, function (lien) {
            var m = lien.pathName.match(/\/(.*)\/?/) || []
              , code = parseInt(m[1])
              ;

            if (isNaN(code) || !themeObj.errors[code]) {
                return lien.end(404);
            }
            lien.file(themeObj.errors[code]);
        });

        // Blog posts
        server.page.add(new RegExp(Config.blog.path + "\/[0-9]+.*"), function (lien) {
            debugger;
            lien.end();
        });

        // Blog pages (pagination)
        server.page.add(new RegExp(Config.blog.path + "(\/page\/[1-9]([0-9]*))?\/$"), function (lien) {
            debugger;
            lien.end();
        });

        server.on("request", function (lien) {
            lien.end();
        });
    });

   //     if (
   //         (route && route.url && typeof route.url !== "object"
   //         || isBlogPost || isBlogPage)
   //         && typeof Bloggify.apis["handlePage:" + req.method] === "function"
   //     ) {
   //         Bloggify.session.isLoggedIn(req, function (err, sessionData) {
   //             if (err) {
   //                 Debug.log(err, "error");
   //                 return Statique.error(req, res, 500);
   //             }
   //             Bloggify.apis["handlePage:" + req.method](
   //                 req, res, pathName, route, null, isBlogPost, isBlogPage, sessionData
   //             );
   //         });
   //         return;
   //     }
});
<commit_msg>Cleaning server.js file<commit_after>var Statique = require("statique")
  , Start = require("./start")
  , Http = require("http")
  , Url = require("url")
  , Lien = require("lien")
  , Config = Bloggify.getConfig()
  , Theme = require("./theme")
  , CoreApis = require("./lib")
  ;

var server = Bloggify.server = new Lien({
    host: Config.host
  , port: Config.port
  , root: Config.content
  , cache: Config.fileCache
});

Bloggify.initPlugins(function () {
    Theme(Config.content + Config.theme, function (err, themeObj) {
        if (err) { throw err; }

        // Error pages
        server._sServer.setErrors(themeObj.errors);
        server.page.add(/\/[4-9][0-9][0-9]\/?/, CoreApis.errorPages);

        // Site pages
        server.page.add(new RegExp(Config.blog.path + "\/[0-9]+.*"), CoreApis.sitePage);

        // Blog posts
        server.page.add(new RegExp(Config.blog.path + "\/[0-9]+.*"), CoreApis.blogPost);

        // Blog pages (pagination)
        server.page.add(new RegExp(Config.blog.path + "(\/page\/[1-9]([0-9]*))?\/$"), CoreApis.blogPage);

        // Other requests (CSS etc)
        server.on("request", function (lien) {
            lien.end();
        });
    });
});
<|endoftext|>


<commit_before>/* @flow */

import defineType from "./index";

defineType("AnyTypeAnnotation", {
  aliases: ["Flow", "FlowBaseAnnotation"],
  fields: {
    // todo
  }
});

defineType("ArrayTypeAnnotation", {
  visitor: ["elementType"],
  aliases: ["Flow"],
  fields: {
    // todo
  }
});

defineType("BooleanTypeAnnotation", {
  aliases: ["Flow", "FlowBaseAnnotation"],
  fields: {
    // todo
  }
});

defineType("BooleanLiteralTypeAnnotation", {
  aliases: ["Flow"],
  fields: {}
});

defineType("NullLiteralTypeAnnotation", {
  aliases: ["Flow", "FlowBaseAnnotation"],
  fields: {}
});

defineType("ClassImplements", {
  visitor: ["id", "typeParameters"],
  aliases: ["Flow"],
  fields: {
    // todo
  }
});

defineType("ClassProperty", {
  visitor: ["key", "value", "typeAnnotation", "decorators"],
  aliases: ["Flow", "Property"],
  fields: {
    // todo
  }
});

defineType("DeclareClass", {
  visitor: ["id", "typeParameters", "extends", "body"],
  aliases: ["Flow", "FlowDeclaration", "Statement", "Declaration"],
  fields: {
    // todo
  }
});

defineType("DeclareFunction", {
  visitor: ["id"],
  aliases: ["Flow", "FlowDeclaration", "Statement", "Declaration"],
  fields: {
    // todo
  }
});

defineType("DeclareModule", {
  visitor: ["id", "body"],
  aliases: ["Flow", "FlowDeclaration", "Statement", "Declaration"],
  fields: {
    // todo
  }
});

defineType("DeclareVariable", {
  visitor: ["id"],
  aliases: ["Flow", "FlowDeclaration", "Statement", "Declaration"],
  fields: {
    // todo
  }
});

defineType("ExistentialTypeParam", {
  aliases: ["Flow"]
});

defineType("FunctionTypeAnnotation", {
  visitor: ["typeParameters", "params", "rest", "returnType"],
  aliases: ["Flow"],
  fields: {
    // todo
  }
});

defineType("FunctionTypeParam", {
  visitor: ["name", "typeAnnotation"],
  aliases: ["Flow"],
  fields: {
    // todo
  }
});

defineType("GenericTypeAnnotation", {
  visitor: ["id", "typeParameters"],
  aliases: ["Flow"],
  fields: {
    // todo
  }
});

defineType("InterfaceExtends", {
  visitor: ["id", "typeParameters"],
  aliases: ["Flow"],
  fields: {
    // todo
  }
});

defineType("InterfaceDeclaration", {
  visitor: ["id", "typeParameters", "extends", "body"],
  aliases: ["Flow", "FlowDeclaration", "Statement", "Declaration"],
  fields: {
    // todo
  }
});

defineType("IntersectionTypeAnnotation", {
  visitor: ["types"],
  aliases: ["Flow"],
  fields: {
    // todo
  }
});

defineType("MixedTypeAnnotation", {
  aliases: ["Flow", "FlowBaseAnnotation"]
});

defineType("NullableTypeAnnotation", {
  visitor: ["typeAnnotation"],
  aliases: ["Flow"],
  fields: {
    // todo
  }
});

defineType("NumericLiteralTypeAnnotation", {
  aliases: ["Flow"],
  fields: {
    // todo
  }
});

defineType("NumberTypeAnnotation", {
  aliases: ["Flow", "FlowBaseAnnotation"],
  fields: {
    // todo
  }
});

defineType("StringLiteralTypeAnnotation", {
  aliases: ["Flow"],
  fields: {
    // todo
  }
});

defineType("StringTypeAnnotation", {
  aliases: ["Flow", "FlowBaseAnnotation"],
  fields: {
    // todo
  }
});

defineType("ThisTypeAnnotation", {
  aliases: ["Flow", "FlowBaseAnnotation"],
  fields: {}
});

defineType("TupleTypeAnnotation", {
  visitor: ["types"],
  aliases: ["Flow"],
  fields: {
    // todo
  }
});

defineType("TypeofTypeAnnotation", {
  visitor: ["argument"],
  aliases: ["Flow"],
  fields: {
    // todo
  }
});

defineType("TypeAlias", {
  visitor: ["id", "typeParameters", "right"],
  aliases: ["Flow", "FlowDeclaration", "Statement", "Declaration"],
  fields: {
    // todo
  }
});

defineType("TypeAnnotation", {
  visitor: ["typeAnnotation"],
  aliases: ["Flow"],
  fields: {
    // todo
  }
});

defineType("TypeCastExpression", {
  visitor: ["expression", "typeAnnotation"],
  aliases: ["Flow", "ExpressionWrapper", "Expression"],
  fields: {
    // todo
  }
});

defineType("TypeParameterDeclaration", {
  visitor: ["params"],
  aliases: ["Flow"],
  fields: {
    // todo
  }
});

defineType("TypeParameterInstantiation", {
  visitor: ["params"],
  aliases: ["Flow"],
  fields: {
    // todo
  }
});

defineType("ObjectTypeAnnotation", {
  visitor: ["properties", "indexers", "callProperties"],
  aliases: ["Flow"],
  fields: {
    // todo
  }
});

defineType("ObjectTypeCallProperty", {
  visitor: ["value"],
  aliases: ["Flow", "UserWhitespacable"],
  fields: {
    // todo
  }
});

defineType("ObjectTypeIndexer", {
  visitor: ["id", "key", "value"],
  aliases: ["Flow", "UserWhitespacable"],
  fields: {
    // todo
  }
});

defineType("ObjectTypeProperty", {
  visitor: ["key", "value"],
  aliases: ["Flow", "UserWhitespacable"],
  fields: {
    // todo
  }
});

defineType("QualifiedTypeIdentifier", {
  visitor: ["id", "qualification"],
  aliases: ["Flow"],
  fields: {
    // todo
  }
});

defineType("UnionTypeAnnotation", {
  visitor: ["types"],
  aliases: ["Flow"],
  fields: {
    // todo
  }
});

defineType("VoidTypeAnnotation", {
  aliases: ["Flow", "FlowBaseAnnotation"],
  fields: {
    // todo
  }
});
<commit_msg>Add support for "declare type" Flow syntax<commit_after>/* @flow */

import defineType from "./index";

defineType("AnyTypeAnnotation", {
  aliases: ["Flow", "FlowBaseAnnotation"],
  fields: {
    // todo
  }
});

defineType("ArrayTypeAnnotation", {
  visitor: ["elementType"],
  aliases: ["Flow"],
  fields: {
    // todo
  }
});

defineType("BooleanTypeAnnotation", {
  aliases: ["Flow", "FlowBaseAnnotation"],
  fields: {
    // todo
  }
});

defineType("BooleanLiteralTypeAnnotation", {
  aliases: ["Flow"],
  fields: {}
});

defineType("NullLiteralTypeAnnotation", {
  aliases: ["Flow", "FlowBaseAnnotation"],
  fields: {}
});

defineType("ClassImplements", {
  visitor: ["id", "typeParameters"],
  aliases: ["Flow"],
  fields: {
    // todo
  }
});

defineType("ClassProperty", {
  visitor: ["key", "value", "typeAnnotation", "decorators"],
  aliases: ["Flow", "Property"],
  fields: {
    // todo
  }
});

defineType("DeclareClass", {
  visitor: ["id", "typeParameters", "extends", "body"],
  aliases: ["Flow", "FlowDeclaration", "Statement", "Declaration"],
  fields: {
    // todo
  }
});

defineType("DeclareFunction", {
  visitor: ["id"],
  aliases: ["Flow", "FlowDeclaration", "Statement", "Declaration"],
  fields: {
    // todo
  }
});

defineType("DeclareModule", {
  visitor: ["id", "body"],
  aliases: ["Flow", "FlowDeclaration", "Statement", "Declaration"],
  fields: {
    // todo
  }
});

defineType("DeclareTypeAlias", {
  visitor: ["id", "typeParameters", "right"],
  aliases: ["Flow", "FlowDeclaration", "Statement", "Declaration"],
  fields: {
    // todo
  }
});

defineType("DeclareVariable", {
  visitor: ["id"],
  aliases: ["Flow", "FlowDeclaration", "Statement", "Declaration"],
  fields: {
    // todo
  }
});

defineType("ExistentialTypeParam", {
  aliases: ["Flow"]
});

defineType("FunctionTypeAnnotation", {
  visitor: ["typeParameters", "params", "rest", "returnType"],
  aliases: ["Flow"],
  fields: {
    // todo
  }
});

defineType("FunctionTypeParam", {
  visitor: ["name", "typeAnnotation"],
  aliases: ["Flow"],
  fields: {
    // todo
  }
});

defineType("GenericTypeAnnotation", {
  visitor: ["id", "typeParameters"],
  aliases: ["Flow"],
  fields: {
    // todo
  }
});

defineType("InterfaceExtends", {
  visitor: ["id", "typeParameters"],
  aliases: ["Flow"],
  fields: {
    // todo
  }
});

defineType("InterfaceDeclaration", {
  visitor: ["id", "typeParameters", "extends", "body"],
  aliases: ["Flow", "FlowDeclaration", "Statement", "Declaration"],
  fields: {
    // todo
  }
});

defineType("IntersectionTypeAnnotation", {
  visitor: ["types"],
  aliases: ["Flow"],
  fields: {
    // todo
  }
});

defineType("MixedTypeAnnotation", {
  aliases: ["Flow", "FlowBaseAnnotation"]
});

defineType("NullableTypeAnnotation", {
  visitor: ["typeAnnotation"],
  aliases: ["Flow"],
  fields: {
    // todo
  }
});

defineType("NumericLiteralTypeAnnotation", {
  aliases: ["Flow"],
  fields: {
    // todo
  }
});

defineType("NumberTypeAnnotation", {
  aliases: ["Flow", "FlowBaseAnnotation"],
  fields: {
    // todo
  }
});

defineType("StringLiteralTypeAnnotation", {
  aliases: ["Flow"],
  fields: {
    // todo
  }
});

defineType("StringTypeAnnotation", {
  aliases: ["Flow", "FlowBaseAnnotation"],
  fields: {
    // todo
  }
});

defineType("ThisTypeAnnotation", {
  aliases: ["Flow", "FlowBaseAnnotation"],
  fields: {}
});

defineType("TupleTypeAnnotation", {
  visitor: ["types"],
  aliases: ["Flow"],
  fields: {
    // todo
  }
});

defineType("TypeofTypeAnnotation", {
  visitor: ["argument"],
  aliases: ["Flow"],
  fields: {
    // todo
  }
});

defineType("TypeAlias", {
  visitor: ["id", "typeParameters", "right"],
  aliases: ["Flow", "FlowDeclaration", "Statement", "Declaration"],
  fields: {
    // todo
  }
});

defineType("TypeAnnotation", {
  visitor: ["typeAnnotation"],
  aliases: ["Flow"],
  fields: {
    // todo
  }
});

defineType("TypeCastExpression", {
  visitor: ["expression", "typeAnnotation"],
  aliases: ["Flow", "ExpressionWrapper", "Expression"],
  fields: {
    // todo
  }
});

defineType("TypeParameterDeclaration", {
  visitor: ["params"],
  aliases: ["Flow"],
  fields: {
    // todo
  }
});

defineType("TypeParameterInstantiation", {
  visitor: ["params"],
  aliases: ["Flow"],
  fields: {
    // todo
  }
});

defineType("ObjectTypeAnnotation", {
  visitor: ["properties", "indexers", "callProperties"],
  aliases: ["Flow"],
  fields: {
    // todo
  }
});

defineType("ObjectTypeCallProperty", {
  visitor: ["value"],
  aliases: ["Flow", "UserWhitespacable"],
  fields: {
    // todo
  }
});

defineType("ObjectTypeIndexer", {
  visitor: ["id", "key", "value"],
  aliases: ["Flow", "UserWhitespacable"],
  fields: {
    // todo
  }
});

defineType("ObjectTypeProperty", {
  visitor: ["key", "value"],
  aliases: ["Flow", "UserWhitespacable"],
  fields: {
    // todo
  }
});

defineType("QualifiedTypeIdentifier", {
  visitor: ["id", "qualification"],
  aliases: ["Flow"],
  fields: {
    // todo
  }
});

defineType("UnionTypeAnnotation", {
  visitor: ["types"],
  aliases: ["Flow"],
  fields: {
    // todo
  }
});

defineType("VoidTypeAnnotation", {
  aliases: ["Flow", "FlowBaseAnnotation"],
  fields: {
    // todo
  }
});
<|endoftext|>


<commit_before>var Q = require('q');
var fs = require('fs');
var rimraf = require('rimraf');
var assert = require('assert');
var mockery = require('mockery');
var utils = require('../lib/utils');

describe('cli upgrade cmd', function() {
  var cwd;
  var upgrade;
  var spawnCalls;
  var writeCalls;
  var runBinaryCall;
  var folder = 'test-project';
  var cmdUpgradePath = '../lib/cli/cmd-upgrade';
  var pkgJsonPath = __dirname + '/../test-project/package.json';

  beforeEach(function() {
    spawnCalls = [];
    writeCalls = [];
    runBinaryCall = {};
    cwd = process.cwd();

    deleteFolder();

    mockery.enable({
      useCleanCache: true,
      warnOnUnregistered: false
    });

    mockery.registerAllowable(cmdUpgradePath);

    mockery.registerMock('./run-binary', function() {
      runBinaryCall.args = arguments[0];
      runBinaryCall.options = arguments[1];
    });

    mockery.registerMock('../utils', {
      mkdirp: utils.mkdirp,
      versionRange: function() { return 'latest'; },
      projectRoot: function(){
        return Promise.resolve(__dirname + '/../' + folder);
      },
      spawn: function() {
        spawnCalls.push({
          binary: arguments[0],
          args: arguments[1],
          options: arguments[2]
        });
        return Q(true);
      }
    });

    mockery.registerMock(pkgJsonPath, {
      dependencies: {
        foo: "1.0.0"
      },
      devDependencies: {
        bar: "1.0.0"
      }
    });

    mockery.registerMock('fs', {
      writeFileSync: function(path, data, enc){
        writeCalls.push({ path, data, enc });
      }
    });

    mockery.registerMock('cross-spawn-async', function(){
      spawnCalls.push({
        binary: arguments[0],
        args: arguments[1],
        options: arguments[2]
      });
      var makeOn = function() {
        var fn = function(ev, cb) {
          fn.cb = cb;
        };
        return fn;
      };
      var onData = makeOn();
      var onExit = makeOn();
      var mock = {stdout: { on: onData }, on: onExit};

      setTimeout(function(){
        var pkg = {donejs: {dependencies: {foo: "2.0.0"}, devDependencies: {bar: "2.0.0"}}};
        onData.cb(JSON.stringify(pkg));
        setTimeout(function() { onExit.cb(0); }, 20);
      }, 20);

      return mock;
    });

    upgrade = require(cmdUpgradePath);
  });

  afterEach(function() {
    deleteFolder();
    mockery.disable();
    mockery.deregisterAll();
  });

  it('updates the package.json', function(done){
    upgrade(null, {canmigrate: false})
      .then(function(){
        assert.equal(writeCalls.length, 1);
        assert.equal(writeCalls[0].path, pkgJsonPath);

        var json = JSON.parse(writeCalls[0].data);
        assert.equal(json.dependencies.foo, "2.0.0", "dependency is upgraded");
        assert.equal(json.devDependencies.bar, "2.0.0", "devDependency is upgraded");

        done();
      })
      .catch(done);
  });

  it('runs can-migrate', function(done){
    upgrade(null, {canmigrate: true})
      .then(function(){
        assert.equal(runBinaryCall.args[0], "can-migrate", "ran can-migrate");
        done();
      })
      .catch(done);
  });

  it('Does not run can-migrate when --no-canmigrate flag is passed', function(done){
    upgrade(null, {canmigrate: false})
      .then(function(){
        assert.equal(runBinaryCall.args, undefined, "did not run can-migrate");
        done();
      })
      .catch(done);
  });

  function deleteFolder() {
    if (fs.existsSync(folder)) {
      rimraf.sync(folder);
    }
  }
});
<commit_msg>Fix tests checking if can-migrate was called<commit_after>var Q = require('q');
var fs = require('fs');
var path = require('path');
var rimraf = require('rimraf');
var assert = require('assert');
var mockery = require('mockery');
var utils = require('../lib/utils');

describe('cli upgrade cmd', function() {
  var cwd;
  var upgrade;
  var spawnCalls;
  var writeCalls;
  var folder = 'test-project';
  var cmdUpgradePath = '../lib/cli/cmd-upgrade';
  var pkgJsonPath = path.join(__dirname, "..", folder, "package.json");

  beforeEach(function() {
    spawnCalls = [];
    writeCalls = [];
    cwd = process.cwd();

    deleteFolder();

    mockery.enable({
      useCleanCache: true,
      warnOnUnregistered: false
    });

    mockery.registerAllowable(cmdUpgradePath);

    mockery.registerMock('../utils', {
      mkdirp: utils.mkdirp,
      versionRange: function() { return 'latest'; },
      projectRoot: function(){
        return Promise.resolve(__dirname + '/../' + folder);
      },
      spawn: function() {
        spawnCalls.push({
          binary: arguments[0],
          args: arguments[1],
          options: arguments[2]
        });
        return Q(true);
      }
    });

    mockery.registerMock(pkgJsonPath, {
      dependencies: {
        foo: "1.0.0"
      },
      devDependencies: {
        bar: "1.0.0"
      }
    });

    mockery.registerMock('fs', {
      writeFileSync: function(path, data, enc){
        writeCalls.push({ path, data, enc });
      }
    });

    mockery.registerMock('cross-spawn-async', function(){
      spawnCalls.push({
        binary: arguments[0],
        args: arguments[1],
        options: arguments[2]
      });
      var makeOn = function() {
        var fn = function(ev, cb) {
          fn.cb = cb;
        };
        return fn;
      };
      var onData = makeOn();
      var onExit = makeOn();
      var mock = {stdout: { on: onData }, on: onExit};

      setTimeout(function(){
        var pkg = {donejs: {dependencies: {foo: "2.0.0"}, devDependencies: {bar: "2.0.0"}}};
        onData.cb(JSON.stringify(pkg));
        setTimeout(function() { onExit.cb(0); }, 20);
      }, 20);

      return mock;
    });

    upgrade = require(cmdUpgradePath);
  });

  afterEach(function() {
    //deleteFolder();
    mockery.disable();
    mockery.deregisterAll();
  });

  it('updates the package.json', function(done){
    upgrade(null, {canmigrate: false})
      .then(function(){
        assert.equal(writeCalls.length, 1);
        assert.equal(writeCalls[0].path, pkgJsonPath);

        var json = JSON.parse(writeCalls[0].data);
        assert.equal(json.dependencies.foo, "2.0.0", "dependency is upgraded");
        assert.equal(json.devDependencies.bar, "2.0.0", "devDependency is upgraded");

        done();
      })
      .catch(done);
  });

  it('runs can-migrate', function(done){
    upgrade(null, {canmigrate: true})
      .then(function(){
        var lastCall = spawnCalls[spawnCalls.length - 1];
        assert.ok(/can-migrate/.test(lastCall.args[0]), "ran can-migrate");
        done();
      })
      .catch(done);
  });

  it('Does not run can-migrate when --no-canmigrate flag is passed', function(done){
    upgrade(null, {canmigrate: false})
      .then(function(){
        var lastCall = spawnCalls[spawnCalls.length - 1];
        assert.ok(!/can-migrate/.test(lastCall.args[0]), "did not run  can-migrate");
        done();
      })
      .catch(done);
  });

  function deleteFolder() {
    if (fs.existsSync(folder)) {
      rimraf.sync(folder);
    }
  }
});
<|endoftext|>


<commit_before>/*
 * Copyright 2014, Gregg Tavares.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *
 *     * Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above
 * copyright notice, this list of conditions and the following disclaimer
 * in the documentation and/or other materials provided with the
 * distribution.
 *     * Neither the name of Gregg Tavares. nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
"use strict";

define(function() {
  var addTextNode = function(element, txt) {
    var node = document.createTextNode(txt);
    element.appendChild(node);
    return node;
  };

  var elemNum = 1;

  var addRange = function(parent, label, obj, id, min, max) {
    if (!(id instanceof Array)) {
      id = [id];
    }
    var elemId = "range" + (++elemNum);
    var labelElem = document.createElement("label");
    labelElem.for = elemId;
    var node = addTextNode(labelElem, label);
    parent.appendChild(labelElem);
    labelElem.style.display = "block";

    var input = document.createElement("input");
    input.type = "range";
    input.id = elemId;
    input.value = Math.floor((obj[id[0]] - min) * 100 / (max - min));

    var updateNode = function(value) {
      node.nodeValue = label + ": " + value.toFixed(3);
    };

    input.addEventListener('input', function(e) {
      var v = parseFloat(input.value);
      var value = v * (max - min) / 100 + min;
      for (var ii = 0; ii < id.length; ++ii) {
        obj[id[ii]] = value;
      }
      updateNode(value);
    }, false);

    updateNode(obj[id[0]]);
  };

  //addRange(div, "x", this.tileDrawOptions, "x", 0, 300);
  //addRange(div, "y", this.tileDrawOptions, "y", 0, 300);
  //addRange(div, "width", this.tileDrawOptions, "width", 0, this.canvas.width);
  //addRange(div, "height", this.tileDrawOptions, "height", 0, this.canvas.height);
  //addRange(div, "scale", this.tileDrawOptions, ["scaleX", "scaleY"], 0.1, 40);
  //addRange(div, "rotation", this.tileDrawOptions, "rotation", -Math.PI, Math.PI);
  //addRange(div, "originX", this.tileDrawOptions, "originX", 0, this.canvas.width);
  //addRange(div, "originY", this.tileDrawOptions, "originY", 0, this.canvas.height);
  //parent.appendChild(div);

  return {
    addRange: addRange,
  };
});
<commit_msg>add callback to use addRange<commit_after>/*
 * Copyright 2014, Gregg Tavares.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *
 *     * Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above
 * copyright notice, this list of conditions and the following disclaimer
 * in the documentation and/or other materials provided with the
 * distribution.
 *     * Neither the name of Gregg Tavares. nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
"use strict";

define(function() {
  var addTextNode = function(element, txt) {
    var node = document.createTextNode(txt);
    element.appendChild(node);
    return node;
  };

  var elemNum = 1;

  var addRange = function(parent, label, obj, id, min, max, opt_fn) {
    if (!(id instanceof Array)) {
      id = [id];
    }
    var elemId = "range" + (++elemNum);
    var labelElem = document.createElement("label");
    labelElem.for = elemId;
    var node = addTextNode(labelElem, label);
    parent.appendChild(labelElem);
    labelElem.style.display = "block";

    var input = document.createElement("input");
    input.type = "range";
    input.id = elemId;
    input.value = Math.floor((obj[id[0]] - min) * 100 / (max - min));

    parent.appendChild(input);

    var updateNode = function(value) {
      node.nodeValue = label + ": " + value.toFixed(3);
    };

    input.addEventListener('input', function(e) {
      var v = parseFloat(input.value);
      var value = v * (max - min) / 100 + min;
      for (var ii = 0; ii < id.length; ++ii) {
        obj[id[ii]] = value;
      }
      updateNode(value);
      if (opt_fn) {
        opt_fn(value);
      }
    }, false);

    updateNode(obj[id[0]]);
  };

  //addRange(div, "x", this.tileDrawOptions, "x", 0, 300);
  //addRange(div, "y", this.tileDrawOptions, "y", 0, 300);
  //addRange(div, "width", this.tileDrawOptions, "width", 0, this.canvas.width);
  //addRange(div, "height", this.tileDrawOptions, "height", 0, this.canvas.height);
  //addRange(div, "scale", this.tileDrawOptions, ["scaleX", "scaleY"], 0.1, 40);
  //addRange(div, "rotation", this.tileDrawOptions, "rotation", -Math.PI, Math.PI);
  //addRange(div, "originX", this.tileDrawOptions, "originX", 0, this.canvas.width);
  //addRange(div, "originY", this.tileDrawOptions, "originY", 0, this.canvas.height);
  //parent.appendChild(div);

  return {
    addRange: addRange,
  };
});
<|endoftext|>


<commit_before>import path from 'path';
import fs from 'fs';
import { logger } from '@storybook/node-logger';
import { TsconfigPathsPlugin } from 'tsconfig-paths-webpack-plugin';
import {
  isBuildAngularInstalled,
  normalizeAssetPatterns,
  filterOutStylingRules,
  getAngularCliParts,
} from './angular-cli_utils';

function getTsConfigOptions(tsConfigPath) {
  const basicOptions = {
    options: {},
    raw: {},
    fileNames: [],
    errors: [],
  };

  if (!fs.existsSync(tsConfigPath)) {
    return basicOptions;
  }

  const tsConfig = JSON.parse(fs.readFileSync(tsConfigPath, 'utf8'));
  const { baseUrl } = tsConfig.compilerOptions || {};

  if (baseUrl) {
    const tsConfigDirName = path.dirname(tsConfigPath);
    basicOptions.options.baseUrl = path.resolve(tsConfigDirName, baseUrl);
  }

  return basicOptions;
}

export function getAngularCliWebpackConfigOptions(dirToSearch) {
  const fname = path.join(dirToSearch, 'angular.json');

  if (!fs.existsSync(fname)) {
    return null;
  }

  const angularJson = JSON.parse(fs.readFileSync(fname, 'utf8'));
  const { projects, defaultProject } = angularJson;

  if (!projects || !Object.keys(projects).length) {
    throw new Error('angular.json must have projects entry.');
  }

  let project = projects[Object.keys(projects)[0]];

  if (defaultProject) {
    project = projects[defaultProject];
  }

  const { options: projectOptions } = project.architect.build;

  const normalizedAssets = normalizeAssetPatterns(
    projectOptions.assets,
    dirToSearch,
    project.sourceRoot
  );

  const projectRoot = path.resolve(dirToSearch, project.root);
  const tsConfigPath = path.resolve(dirToSearch, projectOptions.tsConfig);
  const tsConfig = getTsConfigOptions(tsConfigPath);

  return {
    root: dirToSearch,
    projectRoot,
    tsConfigPath,
    tsConfig,
    supportES2015: false,
    buildOptions: {
      ...projectOptions,
      assets: normalizedAssets,
    },
  };
}

export function applyAngularCliWebpackConfig(baseConfig, cliWebpackConfigOptions) {
  if (!cliWebpackConfigOptions) {
    return baseConfig;
  }

  if (!isBuildAngularInstalled()) {
    logger.info('=> Using base config because @angular-devkit/build-angular is not installed.');
    return baseConfig;
  }

  const cliParts = getAngularCliParts(cliWebpackConfigOptions);

  if (!cliParts) {
    logger.warn('=> Failed to get angular-cli webpack config.');
    return baseConfig;
  }

  logger.info('=> Get angular-cli webpack config.');

  const { cliCommonConfig, cliStyleConfig } = cliParts;

  // Don't use storybooks styling rules because we have to use rules created by @angular-devkit/build-angular
  // because @angular-devkit/build-angular created rules have include/exclude for global style files.
  const rulesExcludingStyles = filterOutStylingRules(baseConfig);

  // cliStyleConfig.entry adds global style files to the webpack context
  const entry = [
    ...baseConfig.entry,
    ...Object.values(cliStyleConfig.entry).reduce((acc, item) => acc.concat(item), []),
    // iframe: []
    //   .concat(baseConfig.entry.iframe)
    //   .concat(Object.values(cliStyleConfig.entry).reduce((acc, item) => acc.concat(item), [])),
  ];

  const module = {
    ...baseConfig.module,
    rules: [...cliStyleConfig.module.rules, ...rulesExcludingStyles],
  };

  // We use cliCommonConfig plugins to serve static assets files.
  const plugins = [...cliStyleConfig.plugins, ...cliCommonConfig.plugins, ...baseConfig.plugins];

  const resolve = {
    ...baseConfig.resolve,
    modules: Array.from(
      new Set([...baseConfig.resolve.modules, ...cliCommonConfig.resolve.modules])
    ),
    plugins: [
      new TsconfigPathsPlugin({
        configFile: cliWebpackConfigOptions.buildOptions.tsConfig,
      }),
    ],
  };

  return {
    ...baseConfig,
    entry,
    module,
    plugins,
    resolve,
    resolveLoader: cliCommonConfig.resolveLoader,
  };
}
<commit_msg>Remove the unneeded comment<commit_after>import path from 'path';
import fs from 'fs';
import { logger } from '@storybook/node-logger';
import { TsconfigPathsPlugin } from 'tsconfig-paths-webpack-plugin';
import {
  isBuildAngularInstalled,
  normalizeAssetPatterns,
  filterOutStylingRules,
  getAngularCliParts,
} from './angular-cli_utils';

function getTsConfigOptions(tsConfigPath) {
  const basicOptions = {
    options: {},
    raw: {},
    fileNames: [],
    errors: [],
  };

  if (!fs.existsSync(tsConfigPath)) {
    return basicOptions;
  }

  const tsConfig = JSON.parse(fs.readFileSync(tsConfigPath, 'utf8'));
  const { baseUrl } = tsConfig.compilerOptions || {};

  if (baseUrl) {
    const tsConfigDirName = path.dirname(tsConfigPath);
    basicOptions.options.baseUrl = path.resolve(tsConfigDirName, baseUrl);
  }

  return basicOptions;
}

export function getAngularCliWebpackConfigOptions(dirToSearch) {
  const fname = path.join(dirToSearch, 'angular.json');

  if (!fs.existsSync(fname)) {
    return null;
  }

  const angularJson = JSON.parse(fs.readFileSync(fname, 'utf8'));
  const { projects, defaultProject } = angularJson;

  if (!projects || !Object.keys(projects).length) {
    throw new Error('angular.json must have projects entry.');
  }

  let project = projects[Object.keys(projects)[0]];

  if (defaultProject) {
    project = projects[defaultProject];
  }

  const { options: projectOptions } = project.architect.build;

  const normalizedAssets = normalizeAssetPatterns(
    projectOptions.assets,
    dirToSearch,
    project.sourceRoot
  );

  const projectRoot = path.resolve(dirToSearch, project.root);
  const tsConfigPath = path.resolve(dirToSearch, projectOptions.tsConfig);
  const tsConfig = getTsConfigOptions(tsConfigPath);

  return {
    root: dirToSearch,
    projectRoot,
    tsConfigPath,
    tsConfig,
    supportES2015: false,
    buildOptions: {
      ...projectOptions,
      assets: normalizedAssets,
    },
  };
}

export function applyAngularCliWebpackConfig(baseConfig, cliWebpackConfigOptions) {
  if (!cliWebpackConfigOptions) {
    return baseConfig;
  }

  if (!isBuildAngularInstalled()) {
    logger.info('=> Using base config because @angular-devkit/build-angular is not installed.');
    return baseConfig;
  }

  const cliParts = getAngularCliParts(cliWebpackConfigOptions);

  if (!cliParts) {
    logger.warn('=> Failed to get angular-cli webpack config.');
    return baseConfig;
  }

  logger.info('=> Get angular-cli webpack config.');

  const { cliCommonConfig, cliStyleConfig } = cliParts;

  // Don't use storybooks styling rules because we have to use rules created by @angular-devkit/build-angular
  // because @angular-devkit/build-angular created rules have include/exclude for global style files.
  const rulesExcludingStyles = filterOutStylingRules(baseConfig);

  // cliStyleConfig.entry adds global style files to the webpack context
  const entry = [
    ...baseConfig.entry,
    ...Object.values(cliStyleConfig.entry).reduce((acc, item) => acc.concat(item), []),
  ];

  const module = {
    ...baseConfig.module,
    rules: [...cliStyleConfig.module.rules, ...rulesExcludingStyles],
  };

  // We use cliCommonConfig plugins to serve static assets files.
  const plugins = [...cliStyleConfig.plugins, ...cliCommonConfig.plugins, ...baseConfig.plugins];

  const resolve = {
    ...baseConfig.resolve,
    modules: Array.from(
      new Set([...baseConfig.resolve.modules, ...cliCommonConfig.resolve.modules])
    ),
    plugins: [
      new TsconfigPathsPlugin({
        configFile: cliWebpackConfigOptions.buildOptions.tsConfig,
      }),
    ],
  };

  return {
    ...baseConfig,
    entry,
    module,
    plugins,
    resolve,
    resolveLoader: cliCommonConfig.resolveLoader,
  };
}
<|endoftext|>


<commit_before>/**
 * # Base configuration
 *
 * This is the base configuration module which gets loaded first by the [configuration loader](index.js.html).
 */

/**
 * Server listening port.
 * @type {Number}
 */
exports.port = 3000;

/**
 * Base web URL
 * @type {String}
 */
exports.baseURL = 'http://localhost:' + exports.port;

/**
 * Database connection.
 * @type {Object}
 */
exports.db = {
  mongoose: {
    host: '127.0.0.1',
    port: '27017',
    db: 'waigo'
  }
};

/**
 * Logging config.
 * @type {Object}
 */
exports.logging = {
  winston: {
    // log to mongo db
    mongo: {
      // log level threshold
      level: 'error',
      collection: 'logs',
      // whether to confirm writes to db log table
      safe: false
    }
  }
};

/**
 * Session configuration.
 *
 * We don't provide default `keys` so as to encourage developers to provide a custom one for their app.
 *
 * @type {Object}
 */
exports.session = {
  // cookie signing keys - these are used for signing cookies (using Keygrip) and should be set for your app
  // keys: ['use', 'your', 'own'],
  // session cookie name
  name: 'waigo',
  // session storage
  store: {
    // session store type
    type: 'mongo',
    // session store config
    config: {
      url: 'mongodb://127.0.0.1:27017/waigo',
      collection: 'sessions'
    }
  },
  // more cookie options
  cookie: {
    // cookie expires in...
    validForDays: 7,
    // cookie valid for url path...
    path: '/'
  }
};

/**
 * Server responses to client requests can be in the formats specified here.
 * @type {Object}
 */
exports.outputFormats = {
  // List of enabled formats along with options to pass to each formatter. */
  formats: {
    html: {
      // Folder relative to application root folder, in which to look for view templates. */
      folder: 'views',
      // Default view template filename extension when not explicitly provided. */
      ext: 'jade',
      // Map file extension to rendering engine
      engine: {
        'jade': 'jade'
      }
    },
    json: {}
  },
  // Use this URL query parameter to determine output format. */
  paramName: 'format',
  // Default format, in case URL query parameter which determines output format isn't provided. */
  default: 'html'
};

/**
 * Static resources.
 * @type {Object}
 */
exports.staticResources = {
  // relative to app folder
  folder: '../public',
  // see support/middleware/staticResources for options
  options: {}
};

/**
 * Config for request error handler.
 * @type {Object}
 */
exports.errorHandler = {
  // whether to show stack traces in error output.
  showStack: false
};
<commit_msg>Build fix<commit_after>/**
 * # Base configuration
 *
 * This is the base configuration module which gets loaded first by the [configuration loader](index.js.html).
 */

/**
 * Server listening port.
 * @type {Number}
 */
exports.port = 3000;

/**
 * Base web URL
 * @type {String}
 */
exports.baseURL = 'http://localhost:' + exports.port;

/**
 * Database connection.
 * @type {Object}
 */
exports.db = {
  mongoose: {
    host: '127.0.0.1',
    port: '27017',
    db: 'waigo'
  }
};

/**
 * Logging config.
 * @type {Object}
 */
exports.logging = {
  winston: {
    // log to mongo db
    mongo: {
      // log level threshold
      level: 'error',
      collection: 'logs',
      // whether to confirm writes to db log table
      safe: false
    }
  }
};

/**
 * Session configuration.
 *
 * We don't provide default `keys` so as to encourage developers to provide a custom one for their app.
 *
 * @type {Object}
 */
exports.session = {
  // cookie signing keys - these are used for signing cookies (using Keygrip) and should be set for your app
  // keys: ['use', 'your', 'own'],
  // session cookie name
  name: 'waigo',
  // session storage
  store: {
    // session store type
    type: 'mongo',
    // session store config
    config: {
      url: 'mongodb://127.0.0.1:27017/waigo',
      collection: 'sessions'
    }
  },
  // more cookie options
  cookie: {
    // cookie expires in...
    validForDays: 7,
    // cookie valid for url path...
    path: '/'
  }
};

/**
 * Server responses to client requests can be in the formats specified here.
 * @type {Object}
 */
exports.outputFormats = {
  // List of enabled formats along with options to pass to each formatter. */
  formats: {
    html: {
      // Folder relative to application root folder, in which to look for view templates. */
      folder: 'views',
      // Default view template filename extension when not explicitly provided. */
      ext: 'jade',
      // Map file extension to rendering engine
      engine: {
        'jade': 'jade'
      }
    },
    json: {}
  },
  // Use this URL query parameter to determine output format. */
  paramName: 'format',
  // Default format, in case URL query parameter which determines output format isn't provided. */
  default: 'html'
};

/**
 * Static resources.
 * @type {Object}
 */
exports.staticResources = {
  // relative to app folder
  folder: '../public',
  // see support/middleware/staticResources for options
  options: {}
};

/**
 * Config for request error handler.
 * @type {Object}
 */
exports.errorHandler = {
  // whether to show stack traces in error output.
  showStack: false
};
<|endoftext|>