<commit_before>$(function() {

  $( "#fecha" ).datepicker();
  $( "#fecha" ).datepicker( "option", "dateFormat", "yy-mm-dd" );

  // $( "#frmasistencia" ).on( "change", "#fecha", function() {
  //   $( "#date" ).val($( "#fecha" ).val());
  // });

$( "#frmmonedero" ).on( "click", "#btnbuscar", function() {
      var fecha = $('#frmmonedero #fecha').val();
      var perfil = $("#tecnico1id").val();
      var supervisor = $("#supervisorid").val();

      window.location.href = '/index.php/monedero?perfil='+perfil+'&fecha='+fecha+'&supervisor='+supervisor;
});
/*
$( "#frmmonedero" ).on( "click", "#btnbuscar", function() {
      var fecha = $('#frmmonedero #fecha').val();
      var dni = $("#tecnico1id").val();
      window.location.href = '/index.php/monedero?dni='+dni+'&fecha='+fecha;
});
*/

  $( "#frmasistencia" ).on( "click", "#btnbuscar", function() {
      var fecha = $('#frmasistencia #fecha').val();
      var dni = $('#frmasistencia #dni').val();
      console.log(dni);
      var url =  '/index.php/asistencia/buscar/' + fecha+'&dni='+dni;
      window.location.href = '/index.php/asistencia?fecha='+fecha+'&dni='+dni;
    /*
      $.ajax({
        url : url,
        data : {fecha : fecha},
        type : 'GET',
        dataType : 'json',
        success : function(json) {
            // window.location.href = url;
            // history.pushState(null, "", url);
            //alert('okk');
            window.location.href = '/index.php/asistencia?fecha='+fecha;
            //$('#resultadoasistencia').html(json.result);
        },
        error : function(xhr, status) {
             alert('Disculpe, existió un problema');
        },
        complete : function(xhr, status) {
            // alert('Petición realizada');
        }
      });*/

    $( "#date" ).val($( "#fecha" ).val());

  });

  $( "#grabar" ).on( "click", function() {
      var fecha = $('#fecha').val();
      var dni = $('#dni').val();
      var result = $('#result').val();

      if (result=='result2')
        var url = '/index.php/asistencia/grabar';
      else
        var url= '/index.php/asistencia/grabar';

      var data = $('#frmasistencia').serialize();
      $.ajax({
        url : url,
        data : {data : data},
        type : 'POST',
        dataType : 'json',
        success : function(json) {
              alert('Asistencia guardada correctamente');
              window.location.href = '/index.php/asistencia?fecha='+fecha+'&dni='+dni;
            // history.pushState(null, "", url);
            // $('#frmasistencia #resultadoasistencia').html(json.result);
        },
        error : function(xhr, status) {
             alert('Disculpe, existió un problema');
        },
        complete : function(xhr, status) {
            // alert('Petición realizada');
        }
      });
  });

$("#tbmonedero  a.supervisor_detalle" ).on( "click", function() {
    var id=$(this).attr('data-id');

  if($(".detalle_jefe-"+id).hasClass('hidden')){

      $(".detalle_jefe-"+id).fadeIn();
      $(".detalle_jefe-"+id).removeClass('hidden');

  }else{

      $(".detalle_jefe-"+id).fadeOut();
      $(".detalle_jefe-"+id).addClass('hidden');
    }

});

$("#mult-asignacion" ).on( "click", function() {

    var checked = []
    $("input[name='sot[]']:checked").each(function ()
      {
        checked.push(parseInt($(this).val()));
      });
      checked = checked.join('&');
      console.log(checked);
       //window.location.href = '/index.php/solicitudes?sot='+checked;
  });

});
<commit_msg>billetera<commit_after>$(function() {

  $( "#fecha" ).datepicker();
  $( "#fecha" ).datepicker( "option", "dateFormat", "yy-mm-dd" );

  // $( "#frmasistencia" ).on( "change", "#fecha", function() {
  //   $( "#date" ).val($( "#fecha" ).val());
  // });

$( "#frmmonedero" ).on( "click", "#btnbuscar", function() {
      var fecha = $('#frmmonedero #fecha').val();
      var perfil = $("#tecnico1id").val();
      var supervisor = $("#supervisorid").val();

      window.location.href = '/index.php/monedero?perfil='+perfil+'&fecha='+fecha+'&supervisor='+supervisor;
});
/*
$( "#frmmonedero" ).on( "click", "#btnbuscar", function() {
      var fecha = $('#frmmonedero #fecha').val();
      var dni = $("#tecnico1id").val();
      window.location.href = '/index.php/monedero?dni='+dni+'&fecha='+fecha;
});
*/

  $( "#frmasistencia" ).on( "click", "#btnbuscar", function() {
      var fecha = $('#frmasistencia #fecha').val();
      var dni = $('#frmasistencia #dni').val();
      console.log(dni);
      var url =  '/index.php/asistencia/buscar/' + fecha+'&dni='+dni;
      window.location.href = '/index.php/asistencia?fecha='+fecha+'&dni='+dni;
    /*
      $.ajax({
        url : url,
        data : {fecha : fecha},
        type : 'GET',
        dataType : 'json',
        success : function(json) {
            // window.location.href = url;
            // history.pushState(null, "", url);
            //alert('okk');
            window.location.href = '/index.php/asistencia?fecha='+fecha;
            //$('#resultadoasistencia').html(json.result);
        },
        error : function(xhr, status) {
             alert('Disculpe, existió un problema');
        },
        complete : function(xhr, status) {
            // alert('Petición realizada');
        }
      });*/

    $( "#date" ).val($( "#fecha" ).val());

  });

  $( "#grabar" ).on( "click", function() {
      var fecha = $('#fecha').val();
      var dni = $('#dni').val();
      var result = $('#result').val();

      if (result=='result2')
        var url = '/index.php/asistencia/grabar';
      else
        var url= '/index.php/asistencia/grabar';

      var data = $('#frmasistencia').serialize();
      $.ajax({
        url : url,
        data : {data : data},
        type : 'POST',
        dataType : 'json',
        success : function(json) {
              alert('Asistencia guardada correctamente');
              window.location.href = '/index.php/asistencia?fecha='+fecha+'&dni='+dni;
            // history.pushState(null, "", url);
            // $('#frmasistencia #resultadoasistencia').html(json.result);
        },
        error : function(xhr, status) {
             alert('Disculpe, existió un problema');
        },
        complete : function(xhr, status) {
            // alert('Petición realizada');
        }
      });
  });

$("#tbmonedero  a.supervisor_detalle" ).on( "click", function() {
    var id=$(this).attr('data-id');

  if($(".detalle_jefe-"+id).hasClass('hidden')){

      $(".detalle_jefe-"+id).fadeIn();
      $(".detalle_jefe-"+id).removeClass('hidden');

  }else{

      $(".detalle_jefe-"+id).fadeOut();
      $(".detalle_jefe-"+id).addClass('hidden');
    }

});

$("#mult-asignacion" ).on( "click", function() {

    var checked = []
    $("input[name='sot[]']:checked").each(function ()
      {
        checked.push(parseInt($(this).val()));
      });
      checked = checked.join('&');
      console.log("---");
      console.log(checked);
       //window.location.href = '/index.php/solicitudes?sot='+checked;
  });

});
<|endoftext|>


<commit_before>import _ from 'lodash';
import LSBackedStore from '../js/ls-backed-store';
import Hashset from 'hashset.js';
import InfoBubble from 'googlemaps/js-info-bubble/src/infobubble';
import MarkerBubble from '../components/marker-bubble.jsx!';
import React from 'react';
import 'jspm_packages/npm/hashset.js@1.1.0/test/object-assign-polyfill';
import {binState} from '../services/moonridge';
import gonePoosLQ from '../stores/states-store';

function getIcon(type, entity) {
  var icons = {
    poo: '/img/pin-poo.svg',
    bin: {
      plain: '/img/pin-bin-plain.svg',
      good: '/img/pin-bin-good.svg',
      bad: '/img/pin-bin-bad.svg'
    }
  };
  if (type === 'bin') {
    if (entity.bags_count > 8) {

    }
  } else {
    return icons[type];

  }

}
var openedBubble;

const store = {
  photos: new Hashset('_id'),

  /**
   * @param {Array<Objects>} markers
   */
  addMarkers: (markers, map) => {

    markers.forEach(function (marker){
      var updated = store.photos.upsert(marker);
      if (!updated) {  //markers cannot change position, so we don't have to recreate google map marker instances
        store.addMarkerToMap(marker, map);
      }
    });

  },
  addMarkerToMap: function addMarkerToMap(marker, map) {
    const myLatLng = new google.maps.LatLng(marker.loc[0], marker.loc[1]);
    const newMarker = new google.maps.Marker({
      position: myLatLng,
      map: map,
      icon: `/img/pin-${marker.type}.svg`
    });

    function createBubble() {
      const infoBubble = new InfoBubble({
        map: map,
        content: `<div id="${marker._id}" class="${marker.type}-bubble" style="width: 345px;height: 300px;"></div>`,
        shadowStyle: 1,
        padding: 10,
        backgroundColor: '#3A1F07',
        borderRadius: 5,
        arrowSize: 25,
        borderWidth: 1,
        borderColor: '#987230',
        //disableAutoPan: true,
        arrowPosition: 50,
        backgroundClassName: 'transparent',
        arrowStyle: 2,
        width: 300,
        height: 600,
        buildCloseBtn: function() {
          var el = document.createElement('SPAN');
          el.style['font-size'] = '25px';
          el.className = 'glyphicon glyphicon-remove';
          return el;
        }
      });

      marker.openInfoBubble = function() {
        if (openedBubble) {
          openedBubble.close();
        }
        infoBubble.open(map, newMarker);
        openedBubble = infoBubble;
        var infoBubbleContainer;

        google.maps.event.addDomListener(infoBubble.close_, 'click', function() {
          location.hash = '#/';
          React.unmountComponentAtNode(infoBubbleContainer);
        });

        location.hash = `#/${marker.type}/${marker._id}`;
        setTimeout(function() {
          infoBubbleContainer = infoBubble.contentContainer_.children[0].children[0];
          React.render(<MarkerBubble {...marker}/>, infoBubbleContainer);
        }, 50);
      };
      google.maps.event.addListener(newMarker, 'click', marker.openInfoBubble);
    }

    if (marker.type === 'bin') {
      return binState.query().find().limit(1).sort('-timestamp').exec().promise.then((binArr)=>{
        var latest = binArr[0];
        if (latest.bag_count > 4) {
          newMarker.icon = '/img/pin-bin-good.svg';
        } else {
          newMarker.icon = '/img/pin-bin-bad.svg';
        }
        createBubble();

      });
    }
    createBubble();

  }

};

//LSBackedStore('map-markers', store);

export default store;<commit_msg>fixed control flow<commit_after>import _ from 'lodash';
import LSBackedStore from '../js/ls-backed-store';
import Hashset from 'hashset.js';
import InfoBubble from 'googlemaps/js-info-bubble/src/infobubble';
import MarkerBubble from '../components/marker-bubble.jsx!';
import React from 'react';
import 'jspm_packages/npm/hashset.js@1.1.0/test/object-assign-polyfill';
import {binState} from '../services/moonridge';
import gonePoosLQ from '../stores/states-store';

function getIcon(type, entity) {
  var icons = {
    poo: '/img/pin-poo.svg',
    bin: {
      plain: '/img/pin-bin-plain.svg',
      good: '/img/pin-bin-good.svg',
      bad: '/img/pin-bin-bad.svg'
    }
  };
  if (type === 'bin') {
    if (entity.bags_count > 8) {

    }
  } else {
    return icons[type];

  }

}
var openedBubble;

const store = {
  photos: new Hashset('_id'),

  /**
   * @param {Array<Objects>} markers
   */
  addMarkers: (markers, map) => {

    markers.forEach(function (marker){
      var updated = store.photos.upsert(marker);
      if (!updated) {  //markers cannot change position, so we don't have to recreate google map marker instances
        store.addMarkerToMap(marker, map);
      }
    });

  },
  addMarkerToMap: function addMarkerToMap(marker, map) {
    const myLatLng = new google.maps.LatLng(marker.loc[0], marker.loc[1]);
    const newMarker = new google.maps.Marker({
      position: myLatLng,
      map: map,
      icon: `/img/pin-${marker.type}.svg`
    });

    function createBubble() {
      const infoBubble = new InfoBubble({
        map: map,
        content: `<div id="${marker._id}" class="${marker.type}-bubble" style="width: 345px;height: 300px;"></div>`,
        shadowStyle: 1,
        padding: 10,
        backgroundColor: '#3A1F07',
        borderRadius: 5,
        arrowSize: 25,
        borderWidth: 1,
        borderColor: '#987230',
        //disableAutoPan: true,
        arrowPosition: 50,
        backgroundClassName: 'transparent',
        arrowStyle: 2,
        width: 300,
        height: 600,
        buildCloseBtn: function() {
          var el = document.createElement('SPAN');
          el.style['font-size'] = '25px';
          el.className = 'glyphicon glyphicon-remove';
          return el;
        }
      });

      marker.openInfoBubble = function() {
        if (openedBubble) {
          openedBubble.close();
        }
        infoBubble.open(map, newMarker);
        openedBubble = infoBubble;
        var infoBubbleContainer;

        google.maps.event.addDomListener(infoBubble.close_, 'click', function() {
          location.hash = '#/';
          React.unmountComponentAtNode(infoBubbleContainer);
        });

        location.hash = `#/${marker.type}/${marker._id}`;
        setTimeout(function() {
          infoBubbleContainer = infoBubble.contentContainer_.children[0].children[0];
          React.render(<MarkerBubble {...marker}/>, infoBubbleContainer);
        }, 50);
      };
      google.maps.event.addListener(newMarker, 'click', marker.openInfoBubble);
    }

    if (marker.type === 'bin') {
      return binState.query().find().limit(1).sort('-timestamp').exec().promise.then((binArr)=>{
        var latest = binArr[0];
        if (latest.bag_count > 4) {
          newMarker.icon = '/img/pin-bin-good.svg';
        } else {
          newMarker.icon = '/img/pin-bin-bad.svg';
        }
        createBubble();

      });
    } else {
      createBubble();
    }

  }

};

//LSBackedStore('map-markers', store);

export default store;<|endoftext|>


<commit_before>import React from "react";
import { connect } from "react-redux";
import Helmet from "react-helmet";
import { Switch, Route, Redirect } from "react-router-dom";
import { push } from "react-router-redux";
import { LinkContainer } from "react-router-bootstrap";
import { Nav, NavItem, Badge } from "react-bootstrap";
import { getReference } from "../../actions";
import { LoadingPlaceholder, Icon } from "../../../base";

import EditReference from "./Edit";
import ReferenceManage from "./Manage";
import ReferenceOTUs from "../../../otus/components/List";
import ReferenceIndexList from "../../../indexes/components/List";
import SourceTypes from "../../../administration/components/General/SourceTypes";
import InternalControl from "../../../administration/components/General/InternalControl";

const ReferenceSettings = () => (

        <SourceTypes />
        <InternalControl />

);

class ReferenceDetail extends React.Component {

    componentDidMount () {
        this.props.onGetReference(this.props.match.params.refId);
    }

    render = () => {

        if (this.props.detail === null || this.props.detail.id !== this.props.match.params.refId) {
            return <LoadingPlaceholder />;
        }

        const { name, id } = this.props.detail;

        return (

                <Helmet>
                    <title>{`${name} - References`}</title>
                </Helmet>

                    {name}
                    <Icon
                        bsStyle="warning"
                        name="pencil-alt"
                        tip="Edit"
                        onClick={this.props.onEdit}
                        pullRight
                    />

                    <LinkContainer to={`/refs/${id}/manage`}>
                        <NavItem>Manage</NavItem>
                    </LinkContainer>
                    <LinkContainer to={`/refs/${id}/otus`}>
                        <NavItem>OTUs <Badge>{this.props.detail.otu_count}</Badge></NavItem>
                    </LinkContainer>
                    <LinkContainer to={`/refs/${id}/indexes`}>
                        <NavItem>Indexes</NavItem>
                    </LinkContainer>
                    <LinkContainer to={`/refs/${id}/settings`}>
                        <NavItem>Settings</NavItem>
                    </LinkContainer>

                <Switch>
                    <Redirect from="/refs/:refId" to={`/refs/${id}/manage`} exact />
                    <Route path="/refs/:refId/manage" component={ReferenceManage} />
                    <Route path="/refs/:refId/otus" component={ReferenceOTUs} />
                    <Route path="/refs/:refId/indexes" component={ReferenceIndexList} />
                    <Route path="/refs/:refId/settings" component={ReferenceSettings} />
                </Switch>

                <EditReference />

        );
    };
}

const mapStateToProps = state => ({
    detail: state.references.detail
});

const mapDispatchToProps = dispatch => ({

    onGetReference: (refId) => {
        dispatch(getReference(refId));
    },

    onEdit: () => {
        dispatch(push({...window.location, state: {editReference: true}}));
    }

});

export default connect(mapStateToProps, mapDispatchToProps)(ReferenceDetail);
<commit_msg>Update header icon size and types<commit_after>import React from "react";
import { connect } from "react-redux";
import Helmet from "react-helmet";
import { Switch, Route, Redirect } from "react-router-dom";
import { push } from "react-router-redux";
import { LinkContainer } from "react-router-bootstrap";
import { Nav, NavItem, Badge } from "react-bootstrap";
import { getReference } from "../../actions";
import { LoadingPlaceholder, Icon } from "../../../base";

import EditReference from "./Edit";
import ReferenceManage from "./Manage";
import ReferenceOTUs from "../../../otus/components/List";
import ReferenceIndexList from "../../../indexes/components/List";
import SourceTypes from "../../../administration/components/General/SourceTypes";
import InternalControl from "../../../administration/components/General/InternalControl";

const ReferenceSettings = () => (

        <SourceTypes />
        <InternalControl />

);

class ReferenceDetail extends React.Component {

    componentDidMount () {
        this.props.onGetReference(this.props.match.params.refId);
    }

    render = () => {

        if (this.props.detail === null || this.props.detail.id !== this.props.match.params.refId) {
            return <LoadingPlaceholder />;
        }

        const { name, id, remote_from } = this.props.detail;

        let headerIcon;

        if (this.props.pathname === `/refs/${id}/manage`) {
            headerIcon = remote_from
                ? (
                    <Icon
                        bsStyle="default"
                        name="lock"
                        pullRight
                        style={{fontSize: "65%"}}
                    />
                )
                : (
                    <Icon
                        bsStyle="warning"
                        name="pencil-alt"
                        tip="Edit"
                        onClick={this.props.onEdit}
                        pullRight
                        style={{fontSize: "65%"}}
                    />
                );
        }

        return (

                <Helmet>
                    <title>{`${name} - References`}</title>
                </Helmet>

                    {name}
                    {headerIcon}

                    <LinkContainer to={`/refs/${id}/manage`}>
                        <NavItem>Manage</NavItem>
                    </LinkContainer>
                    <LinkContainer to={`/refs/${id}/otus`}>
                        <NavItem>OTUs <Badge>{this.props.detail.otu_count}</Badge></NavItem>
                    </LinkContainer>
                    <LinkContainer to={`/refs/${id}/indexes`}>
                        <NavItem>Indexes</NavItem>
                    </LinkContainer>
                    <LinkContainer to={`/refs/${id}/settings`}>
                        <NavItem>Settings</NavItem>
                    </LinkContainer>

                <Switch>
                    <Redirect from="/refs/:refId" to={`/refs/${id}/manage`} exact />
                    <Route path="/refs/:refId/manage" component={ReferenceManage} />
                    <Route path="/refs/:refId/otus" component={ReferenceOTUs} />
                    <Route path="/refs/:refId/indexes" component={ReferenceIndexList} />
                    <Route path="/refs/:refId/settings" component={ReferenceSettings} />
                </Switch>

                <EditReference />

        );
    };
}

const mapStateToProps = state => ({
    detail: state.references.detail,
    pathname: state.router.location.pathname
});

const mapDispatchToProps = dispatch => ({

    onGetReference: (refId) => {
        dispatch(getReference(refId));
    },

    onEdit: () => {
        dispatch(push({...window.location, state: {editReference: true}}));
    }

});

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


<commit_before>module.exports = function() {

	var MongoDB = {

	}

	return MongoDB;
};<commit_msg>Update EasyDB Module<commit_after>module.exports = function() {
	var connect = function() {},
		disconnect = function() {},
		tableExist = function() {},
		getSchema = function() {},
		setSchema = function() {},
		getID = function() {},
		checkID = function() {},
		sql = function() {},
		listTable = function() {},
		getTable = function() {},
		postTable = function() {},
		putTable = function() {},
		deleteTable = function() {},
		listData = function() {},
		getData = function() {},
		postData = function() {},
		putData = function() {},
		deleteData = function() {};

	var MongoDB = {
		connect: connect,
		disconnect: disconnect,
		tableExist: tableExist,
		getSchema: getSchema,
		setSchema: setSchema,
		getID: getID,
		checkID: checkID,
		sql: sql,
		listTable: listTable,
		getTable: getTable,
		postTable: postTable,
		putTable: putTable,
		deleteTable: deleteTable,
		listData: listData,
		getData: getData,
		postData: postData,
		putData: putData,
		deleteData: deleteData
	};

	return MongoDB;
};<|endoftext|>


<commit_before>import { DefaultDraftInlineStyle } from 'draft-js';

// Originally from https://github.com/draft-js-utils/draft-js-utils/blob/master/src/Constants.js.
export const BLOCK_TYPE = {
    // This is used to represent a normal text block (paragraph).
    UNSTYLED: 'unstyled',
    HEADER_ONE: 'header-one',
    HEADER_TWO: 'header-two',
    HEADER_THREE: 'header-three',
    HEADER_FOUR: 'header-four',
    HEADER_FIVE: 'header-five',
    HEADER_SIX: 'header-six',
    UNORDERED_LIST_ITEM: 'unordered-list-item',
    ORDERED_LIST_ITEM: 'ordered-list-item',
    BLOCKQUOTE: 'blockquote',
    CODE: 'code-block',
    ATOMIC: 'atomic',
};

// Originally from https://github.com/draft-js-utils/draft-js-utils/blob/master/src/Constants.js.
export const ENTITY_TYPE = {
    LINK: 'LINK',
    DOCUMENT: 'DOCUMENT',
    MODEL: 'MODEL',
    IMAGE: 'IMAGE',
    EMBED: 'EMBED',
    HORIZONTAL_RULE: 'HORIZONTAL_RULE',
};

// Originally from https://github.com/draft-js-utils/draft-js-utils/blob/master/src/Constants.js.
export const INLINE_STYLE = {
    BOLD: 'BOLD',
    ITALIC: 'ITALIC',
    CODE: 'CODE',
    UNDERLINE: 'UNDERLINE',
    STRIKETHROUGH: 'STRIKETHROUGH',
    MARK: 'MARK',
    QUOTATION: 'QUOTATION',
    SMALL: 'SMALL',
    SAMPLE: 'SAMPLE',
    INSERT: 'INSERT',
    DELETE: 'DELETE',
    KEYBOARD: 'KEYBOARD',
    SUPERSCRIPT: 'SUPERSCRIPT',
    SUBSCRIPT: 'SUBSCRIPT',
};

export const FONT_FAMILY_MONOSPACE =
    'Consolas, Menlo, Monaco, Lucida Console, Liberation Mono, DejaVu Sans Mono, Bitstream Vera Sans Mono, Courier New, monospace, sans-serif';

export const CUSTOM_STYLE_MAP = {
    [INLINE_STYLE.BOLD]: DefaultDraftInlineStyle[INLINE_STYLE.BOLD],
    [INLINE_STYLE.ITALIC]: DefaultDraftInlineStyle[INLINE_STYLE.ITALIC],
    [INLINE_STYLE.STRIKETHROUGH]:
        DefaultDraftInlineStyle[INLINE_STYLE.STRIKETHROUGH],
    [INLINE_STYLE.UNDERLINE]: DefaultDraftInlineStyle[INLINE_STYLE.UNDERLINE],

    [INLINE_STYLE.CODE]: {
        padding: '0.2em 0.3125em',
        margin: '0',
        fontSize: '85%',
        backgroundColor: 'rgba(27, 31, 35, 0.05)',
        fontFamily: FONT_FAMILY_MONOSPACE,
        borderRadius: '3px',
    },

    [INLINE_STYLE.MARK]: {
        backgroundColor: 'yellow',
    },
    [INLINE_STYLE.QUOTATION]: {
        fontStyle: 'italic',
    },
    [INLINE_STYLE.SMALL]: {
        fontSize: 'smaller',
    },
    [INLINE_STYLE.SAMPLE]: {
        fontFamily: FONT_FAMILY_MONOSPACE,
    },
    [INLINE_STYLE.INSERT]: {
        textDecoration: 'underline',
    },
    [INLINE_STYLE.DELETE]: {
        textDecoration: 'line-through',
    },
    [INLINE_STYLE.KEYBOARD]: {
        fontFamily: FONT_FAMILY_MONOSPACE,
        padding: '3px 5px',
        fontSize: '11px',
        lineHeight: '10px',
        color: '#444d56',
        verticalAlign: 'middle',
        backgroundColor: '#fafbfc',
        border: 'solid 1px #c6cbd1',
        borderBottomColor: '#959da5',
        borderRadius: '3px',
        boxShadow: 'inset 0 -1px 0 #959da5',
    },
    [INLINE_STYLE.SUPERSCRIPT]: {
        fontSize: '80%',
        verticalAlign: 'super',
        lineHeight: '1',
    },
    [INLINE_STYLE.SUBSCRIPT]: {
        fontSize: '80%',
        verticalAlign: 'sub',
        lineHeight: '1',
    },
};

export const BR_TYPE = 'BR';
export const UNDO_TYPE = 'undo';
export const REDO_TYPE = 'redo';

// Originally from https://github.com/facebook/draft-js/blob/master/src/component/utils/getDefaultKeyBinding.js.
export const KEY_CODES = {
    K: 75,
    B: 66,
    U: 85,
    J: 74,
    I: 73,
    X: 88,
    0: 48,
    1: 49,
    2: 50,
    3: 51,
    4: 52,
    5: 53,
    6: 54,
    7: 55,
    8: 56,
    '.': 190,
    ',': 188,
};

export const KEYBOARD_SHORTCUTS = {
    [BLOCK_TYPE.UNSTYLED]: {
        other: 'Ctrl+Alt+0',
        macOS: '⌘+Option+0',
    },
    [BLOCK_TYPE.HEADER_ONE]: {
        other: 'Ctrl+Alt+1',
        macOS: '⌘+Option+1',
    },
    [BLOCK_TYPE.HEADER_TWO]: {
        other: 'Ctrl+Alt+2',
        macOS: '⌘+Option+2',
    },
    [BLOCK_TYPE.HEADER_THREE]: {
        other: 'Ctrl+Alt+3',
        macOS: '⌘+Option+3',
    },
    [BLOCK_TYPE.HEADER_FOUR]: {
        other: 'Ctrl+Alt+4',
        macOS: '⌘+Option+4',
    },
    [BLOCK_TYPE.HEADER_FIVE]: {
        other: 'Ctrl+Alt+5',
        macOS: '⌘+Option+5',
    },
    [BLOCK_TYPE.HEADER_SIX]: {
        other: 'Ctrl+Alt+6',
        macOS: '⌘+Option+6',
    },
    [BLOCK_TYPE.UNORDERED_LIST_ITEM]: {
        other: 'Ctrl+Shift+8',
        macOS: '⌘+Shift+8',
    },
    [BLOCK_TYPE.ORDERED_LIST_ITEM]: {
        other: 'Ctrl+Shift+7',
        macOS: '⌘+Shift+7',
    },

    [INLINE_STYLE.BOLD]: { other: 'Ctrl+B', macOS: '⌘+B' },
    [INLINE_STYLE.ITALIC]: { other: 'Ctrl+I', macOS: '⌘+I' },
    [INLINE_STYLE.UNDERLINE]: {
        other: 'Ctrl+U',
        macOS: '⌘+U',
    },
    [INLINE_STYLE.STRIKETHROUGH]: {
        other: 'Ctrl+Shift+X',
        macOS: '⌘+Shift+X',
    },
    [INLINE_STYLE.SUPERSCRIPT]: {
        other: 'Ctrl+.',
        macOS: '⌘+.',
    },
    [INLINE_STYLE.SUBSCRIPT]: {
        other: 'Ctrl+,',
        macOS: '⌘+,',
    },

    [ENTITY_TYPE.LINK]: { other: 'Ctrl+K', macOS: '⌘+K' },

    [BR_TYPE]: {
        other: 'Shift+Enter',
        macOS: 'Shift+Enter',
    },

    [UNDO_TYPE]: {
        other: 'Ctrl+Z',
        macOS: '⌘+Z',
    },

    [REDO_TYPE]: {
        other: 'Ctrl+Shift+Z',
        macOS: '⌘+Shift+Z',
    },
};

export const NBSP = '\u00a0';

export const HANDLED = 'handled';
export const NOT_HANDLED = 'not-handled';

export const BEFORE_INPUT_MAP = {
    '* ': BLOCK_TYPE.UNORDERED_LIST_ITEM,
    '- ': BLOCK_TYPE.UNORDERED_LIST_ITEM,
    '1. ': BLOCK_TYPE.ORDERED_LIST_ITEM,
    // TODO Potentially to be commented out again.
    // See https://github.com/springload/draftail/issues/53
    '# ': BLOCK_TYPE.HEADER_ONE,
    '## ': BLOCK_TYPE.HEADER_TWO,
    '### ': BLOCK_TYPE.HEADER_THREE,
    '#### ': BLOCK_TYPE.HEADER_FOUR,
    '##### ': BLOCK_TYPE.HEADER_FIVE,
    '###### ': BLOCK_TYPE.HEADER_SIX,
    '``` ': BLOCK_TYPE.CODE,
    '> ': BLOCK_TYPE.BLOCKQUOTE,
};

export const BEFORE_INPUT_MAX_LENGTH = Object.keys(BEFORE_INPUT_MAP).reduce(
    (maxLength, input) => Math.max(maxLength, input.length),
    0,
);
<commit_msg>Add code block shortcut with triple tick "```" like Paper. See #53<commit_after>import { DefaultDraftInlineStyle } from 'draft-js';

// Originally from https://github.com/draft-js-utils/draft-js-utils/blob/master/src/Constants.js.
export const BLOCK_TYPE = {
    // This is used to represent a normal text block (paragraph).
    UNSTYLED: 'unstyled',
    HEADER_ONE: 'header-one',
    HEADER_TWO: 'header-two',
    HEADER_THREE: 'header-three',
    HEADER_FOUR: 'header-four',
    HEADER_FIVE: 'header-five',
    HEADER_SIX: 'header-six',
    UNORDERED_LIST_ITEM: 'unordered-list-item',
    ORDERED_LIST_ITEM: 'ordered-list-item',
    BLOCKQUOTE: 'blockquote',
    CODE: 'code-block',
    ATOMIC: 'atomic',
};

// Originally from https://github.com/draft-js-utils/draft-js-utils/blob/master/src/Constants.js.
export const ENTITY_TYPE = {
    LINK: 'LINK',
    DOCUMENT: 'DOCUMENT',
    MODEL: 'MODEL',
    IMAGE: 'IMAGE',
    EMBED: 'EMBED',
    HORIZONTAL_RULE: 'HORIZONTAL_RULE',
};

// Originally from https://github.com/draft-js-utils/draft-js-utils/blob/master/src/Constants.js.
export const INLINE_STYLE = {
    BOLD: 'BOLD',
    ITALIC: 'ITALIC',
    CODE: 'CODE',
    UNDERLINE: 'UNDERLINE',
    STRIKETHROUGH: 'STRIKETHROUGH',
    MARK: 'MARK',
    QUOTATION: 'QUOTATION',
    SMALL: 'SMALL',
    SAMPLE: 'SAMPLE',
    INSERT: 'INSERT',
    DELETE: 'DELETE',
    KEYBOARD: 'KEYBOARD',
    SUPERSCRIPT: 'SUPERSCRIPT',
    SUBSCRIPT: 'SUBSCRIPT',
};

export const FONT_FAMILY_MONOSPACE =
    'Consolas, Menlo, Monaco, Lucida Console, Liberation Mono, DejaVu Sans Mono, Bitstream Vera Sans Mono, Courier New, monospace, sans-serif';

export const CUSTOM_STYLE_MAP = {
    [INLINE_STYLE.BOLD]: DefaultDraftInlineStyle[INLINE_STYLE.BOLD],
    [INLINE_STYLE.ITALIC]: DefaultDraftInlineStyle[INLINE_STYLE.ITALIC],
    [INLINE_STYLE.STRIKETHROUGH]:
        DefaultDraftInlineStyle[INLINE_STYLE.STRIKETHROUGH],
    [INLINE_STYLE.UNDERLINE]: DefaultDraftInlineStyle[INLINE_STYLE.UNDERLINE],

    [INLINE_STYLE.CODE]: {
        padding: '0.2em 0.3125em',
        margin: '0',
        fontSize: '85%',
        backgroundColor: 'rgba(27, 31, 35, 0.05)',
        fontFamily: FONT_FAMILY_MONOSPACE,
        borderRadius: '3px',
    },

    [INLINE_STYLE.MARK]: {
        backgroundColor: 'yellow',
    },
    [INLINE_STYLE.QUOTATION]: {
        fontStyle: 'italic',
    },
    [INLINE_STYLE.SMALL]: {
        fontSize: 'smaller',
    },
    [INLINE_STYLE.SAMPLE]: {
        fontFamily: FONT_FAMILY_MONOSPACE,
    },
    [INLINE_STYLE.INSERT]: {
        textDecoration: 'underline',
    },
    [INLINE_STYLE.DELETE]: {
        textDecoration: 'line-through',
    },
    [INLINE_STYLE.KEYBOARD]: {
        fontFamily: FONT_FAMILY_MONOSPACE,
        padding: '3px 5px',
        fontSize: '11px',
        lineHeight: '10px',
        color: '#444d56',
        verticalAlign: 'middle',
        backgroundColor: '#fafbfc',
        border: 'solid 1px #c6cbd1',
        borderBottomColor: '#959da5',
        borderRadius: '3px',
        boxShadow: 'inset 0 -1px 0 #959da5',
    },
    [INLINE_STYLE.SUPERSCRIPT]: {
        fontSize: '80%',
        verticalAlign: 'super',
        lineHeight: '1',
    },
    [INLINE_STYLE.SUBSCRIPT]: {
        fontSize: '80%',
        verticalAlign: 'sub',
        lineHeight: '1',
    },
};

export const BR_TYPE = 'BR';
export const UNDO_TYPE = 'undo';
export const REDO_TYPE = 'redo';

// Originally from https://github.com/facebook/draft-js/blob/master/src/component/utils/getDefaultKeyBinding.js.
export const KEY_CODES = {
    K: 75,
    B: 66,
    U: 85,
    J: 74,
    I: 73,
    X: 88,
    0: 48,
    1: 49,
    2: 50,
    3: 51,
    4: 52,
    5: 53,
    6: 54,
    7: 55,
    8: 56,
    '.': 190,
    ',': 188,
};

export const KEYBOARD_SHORTCUTS = {
    [BLOCK_TYPE.UNSTYLED]: {
        other: 'Ctrl+Alt+0',
        macOS: '⌘+Option+0',
    },
    [BLOCK_TYPE.HEADER_ONE]: {
        other: 'Ctrl+Alt+1',
        macOS: '⌘+Option+1',
    },
    [BLOCK_TYPE.HEADER_TWO]: {
        other: 'Ctrl+Alt+2',
        macOS: '⌘+Option+2',
    },
    [BLOCK_TYPE.HEADER_THREE]: {
        other: 'Ctrl+Alt+3',
        macOS: '⌘+Option+3',
    },
    [BLOCK_TYPE.HEADER_FOUR]: {
        other: 'Ctrl+Alt+4',
        macOS: '⌘+Option+4',
    },
    [BLOCK_TYPE.HEADER_FIVE]: {
        other: 'Ctrl+Alt+5',
        macOS: '⌘+Option+5',
    },
    [BLOCK_TYPE.HEADER_SIX]: {
        other: 'Ctrl+Alt+6',
        macOS: '⌘+Option+6',
    },
    [BLOCK_TYPE.UNORDERED_LIST_ITEM]: {
        other: 'Ctrl+Shift+8',
        macOS: '⌘+Shift+8',
    },
    [BLOCK_TYPE.ORDERED_LIST_ITEM]: {
        other: 'Ctrl+Shift+7',
        macOS: '⌘+Shift+7',
    },

    [INLINE_STYLE.BOLD]: { other: 'Ctrl+B', macOS: '⌘+B' },
    [INLINE_STYLE.ITALIC]: { other: 'Ctrl+I', macOS: '⌘+I' },
    [INLINE_STYLE.UNDERLINE]: {
        other: 'Ctrl+U',
        macOS: '⌘+U',
    },
    [INLINE_STYLE.STRIKETHROUGH]: {
        other: 'Ctrl+Shift+X',
        macOS: '⌘+Shift+X',
    },
    [INLINE_STYLE.SUPERSCRIPT]: {
        other: 'Ctrl+.',
        macOS: '⌘+.',
    },
    [INLINE_STYLE.SUBSCRIPT]: {
        other: 'Ctrl+,',
        macOS: '⌘+,',
    },

    [ENTITY_TYPE.LINK]: { other: 'Ctrl+K', macOS: '⌘+K' },

    [BR_TYPE]: {
        other: 'Shift+Enter',
        macOS: 'Shift+Enter',
    },

    [UNDO_TYPE]: {
        other: 'Ctrl+Z',
        macOS: '⌘+Z',
    },

    [REDO_TYPE]: {
        other: 'Ctrl+Shift+Z',
        macOS: '⌘+Shift+Z',
    },
};

export const NBSP = '\u00a0';

export const HANDLED = 'handled';
export const NOT_HANDLED = 'not-handled';

export const BEFORE_INPUT_MAP = {
    '* ': BLOCK_TYPE.UNORDERED_LIST_ITEM,
    '- ': BLOCK_TYPE.UNORDERED_LIST_ITEM,
    '1. ': BLOCK_TYPE.ORDERED_LIST_ITEM,
    '# ': BLOCK_TYPE.HEADER_ONE,
    '## ': BLOCK_TYPE.HEADER_TWO,
    '### ': BLOCK_TYPE.HEADER_THREE,
    '#### ': BLOCK_TYPE.HEADER_FOUR,
    '##### ': BLOCK_TYPE.HEADER_FIVE,
    '###### ': BLOCK_TYPE.HEADER_SIX,
    '> ': BLOCK_TYPE.BLOCKQUOTE,
    // It makes more sense not to require a space here.
    // This matches how Dropbox Paper operates.
    '```': BLOCK_TYPE.CODE,
};

export const BEFORE_INPUT_MAX_LENGTH = Object.keys(BEFORE_INPUT_MAP).reduce(
    (maxLength, input) => Math.max(maxLength, input.length),
    0,
);
<|endoftext|>


<commit_before>/*global
  jQuery: false,
  window: false
*/

/*jshint
  bitwise: true,
  browser: true,
  eqeqeq: true,
  indent: 2,
  newcap: true,
  nomen: true,
  regexp: true,
  undef: true,
  white: true
*/

(function ($) {
  /* Console */
  var console;
  if (window.console) {
    console = window.console;
  }
  else {
    console = {
      log: function (message) {
        window.alert(message);
      }
    };
  }

  var $body = $('body'), $title = $('
');

  /* Icon */
  var $icons = $('
');
  $.each(['home', 'at', 'quote', 'quoteAlt', 'arrowUp', 'arrowRight', 'arrowBottom', 'arrowLeft', 'arrowUpAlt', 'arrowRightAlt', 'arrowBottomAlt', 'arrowLeftAlt', 'move', 'moveVertical', 'moveHorizontal', 'moveAlt', 'moveVerticalAlt', 'moveHorizontalAlt', 'cursor', 'plus', 'plusAlt', 'minus', 'minusAlt', 'newWindow', 'dial', 'lightbulb', 'link', 'image', 'article', 'readMore', 'headphones', 'equalizer', 'fullscreen', 'exitFullscreen', 'spin', 'spinAlt', 'moon', 'sun', 'mapPin', 'pin', 'eyedropper', 'denied', 'calendar', 'calendarAlt', 'bolt', 'clock', 'document', 'book', 'bookAlt', 'magnifyingGlass', 'tag', 'heart', 'info', 'chat', 'chatAlt', 'key', 'unlocked', 'locked', 'mail', 'mailAlt', 'phone', 'box', 'pencil', 'pencilAlt', 'comment', 'commentAlt', 'rss', 'star', 'trash', 'user', 'volume', 'mute', 'cog', 'cogAlt', 'x', 'xAlt', 'check', 'checkAlt', 'beaker', 'beakerAlt'
  ], function (i, name) {
    if (i !== 0) {
      $icons.append(' ');
    }
    $icons.append($.ninja().icon(name));
  });
  $body.append($title.clone().text('Icon'), $icons);

  /* Drawer */
  var $drawer = $.ninja().drawer({
    html: 'Content of the drawer',
    title: 'Open Sesame'
  });
  $body.append($title.clone().text('Drawer'), $drawer);

  /* Slider */
  var $slider = $.ninja().slider({
    choices: [{
      html: '0 dB',
      select: function (event) {
        console.log(event.choice.html);
      }
    },
    {
      html: '10 dB',
      select: function (event) {
        console.log(event.choice.html + ': Light leaf rustling, calm breathing');
      }
    },
    {
      html: '20-30 dB',
      select: function (event) {
        console.log(event.choice.html + ': Very calm room');
      }

    },
    {
      html: '40-60 dB',
      select: function (event) {
        console.log(event.choice.html + ': Normal conversation at 1 m');
      }
    },
    {
      html: '60 dB',
      select: function (event) {
        console.log(event.choice.html + ': TV set at home level at 1 m');
      }
    },
    {
      html: '60-80 dB',
      select: function (event) {
        console.log(event.choice.html + ': Passenger car at 10 m');
      }
    },
    {
      html: '78 dB',
      select: function (event) {
        console.log(event.choice.html + ': Hearing damage over long-term exposure, need not be continuous');
      }
    },
    {
      html: '80-90 dB',
      select: function (event) {
        console.log(event.choice.html + ': Traffic on a busy roadway at 10 m');
      }
    },
    {
      html: '100 dB',
      select: function (event) {
        console.log(event.choice.html + ': Jack hammer at 1 m');
      }
    },
    {
      html: '120 dB',
      select: function (event) {
        console.log(event.choice.html + ': Hearing damage immediately possible');
      }
    },
    {
      html: '130 dB',
      select: function (event) {
        console.log(event.choice.html + ': Threshold of pain');
      }
    },
    {
      html: '150 dB',
      select: function (event) {
        console.log(event.choice.html + ': Jet engine at 30 m');
      }
    },
    {
      html: '168 dB',
      select: function (event) {
        console.log(event.choice.html + ': M1 Garand rifle being fired at 1 m');
      }
    }],
    slot: 3,
    title: 'Volume'
  }).select(function (event) {
    console.log('Slider returns: ' + event.choice.html);
  });
  $body.append($title.clone().text('Slider'), $slider);

  /* Suggest */
  var $suggest = $.ninja().suggest({
    html: $.ninja().icon('magnifyingGlass'),
    placeholder: 'Ninja UI Search',
    width: '50%'
  }).change(function (event) {
    $.ajax({
      url: 'http://clients1.google.com/complete/search',
      dataType: 'jsonp',
      data: {
        q: event.value,
        ds: '',
        nolabels: 't'
      },
      success: function (data, message) {
        $suggest.update({
          choices: $.map(data[1], function (item) {
            return {
              html: item[0]
            };
          })
        });
      },
      error: function (request, status, error) {
        console.error(error);
        $suggest.update({
          choices: [{
            html: $('
', {
              css: {
                color: 'red'
              },
              text: 'Server error: ' + error
            }),
            spacer: true
          }]
        });
      },
      timeout: 4000
    });
  }).select(function (event) {
    console.log('Global select function called returning: ' + event.html);
  });
  $body.append($title.clone().text('Suggest'), $suggest);

  /* Button */
  var $button = $.ninja().button({
    html: 'Default'
  }),
  $buttonStates = $.ninja().button({
    html: 'Disabled'
  }).deselect(function () {
    console.log('Deselected button.');
  }).enable(function () {
    console.log('Enabled button.');
  }).select(function () {
    console.log('Selected button.');
  }),
  $buttonChangeState = $.ninja().button({
    html: 'Disable/Enable',
    select: true
  }).toggle(function () {
    $buttonStates.enable();
  }, function () {
    $buttonStates.disable();
  }),
  $buttonIcon = $.ninja().button({
    html: $('').append($.ninja().icon('home'), ' With Icon')
  });
  $body.append($title.clone().text('Button'), $button, ' ', $buttonIcon, ' ', $buttonStates, ' ', $buttonChangeState);
  $buttonStates.disable().disable(function () {
    console.log('Disabled button.');
  });

  /* Bubble */
  var $bubbleButton;
  var $buttonBubble = $.ninja().button({
    html: 'Button Bubble'
  }).select(function () {
    $bubbleButton = $buttonBubble.bubble();
    $bubbleButton.html($('
', {
      css: {
        whiteSpace: 'nowrap'
      },
      text: 'Button bubble content loaded via ninja().html().'
    }));
  }).deselect(function () {
    $bubbleButton.detach();
  });

  var $bubbleList;
  var $buttonListBubble = $.ninja().button({
    html: 'List Bubble'
  }).select(function () {
    $bubbleList = $buttonListBubble.bubble();
    $bubbleList.html($.ninja().list({
      choices: [{
        html: $('
', {
          text: 'Choose me!'
        }),
        select: function () {
          console.log('Local select function called.');
        }
      },
      {
        html: $('
'),
        spacer: true
      },
      {
        html: $('
', {
          text: 'No, choose me!'
        })
      }]
    }).select(function (event) {
      console.log('Global select function called returning: ' + $(event.html).text());
      $bubbleList.detach();
    }));
  }).deselect(function () {
    $bubbleList.detach();
  });

  var $spinner = $('', {
    className: 'ninja ninjaInline',
    css: {
      backgroundImage: 'url("../lib/images/wait.png")',
      height: '16px',
      width: '16px'
    }
  }).ninja().spin();
  var $bubbleWindow;
  var $buttonWindowBubble = $.ninja().button({
    html: 'Window Bubble'
  }).select(function () {
    $bubbleWindow = $buttonWindowBubble.ninja().bubble({
      html: ' Loading...',
      pop: true,
      window: true
    }).prepend($spinner);
    /* Fake asynchronous delay */
    setTimeout(function () {
      $bubbleWindow.html('Document body bubble content loaded via ninja().html().');
    }, 2000);
  }).deselect(function () {
    $bubbleWindow.detach();
  });
  $body.append($title.clone().text('Bubble'), $buttonBubble, ' ', $buttonListBubble, ' ', $buttonWindowBubble);

  var $rating = $.ninja().rating({
    choices: [{
      html: $('
', {
        text: 'One star.'
      }),
      select: function () {
        console.log('Local select function called.');
      }
    },
    {
      html: $('
', {
        text: 'Two stars.'
      })
    },
    {
      html: $('
', {
        text: 'Three stars.'
      })
    },
    {
      html: $('
', {
        text: 'Four stars.'
      })
    },
    {
      html: $('
', {
        text: 'Five stars.'
      })
    }],
    starsAverage: 3
  }).select(function (event) {
    console.log('Global select function called returning: ' + event.html.text());
  });
  $body.append($title.clone().text('Rating'), $rating);

}(jQuery));<commit_msg>Alphabetize order of examples in test.<commit_after>/*global
  jQuery: false,
  window: false
*/

/*jshint
  bitwise: true,
  browser: true,
  eqeqeq: true,
  indent: 2,
  newcap: true,
  nomen: true,
  regexp: true,
  undef: true,
  white: true
*/

(function ($) {
  /* Console */
  var console;
  if (window.console) {
    console = window.console;
  }
  else {
    console = {
      log: function (message) {
        window.alert(message);
      }
    };
  }

  var $body = $('body'), $title = $('
');

  /* Button */
  var $button = $.ninja().button({
    html: 'Default'
  }),
  $buttonStates = $.ninja().button({
    html: 'Disabled'
  }).deselect(function () {
    console.log('Deselected button.');
  }).enable(function () {
    console.log('Enabled button.');
  }).select(function () {
    console.log('Selected button.');
  }),
  $buttonChangeState = $.ninja().button({
    html: 'Disable/Enable',
    select: true
  }).toggle(function () {
    $buttonStates.enable();
  }, function () {
    $buttonStates.disable();
  }),
  $buttonIcon = $.ninja().button({
    html: $('').append($.ninja().icon('home'), ' With Icon')
  });
  $body.append($title.clone().text('Button'), $button, ' ', $buttonIcon, ' ', $buttonStates, ' ', $buttonChangeState);
  $buttonStates.disable().disable(function () {
    console.log('Disabled button.');
  });

  /* Drawer */
  var $drawer = $.ninja().drawer({
    html: 'Content of the drawer',
    title: 'Open Sesame'
  });
  $body.append($title.clone().text('Drawer'), $drawer);

  /* Icon */
  var $icons = $('
');
  $.each(['home', 'at', 'quote', 'quoteAlt', 'arrowUp', 'arrowRight', 'arrowBottom', 'arrowLeft', 'arrowUpAlt', 'arrowRightAlt', 'arrowBottomAlt', 'arrowLeftAlt', 'move', 'moveVertical', 'moveHorizontal', 'moveAlt', 'moveVerticalAlt', 'moveHorizontalAlt', 'cursor', 'plus', 'plusAlt', 'minus', 'minusAlt', 'newWindow', 'dial', 'lightbulb', 'link', 'image', 'article', 'readMore', 'headphones', 'equalizer', 'fullscreen', 'exitFullscreen', 'spin', 'spinAlt', 'moon', 'sun', 'mapPin', 'pin', 'eyedropper', 'denied', 'calendar', 'calendarAlt', 'bolt', 'clock', 'document', 'book', 'bookAlt', 'magnifyingGlass', 'tag', 'heart', 'info', 'chat', 'chatAlt', 'key', 'unlocked', 'locked', 'mail', 'mailAlt', 'phone', 'box', 'pencil', 'pencilAlt', 'comment', 'commentAlt', 'rss', 'star', 'trash', 'user', 'volume', 'mute', 'cog', 'cogAlt', 'x', 'xAlt', 'check', 'checkAlt', 'beaker', 'beakerAlt'
  ], function (i, name) {
    if (i !== 0) {
      $icons.append(' ');
    }
    $icons.append($.ninja().icon(name));
  });
  $body.append($title.clone().text('Icon'), $icons);

  /* Pop-Up */
  var $bubbleButton;
  var $buttonBubble = $.ninja().button({
    html: 'Pop-Up'
  }).select(function () {
    $bubbleButton = $buttonBubble.bubble();
    $bubbleButton.html($('
', {
      css: {
        whiteSpace: 'nowrap'
      },
      text: 'Button bubble content loaded via ninja().html().'
    }));
  }).deselect(function () {
    $bubbleButton.detach();
  });
  var $bubbleList;
  var $buttonListBubble = $.ninja().button({
    html: 'Pop-Up List'
  }).select(function () {
    $bubbleList = $buttonListBubble.bubble();
    $bubbleList.html($.ninja().list({
      choices: [{
        html: $('
', {
          text: 'Choose me!'
        }),
        select: function () {
          console.log('Local select function called.');
        }
      },
      {
        html: $('
'),
        spacer: true
      },
      {
        html: $('
', {
          text: 'No, choose me!'
        })
      }]
    }).select(function (event) {
      console.log('Global select function called returning: ' + $(event.html).text());
      $bubbleList.detach();
    }));
  }).deselect(function () {
    $bubbleList.detach();
  });

  var $spinner = $('', {
    className: 'ninja ninjaInline',
    css: {
      backgroundImage: 'url("../lib/images/wait.png")',
      height: '16px',
      width: '16px'
    }
  }).ninja().spin();
  var $bubbleWindow;
  var $buttonWindowBubble = $.ninja().button({
    html: 'Pop-Up Window'
  }).select(function () {
    $bubbleWindow = $buttonWindowBubble.ninja().bubble({
      html: ' Loading...',
      pop: true,
      window: true
    }).prepend($spinner);
    /* Fake asynchronous delay */
    setTimeout(function () {
      $bubbleWindow.html('Document body bubble content loaded via ninja().html().');
    }, 2000);
  }).deselect(function () {
    $bubbleWindow.detach();
  });
  $body.append($title.clone().text('Pop-Up'), $buttonBubble, ' ', $buttonListBubble, ' ', $buttonWindowBubble);

  /* Rating */
  var $rating = $.ninja().rating({
    choices: [{
      html: $('
', {
        text: 'One star.'
      }),
      select: function () {
        console.log('Local select function called.');
      }
    },
    {
      html: $('
', {
        text: 'Two stars.'
      })
    },
    {
      html: $('
', {
        text: 'Three stars.'
      })
    },
    {
      html: $('
', {
        text: 'Four stars.'
      })
    },
    {
      html: $('
', {
        text: 'Five stars.'
      })
    }],
    starsAverage: 3
  }).select(function (event) {
    console.log('Global select function called returning: ' + event.html.text());
  });
  $body.append($title.clone().text('Rating'), $rating);

  /* Slider */
  var $slider = $.ninja().slider({
    choices: [{
      html: '0 dB',
      select: function (event) {
        console.log(event.choice.html);
      }
    },
    {
      html: '10 dB',
      select: function (event) {
        console.log(event.choice.html + ': Light leaf rustling, calm breathing');
      }
    },
    {
      html: '20-30 dB',
      select: function (event) {
        console.log(event.choice.html + ': Very calm room');
      }

    },
    {
      html: '40-60 dB',
      select: function (event) {
        console.log(event.choice.html + ': Normal conversation at 1 m');
      }
    },
    {
      html: '60 dB',
      select: function (event) {
        console.log(event.choice.html + ': TV set at home level at 1 m');
      }
    },
    {
      html: '60-80 dB',
      select: function (event) {
        console.log(event.choice.html + ': Passenger car at 10 m');
      }
    },
    {
      html: '78 dB',
      select: function (event) {
        console.log(event.choice.html + ': Hearing damage over long-term exposure, need not be continuous');
      }
    },
    {
      html: '80-90 dB',
      select: function (event) {
        console.log(event.choice.html + ': Traffic on a busy roadway at 10 m');
      }
    },
    {
      html: '100 dB',
      select: function (event) {
        console.log(event.choice.html + ': Jack hammer at 1 m');
      }
    },
    {
      html: '120 dB',
      select: function (event) {
        console.log(event.choice.html + ': Hearing damage immediately possible');
      }
    },
    {
      html: '130 dB',
      select: function (event) {
        console.log(event.choice.html + ': Threshold of pain');
      }
    },
    {
      html: '150 dB',
      select: function (event) {
        console.log(event.choice.html + ': Jet engine at 30 m');
      }
    },
    {
      html: '168 dB',
      select: function (event) {
        console.log(event.choice.html + ': M1 Garand rifle being fired at 1 m');
      }
    }],
    slot: 3,
    title: 'Volume'
  }).select(function (event) {
    console.log('Slider returns: ' + event.choice.html);
  });
  $body.append($title.clone().text('Slider'), $slider);

  /* Suggest */
  var $suggest = $.ninja().suggest({
    html: $.ninja().icon('magnifyingGlass'),
    placeholder: 'Ninja UI Search',
    width: '50%'
  }).change(function (event) {
    $.ajax({
      url: 'http://clients1.google.com/complete/search',
      dataType: 'jsonp',
      data: {
        q: event.value,
        ds: '',
        nolabels: 't'
      },
      success: function (data, message) {
        $suggest.update({
          choices: $.map(data[1], function (item) {
            return {
              html: item[0]
            };
          })
        });
      },
      error: function (request, status, error) {
        console.error(error);
        $suggest.update({
          choices: [{
            html: $('
', {
              css: {
                color: 'red'
              },
              text: 'Server error: ' + error
            }),
            spacer: true
          }]
        });
      },
      timeout: 4000
    });
  }).select(function (event) {
    console.log('Global select function called returning: ' + event.html);
  });
  $body.append($title.clone().text('Suggest'), $suggest);

}(jQuery));<|endoftext|>


<commit_before>'use strict';

require('mocha');
var expect = require('expect.js');
var exec = require('child_process').exec;
var fs = require('fs');

describe('grunt-parallelize', function() {
  describe('grunt parallelize:task:target', function() {
    it('supports "Compact Format"', function(done) {
      testGruntfile('compactFormat', done);
    });

    it('supports "Files Array Format"', function(done) {
      testGruntfile('filesArrayFormat', done);
    });

    it('runs and displays all child tasks if some task has error"', function(done) {
      testGruntfile('containsError', done);
    });
  });

  describe('grunt parallelize:task', function() {
    this.timeout(5000);
    it('runs all targets', function(done) {
      testGruntfile('runAllTargets', done);
    });

    it('runs and displays all targets if some target has error"', function(done) {
      testGruntfile('someTargetContainsError', done);
    });
  });

  describe('grunt parallelize', function() {
    this.timeout(5000);
    it('runs all tasks', function(done) {
      testGruntfile('runAllTasks', done);
    });
  });

  describe('detect processes', function() {
    it('detects from target options', function(done) {
      testGruntfile('targetOption', done);
    });

    it('detects from task options', function(done) {
      testGruntfile('taskOption', done);
    });
  });

  describe('Writes files', function() {
    it('Compact Format', function(done){
      testGruntfileWithFileWrite('compactFormatWithDest', done);
    });

    it('Files Array Format', function(done){
      testGruntfileWithFileWrite('filesArrayFormatWithDest', done);
    });

    it('Files Object Format', function(done){
      testGruntfileWithFileWrite('filesObjectFormatWithDest', done);
    });
  });
});

function testGruntfileWithFileWrite(name, callback){
  var prefix = __dirname + '/cases/' + name;
  var gruntfile = prefix + '.Gruntfile.js';
  var expectedDir = __dirname + '/fixtures/file_output/';
  var expectedFiles = [];
  fs.readdirSync(expectedDir).forEach(function(file){
    if (file.indexOf(name) === 0) {
      expectedFiles.push(file);
    }
  });
  var outputDir = __dirname + '/output/';
  // clean up the output dir
  deleteFolderRecursive(outputDir);

  runGruntfile(gruntfile, function(err, stdout, stderr) {
    expectedFiles.forEach(function(file){
      expect(fs.readFileSync(outputDir + file, {encoding: 'utf8'}))
        .to.be(fs.readFileSync(expectedDir + file, {encoding: 'utf8'}));
    });
    callback(err);
  });
}

function testGruntfile(name, callback) {
  var prefix = __dirname + '/cases/' + name;
  var gruntfile = prefix + '.Gruntfile.js';
  runGruntfile(gruntfile, function(err, stdout, stderr) {
    var expectedFile = prefix + (err ? '.ng.txt' : '.ok.txt');
    var expected;
    try {
      expected = fs.readFileSync(expectedFile, {encoding: 'utf8'});
    } catch (e) {
      // ng is unexpected.
      console.log('stdout: ' + stdout);
      callback(err || stderr || stdout || true);
      return;
    }
    try {
      expect(stdout).to.be(expected);
    } catch (e) {
      console.log('expected:');
      console.log(expected);
      console.log('actual:');
      console.log(stdout);
      throw e;
    }
    callback();
  });
}

function runGruntfile(gruntfile, callback) {
  var cmd = ['grunt', '--no-color', '--gruntfile', gruntfile].join(' ');
  var options = {};
  exec(cmd, options, callback);
}

function deleteFolderRecursive(path) {
  var files = [];
  if( fs.existsSync(path) ) {
    files = fs.readdirSync(path);
    files.forEach(function(file,index){
      var curPath = path + '/' + file;
      if(fs.lstatSync(curPath).isDirectory()) { // recurse
        deleteFolderRecursive(curPath);
      } else { // delete file
        fs.unlinkSync(curPath);
      }
    });
    fs.rmdirSync(path);
  }
}
<commit_msg>Sort test ouput to avoid concurrency issues<commit_after>'use strict';

require('mocha');
var expect = require('expect.js');
var exec = require('child_process').exec;
var fs = require('fs');

describe('grunt-parallelize', function() {
  describe('grunt parallelize:task:target', function() {
    it('supports "Compact Format"', function(done) {
      testGruntfile('compactFormat', done);
    });

    it('supports "Files Array Format"', function(done) {
      testGruntfile('filesArrayFormat', done);
    });

    it('runs and displays all child tasks if some task has error"', function(done) {
      testGruntfile('containsError', done);
    });
  });

  describe('grunt parallelize:task', function() {
    this.timeout(5000);
    it('runs all targets', function(done) {
      testGruntfile('runAllTargets', done);
    });

    it('runs and displays all targets if some target has error"', function(done) {
      testGruntfile('someTargetContainsError', done);
    });
  });

  describe('grunt parallelize', function() {
    this.timeout(5000);
    it('runs all tasks', function(done) {
      testGruntfile('runAllTasks', done);
    });
  });

  describe('detect processes', function() {
    it('detects from target options', function(done) {
      testGruntfile('targetOption', done);
    });

    it('detects from task options', function(done) {
      testGruntfile('taskOption', done);
    });
  });

  describe('Writes files', function() {
    it('Compact Format', function(done){
      testGruntfileWithFileWrite('compactFormatWithDest', done);
    });

    it('Files Array Format', function(done){
      testGruntfileWithFileWrite('filesArrayFormatWithDest', done);
    });

    it('Files Object Format', function(done){
      testGruntfileWithFileWrite('filesObjectFormatWithDest', done);
    });
  });
});

function testGruntfileWithFileWrite(name, callback){
  var prefix = __dirname + '/cases/' + name;
  var gruntfile = prefix + '.Gruntfile.js';
  var expectedDir = __dirname + '/fixtures/file_output/';
  var expectedFiles = [];
  fs.readdirSync(expectedDir).forEach(function(file){
    if (file.indexOf(name) === 0) {
      expectedFiles.push(file);
    }
  });
  var outputDir = __dirname + '/output/';
  // clean up the output dir
  deleteFolderRecursive(outputDir);

  runGruntfile(gruntfile, function(err, stdout, stderr) {
    expectedFiles.forEach(function(file){
      expect(fs.readFileSync(outputDir + file, {encoding: 'utf8'}))
        .to.be(fs.readFileSync(expectedDir + file, {encoding: 'utf8'}));
    });
    callback(err);
  });
}

function testGruntfile(name, callback) {
  var prefix = __dirname + '/cases/' + name;
  var gruntfile = prefix + '.Gruntfile.js';
  runGruntfile(gruntfile, function(err, stdout, stderr) {
    var expectedFile = prefix + (err ? '.ng.txt' : '.ok.txt');
    var expected;
    try {
      expected = fs.readFileSync(expectedFile, {encoding: 'utf8'});
    } catch (e) {
      // ng is unexpected.
      console.log('stdout: ' + stdout);
      callback(err || stderr || stdout || true);
      return;
    }
    try {
      expect(stdout.split('\n').sort().join('\n'))
        .to.be(expected.split('\n').sort().join('\n'));
    } catch (e) {
      console.log('expected:');
      console.log(expected);
      console.log('actual:');
      console.log(stdout);
      throw e;
    }
    callback();
  });
}

function runGruntfile(gruntfile, callback) {
  var cmd = ['grunt', '--no-color', '--gruntfile', gruntfile].join(' ');
  var options = {};
  exec(cmd, options, callback);
}

function deleteFolderRecursive(path) {
  var files = [];
  if( fs.existsSync(path) ) {
    files = fs.readdirSync(path);
    files.forEach(function(file,index){
      var curPath = path + '/' + file;
      if(fs.lstatSync(curPath).isDirectory()) { // recurse
        deleteFolderRecursive(curPath);
      } else { // delete file
        fs.unlinkSync(curPath);
      }
    });
    fs.rmdirSync(path);
  }
}
<|endoftext|>


<commit_before>/**
 * Created by sghaida on 5/11/2017.
 */

var mongo   = require('mongoose'),
    Schema  = mongo.Schema;

var category = ['company','public'];

var announcementSchema = new Schema({
    title: String,
    body: String,
    category: {type: String, enum:category},
    imageUrl: {type: String, default: ''},
    creationDate: {type: Date, default: Date.now},
    archiveAfter: {type: Number, default: 30},
    department: {
        type: Schema.Types.ObjectId,
        ref: 'Department'
    },
    author: {
        id: {
            type: Schema.Types.ObjectId,
            ref: 'User'
        },
        name: String
    },
    tags : [{
        type: Schema.Types.ObjectId,
        ref: 'Tag'
    }],
    transaction: {
        reason: String,
        isApproved: {type: Boolean, default: false},
        transactionDate: {type: Date, default: Date.now},
        validatedBy: {type: String}gg
    },
    status: {type: String, default: 'Pending'},
    exposedToCountry: {type: Boolean, default: false},
    exposedGlobally: {type: Boolean, default: false}
});

module.exports = mongo.model('Announcement', announcementSchema);
<commit_msg>fixed typo<commit_after>/**
 * Created by sghaida on 5/11/2017.
 */

var mongo   = require('mongoose'),
    Schema  = mongo.Schema;

var category = ['company','public'];

var announcementSchema = new Schema({
    title: String,
    body: String,
    category: {type: String, enum:category},
    imageUrl: {type: String, default: ''},
    creationDate: {type: Date, default: Date.now},
    archiveAfter: {type: Number, default: 30},
    department: {
        type: Schema.Types.ObjectId,
        ref: 'Department'
    },
    author: {
        id: {
            type: Schema.Types.ObjectId,
            ref: 'User'
        },
        name: String
    },
    tags : [{
        type: Schema.Types.ObjectId,
        ref: 'Tag'
    }],
    transaction: {
        reason: String,
        isApproved: {type: Boolean, default: false},
        transactionDate: {type: Date, default: Date.now},
        validatedBy: {type: String}
    },
    status: {type: String, default: 'Pending'},
    exposedToCountry: {type: Boolean, default: false},
    exposedGlobally: {type: Boolean, default: false}
});

module.exports = mongo.model('Announcement', announcementSchema);
<|endoftext|>


<commit_before>// All credit goes to Rick Olson.
(function($) {

  $.relatizeDate = function(ds) {
    return $.relatizeDate.timeFromNowInWords( new Date(ds) );
  }

  // shortcut
  $r = $.relatizeDate

  $.extend($.relatizeDate, {
    shortDays: [ 'Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat' ],
    days: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
    shortMonths: [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ],
    months: [ 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December' ],

    /**
     * Given a formatted string, replace the necessary items and return.
     * Example: Time.now().strftime("%B %d, %Y") => February 11, 2008
     * @param {String} format The formatted string used to format the results
     */
    strftime: function(date, format) {
      var day = date.getDay(), month = date.getMonth();
      var hours = date.getHours(), minutes = date.getMinutes();

      var pad = function(num) {
        var string = num.toString(10);
        return new Array((2 - string.length) + 1).join('0') + string
      };

      return format.replace(/\%([aAbBcdHImMpSwyY])/g, function(part) {
        switch(part[1]) {
          case 'a': return $r.shortDays[day]; break;
          case 'A': return $r.days[day]; break;
          case 'b': return $r.shortMonths[month]; break;
          case 'B': return $r.months[month]; break;
          case 'c': return date.toString(); break;
          case 'd': return pad(date.getDate()); break;
          case 'H': return pad(hours); break;
          case 'I': return pad((hours + 12) % 12); break;
          case 'm': return pad(month + 1); break;
          case 'M': return pad(minutes); break;
          case 'p': return hours > 12 ? 'PM' : 'AM'; break;
          case 'S': return pad(date.getSeconds()); break;
          case 'w': return day; break;
          case 'y': return pad(date.getFullYear() % 100); break;
          case 'Y': return date.getFullYear().toString(); break;
        }
      })
    },

    timeFromNowInWords: function(targetDate, includeTime) {
      return $r.distanceOfTimeInWords(new Date(), targetDate, includeTime);
    },

    /**
     * Return the distance of time in words between two Date's
     * Example: '5 days ago', 'about an hour ago'
     * @param {Date} fromTime The start date to use in the calculation
     * @param {Date} toTime The end date to use in the calculation
     * @param {Boolean} Include the time in the output
     */
    distanceOfTimeInWords: function(fromTime, toTime, includeTime) {
      var delta = parseInt((toTime.getTime() - fromTime.getTime()) / 1000);
      var figure, unit;
      if (delta < -120) {
        figure = (parseInt(delta / 60)).toString();
        unit = 'minutes';
      } else if (delta < 0) {
        figure = '-1';
        unit = 'minute';
      } else if (delta < 120) {
        figure = '1';
        unit = 'minute';
      } else if (delta < (45*60)) {
        figure = (parseInt(delta / 60)).toString();
        unit = ' minutes';
      } else if (delta < (120*60)) {
        figure = '1';
        unit = 'hour';
      } else if (delta < (24*60*60)) {
        figure = (parseInt(delta / 3600)).toString();
        unit = 'hours';
      } else if (delta < (48*60*60)) {
        figure = '1';
        unit = 'day';
      } else {
        figure = (parseInt(delta / 86400)).toString();
        unit = 'days';
      }
      return {
        figure: figure,
        unit: unit
      };
    }
  })
})(jQuery);
<commit_msg>show currently happening events as 0 minutes<commit_after>// All credit goes to Rick Olson.
(function($) {

  $.relatizeDate = function(ds) {
    return $.relatizeDate.timeFromNowInWords( new Date(ds) );
  }

  // shortcut
  $r = $.relatizeDate

  $.extend($.relatizeDate, {
    shortDays: [ 'Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat' ],
    days: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
    shortMonths: [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ],
    months: [ 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December' ],

    /**
     * Given a formatted string, replace the necessary items and return.
     * Example: Time.now().strftime("%B %d, %Y") => February 11, 2008
     * @param {String} format The formatted string used to format the results
     */
    strftime: function(date, format) {
      var day = date.getDay(), month = date.getMonth();
      var hours = date.getHours(), minutes = date.getMinutes();

      var pad = function(num) {
        var string = num.toString(10);
        return new Array((2 - string.length) + 1).join('0') + string
      };

      return format.replace(/\%([aAbBcdHImMpSwyY])/g, function(part) {
        switch(part[1]) {
          case 'a': return $r.shortDays[day]; break;
          case 'A': return $r.days[day]; break;
          case 'b': return $r.shortMonths[month]; break;
          case 'B': return $r.months[month]; break;
          case 'c': return date.toString(); break;
          case 'd': return pad(date.getDate()); break;
          case 'H': return pad(hours); break;
          case 'I': return pad((hours + 12) % 12); break;
          case 'm': return pad(month + 1); break;
          case 'M': return pad(minutes); break;
          case 'p': return hours > 12 ? 'PM' : 'AM'; break;
          case 'S': return pad(date.getSeconds()); break;
          case 'w': return day; break;
          case 'y': return pad(date.getFullYear() % 100); break;
          case 'Y': return date.getFullYear().toString(); break;
        }
      })
    },

    timeFromNowInWords: function(targetDate, includeTime) {
      return $r.distanceOfTimeInWords(new Date(), targetDate, includeTime);
    },

    /**
     * Return the distance of time in words between two Date's
     * Example: '5 days ago', 'about an hour ago'
     * @param {Date} fromTime The start date to use in the calculation
     * @param {Date} toTime The end date to use in the calculation
     * @param {Boolean} Include the time in the output
     */
    distanceOfTimeInWords: function(fromTime, toTime, includeTime) {
      var delta = parseInt((toTime.getTime() - fromTime.getTime()) / 1000);
      var figure, unit;
      if (delta < 120) {
        figure = '0';
        unit = 'minutes';
      } else if (delta < (45*60)) {
        figure = (parseInt(delta / 60)).toString();
        unit = 'minutes';
      } else if (delta < (120*60)) {
        figure = '1';
        unit = 'hour';
      } else if (delta < (24*60*60)) {
        figure = (parseInt(delta / 3600)).toString();
        unit = 'hours';
      } else if (delta < (48*60*60)) {
        figure = '1';
        unit = 'day';
      } else {
        figure = (parseInt(delta / 86400)).toString();
        unit = 'days';
      }
      return {
        figure: figure,
        unit: unit
      };
    }
  })
})(jQuery);
<|endoftext|>


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

'use strict';

var extend         = require('extend');
var util           = require('util');
var requestFactory = require('../../lib/requestwrapper');
// IMPORTANT:
// Due to the current design, the URL must be the last key on each endpoint or
// it could inadvertently clobber a url query param in the users request.
// see #236
var endpoints      = require('../../lib/alchemy_endpoints.json');
var helper         = require('../../lib/helper');
var pick           = require('object.pick');
function errorFormatter(cb) {
  return function(err, result, response) {
    if (err) {
      cb(err, result);
    }
    else {
      if (result.status === 'OK')
        cb(err,result);
      else
        cb({
          error: result.statusInfo || response['headers']['x-alchemyapi-error-msg'],
          code: 400
        }, null);
    }
  };
}

function createRequest(method) {
  return function(_params, callback ) {
    var params = _params || {};
    var accepted_formats = Object.keys(endpoints[method]);
    var format = helper.getFormat(params, accepted_formats);

    if (format === null) {
      callback(new Error('Missing required parameters: ' +
        accepted_formats.join(', ') +
        ' needs to be specified'));
      return;
    }

    var parameters = {
      options: {
        url: endpoints[method][format],
        method: 'POST',
        json: true,
        qs: pick(params, ['model']),
        form: extend({}, params, {outputMode: 'json'}) // change default output to json
      },
      defaultOptions: this._options
    };
    return requestFactory(parameters, errorFormatter(callback));
  };
}

/**
 *
 * @param options
 * @constructor
 */
function AlchemyLanguage(options) {
  // Default URL
  var serviceDefaults = {
    url: 'https://access.alchemyapi.com/calls'
  };
  // Replace default options with user provided
  this._options = extend(serviceDefaults, options);
}

/**
 * Extracts a grouped, ranked list of named entities (people, companies,
 * organizations, etc.) from text, a URL or HTML.
 */
AlchemyLanguage.prototype.entities = createRequest('entities');

/**
 * Extracts the keywords from text, a URL or HTML.
 */
AlchemyLanguage.prototype.keywords = createRequest('keywords');

/**
 * Tags the concepts from text, a URL or HTML.
 */
AlchemyLanguage.prototype.concepts = createRequest('concepts');

/**
 * Calculates the sentiment for text, a URL or HTML.
 */
AlchemyLanguage.prototype.sentiment = function(params, callback) {
  var _params = extend({}, params);
  var service = (params.target || params.targets) ? 'sentiment_targeted' : 'sentiment';
  if (util.isArray(_params.targets))
    _params.targets = _params.targets.join('|');

  return createRequest(service).call(this, _params, callback);
};
/**
 * Extracts the cleaned text (removes ads, navigation, etc.) for a URL or HTML.
 * if raw = true, extracts the cleaned text (removes ads, navigation, etc.).
 */
AlchemyLanguage.prototype.text = function(params, callback) {
  var service = (params && params.raw) ? 'text_raw' : 'text';
  return createRequest(service).call(this, params, callback);
};

/**
 * Extracts the authors from a URL or HTML.
 */
AlchemyLanguage.prototype.authors = createRequest('authors');

/**
 * Detects the language for text, a URL or HTML.
 */
AlchemyLanguage.prototype.language = createRequest('language');

/**
 * Extracts the title for a URL or HTML.
 *
 * @see http://www.alchemyapi.com/api/text/proc.html
 */
AlchemyLanguage.prototype.title = createRequest('title');

/**
 * Extracts the relations for text, a URL or HTML.
 */
AlchemyLanguage.prototype.relations = createRequest('relations');

/**
 * Categorizes the text for text, a URL or HTML.
 */
AlchemyLanguage.prototype.category = createRequest('category');

/**
 * Extracts the publication date from a webpage or HTML file.
 */
AlchemyLanguage.prototype.publicationDate = createRequest('publication_date');

/**
 * Finds dates in the source text, including relative dates like "next Tuesday"
 * if an anchorDate is set.
 */
AlchemyLanguage.prototype.extractDates = createRequest('extract_dates');

/**
 * Detects the RSS/ATOM feeds for a URL or HTML.
 */
AlchemyLanguage.prototype.feeds = createRequest('feeds');

/**
 * Parses the microformats for a URL or HTML.
 */
AlchemyLanguage.prototype.microformats = createRequest('microformats');

/**
 * Categorized through the taxonomy call for text, HTML, or a URL.
 */
AlchemyLanguage.prototype.taxonomy = createRequest('taxonomy');

/**
 * Combines multiple API operations into a single call.
 */
AlchemyLanguage.prototype.combined = createRequest('combined');

/**
 * Detects emotions (anger, digust, fear, joy, and sadness)
 * for text, HTML, or a URL.
 */
AlchemyLanguage.prototype.emotion = createRequest('emotion');

/**
 * Finds entities and their relationships
 * for text, HTML, or a URL.
 */
AlchemyLanguage.prototype.typedRelations = createRequest('typed_relations');

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

'use strict';

var extend         = require('extend');
var util           = require('util');
var requestFactory = require('../../lib/requestwrapper');
// IMPORTANT:
// Due to the current design, the URL must be the last key on each endpoint or
// it could inadvertently clobber a url query param in the users request.
// see #236
var endpoints      = require('../../lib/alchemy_endpoints.json');
var helper         = require('../../lib/helper');
var pick           = require('object.pick');
function errorFormatter(cb) {
  return function(err, result, response) {
    if (err) {
      cb(err, result);
    }
    else {
      if (result.status === 'OK')
        cb(err,result);
      else
        cb({
          error: result.statusInfo || response['headers']['x-alchemyapi-error-msg'],
          code: 400
        }, null);
    }
  };
}

function createRequest(method) {
  return function(_params, callback ) {
    var params = _params || {};
    var accepted_formats = Object.keys(endpoints[method]);
    var format = helper.getFormat(params, accepted_formats);

    if (format === null) {
      callback(new Error('Missing required parameters: ' +
        accepted_formats.join(', ') +
        ' needs to be specified'));
      return;
    }

    var parameters = {
      options: {
        url: endpoints[method][format],
        method: 'POST',
        json: true,
        qs: pick(params, ['model']),
        form: extend({}, params, {outputMode: 'json'}) // change default output to json
      },
      defaultOptions: this._options
    };
    return requestFactory(parameters, errorFormatter(callback));
  };
}

/**
 *
 * @param options
 * @constructor
 */
function AlchemyLanguage(options) {
  // Default URL
  var serviceDefaults = {
    url: 'https://access.alchemyapi.com/calls'
  };
  // Replace default options with user provided
  this._options = extend(serviceDefaults, options);
}

/**
 * Extracts a grouped, ranked list of named entities (people, companies,
 * organizations, etc.) from text, a URL or HTML.
 */
AlchemyLanguage.prototype.entities = createRequest('entities');

/**
 * Extracts the keywords from text, a URL or HTML.
 */
AlchemyLanguage.prototype.keywords = createRequest('keywords');

/**
 * Tags the concepts from text, a URL or HTML.
 */
AlchemyLanguage.prototype.concepts = createRequest('concepts');

/**
 * Calculates the sentiment for text, a URL or HTML.
 */
AlchemyLanguage.prototype.sentiment = function(params, callback) {
  var _params = extend({}, params);
  var service = (params.target || params.targets) ? 'sentiment_targeted' : 'sentiment';
  if (util.isArray(_params.targets))
    _params.targets = _params.targets.join('|');

  return createRequest(service).call(this, _params, callback);
};
/**
 * Extracts the cleaned text (removes ads, navigation, etc.) for a URL or HTML.
 * if raw = true, extracts the cleaned text (removes ads, navigation, etc.).
 */
AlchemyLanguage.prototype.text = function(params, callback) {
  var service = (params && params.raw) ? 'text_raw' : 'text';
  return createRequest(service).call(this, params, callback);
};

/**
 * Extracts the authors from a URL or HTML.
 */
AlchemyLanguage.prototype.authors = createRequest('authors');

/**
 * Detects the language for text, a URL or HTML.
 */
AlchemyLanguage.prototype.language = createRequest('language');

/**
 * Extracts the title for a URL or HTML.
 *
 * @see http://www.alchemyapi.com/api/text/proc.html
 */
AlchemyLanguage.prototype.title = createRequest('title');

/**
 * Extracts the relations for text, a URL or HTML.
 */
AlchemyLanguage.prototype.relations = createRequest('relations');

/**
 * Categorizes the text for text, a URL or HTML.
 */
AlchemyLanguage.prototype.category = createRequest('category');

/**
 * Extracts the publication date from a webpage or HTML file.
 */
AlchemyLanguage.prototype.publicationDate = createRequest('publication_date');

/**
 * Finds dates in the source text, including relative dates like "next Tuesday"
 * if an anchorDate is set.
 */
AlchemyLanguage.prototype.dates = createRequest('extract_dates');

/**
 * Detects the RSS/ATOM feeds for a URL or HTML.
 */
AlchemyLanguage.prototype.feeds = createRequest('feeds');

/**
 * Parses the microformats for a URL or HTML.
 */
AlchemyLanguage.prototype.microformats = createRequest('microformats');

/**
 * Categorized through the taxonomy call for text, HTML, or a URL.
 */
AlchemyLanguage.prototype.taxonomy = createRequest('taxonomy');

/**
 * Combines multiple API operations into a single call.
 */
AlchemyLanguage.prototype.combined = createRequest('combined');

/**
 * Detects emotions (anger, digust, fear, joy, and sadness)
 * for text, HTML, or a URL.
 */
AlchemyLanguage.prototype.emotion = createRequest('emotion');

/**
 * Finds entities and their relationships
 * for text, HTML, or a URL.
 */
AlchemyLanguage.prototype.typedRelations = createRequest('typed_relations');

module.exports = AlchemyLanguage;
<|endoftext|>


<commit_before>var cip = require('./cip-methods.js');
var Q = require('q');

var result_mapping = [
    {'key': 'id',
     'short': 'id'},
    {'key': '{af4b2e00-5f6a-11d2-8f20-0000c0e166dc}',
     'short': 'filename'
    },
    {'key': '{f5d1dcd8-c553-4346-8d4d-672c85bb59be}',
     'short': 'license',
    },
    {'key': '{9b071045-118c-4f42-afa1-c3121783ac66}',
     'short': 'creator',
    },
    {'key': '{af4b2e2c-5f6a-11d2-8f20-0000c0e166dc}',
     'short': 'copyright',
    },
    {'key': '{2ce9c8eb-b83d-4a91-9d09-2141cac7de12}',
     'short': 'description',
    },
    {'key': '{af4b2e12-5f6a-11d2-8f20-0000c0e166dc}',
     'short': 'img_height'
    },
    {'key': '{af4b2e11-5f6a-11d2-8f20-0000c0e166dc}',
     'short': 'img_width'
    },
    {'key': '{af4b2e0f-5f6a-11d2-8f20-0000c0e166dc}',
     'short': 'dpi',
    },
    {'key': '{418a4c92-fe63-11d3-9030-0080ad80c556}',
     'short': 'longitude',
    },
    {'key': '{418a4c91-fe63-11d3-9030-0080ad80c556}',
     'short': 'latitude',
    },
    {'key': '{ca6903b8-c3c4-47fa-9592-2d486d766ce0}',
     'short': 'actorname',
    },
    {'key': '{38664623-b081-4251-8c1c-383ef57ac54d}',
     'short': 'locationnote'
    },
    {'key': '{a02dd229-5aa8-4bb4-825a-038cf21f92bd}',
     'short': 'year'
    },
    {'key': '{76f2cca6-3652-40ee-b198-5d0afe931caa}',
     'short': 'assetno'
    },
    {'key': '{59ac5106-a3b4-4152-8647-66cebcb6af48}',
     'short': 'creation_time_from'
    },
    {'key': '{eaf2f030-2bfb-4d75-98ab-fb9bd33affcc}',
     'short': 'creation_time_to'
    },
    {'key': '{65f668d1-b070-494f-a9a3-7b6c3d370e65}',
     'short': 'acceptance_time_from'
    },
    {'key': '{0db7de9e-37fa-47a5-b087-0b1e6066ee86}',
     'short': 'acceptance_time_to'
    },
    {'key': '{1cb94319-9e1f-428e-993f-a78c78947f60}',
     'short': 'timenote'
    },
    {'key': '{8e820869-e338-4761-aa88-3dcd89f8cbae}',
     'short': 'archiveno'
    },
    {'key': '{d6025301-ef5e-4722-b101-78fd28262a98}',
     'short': 'topno'
    },
    {'key': '{8ac71e5d-5ca9-42cf-8c21-02c41e1af5cd}',
     'short': 'archivename'
    },
    {'key': '{9aef60d3-38b4-4e47-8104-d018b83ea6c6}',
     'short': 'unitno'
    },
    {'key': '{51b661a3-585e-4dbd-9e98-85e12ad91190}',
     'short': 'place'
    },
    {'key': '{24252838-de09-46e4-8f7d-f3fb85cde78f}',
     'short': 'city'
    },
    {'key': '{6fb1f61b-14a3-4851-bba0-cf7e71ef59cb}',
     'short': 'short_title'
    },
    {'key': '{af4b2e0c-5f6a-11d2-8f20-0000c0e166dc}',
     'short': 'categories'
    },
    {'key': '{659ca0c6-92d8-4f7a-af58-8a3c69df2ede}',
     'short': 'street'
    },
    {'key': '{ed64a9f8-8d19-4f60-a615-5bd3b188e98a}',
     'short': 'address'
    },
    {'key': '{5bbe594f-d029-4bb5-9c42-8f1ac8c94b7f}',
     'short': 'zipcode'
    },
    {'key': '{af4b2e02-5f6a-11d2-8f20-0000c0e166dc}',
     'short': 'modification_time'
    },
    {'key': '{a493be21-0f70-4cae-9394-703eca848bad}',
     'short': 'review_state'
    },
    {'key': '{bf7a30ac-e53b-4147-95e0-aea8c71340ca}',
     'short': 'cropping_status'
    },
    {'key': '{af4b2e71-5f6a-11d2-8f20-0000c0e166dc}',
     'short': 'related_sub_assets'
    },
    {'key': '{af4b2e72-5f6a-11d2-8f20-0000c0e166dc}',
     'short': 'related_master_assets'
    }
];

exports.result_mapping = result_mapping;

function format_result(fields) {
    var result = {};

    for(var i=0; i < result_mapping.length; ++i) {
        if(result_mapping[i].key in fields) {
            result[result_mapping[i].short] = fields[result_mapping[i].key];
        }
    }

    return result;
}

exports.format_result = format_result;

// This expects that the related_master_assets has been parsed using the
// cip-methods.js's parse_binary_relations
function extend_from_master(nm, metadata) {
    // We expect the formatted metadata to contain a binary field with related
    // master asset ids.
    if(!metadata.related_master_assets || metadata.related_master_assets.length === 0) {
        return metadata;
    }
    // We expect only one master asset.
    if(metadata.related_master_assets.length !== 1) {
        // Compile a textual representation of the master asset id's.
        var master_asset_summary = JSON.stringify(metadata.related_master_assets);
        throw new Error( 'Expected exactly one master asset, received ' +
            metadata.related_master_assets.length+ ': ' +master_asset_summary );
    }
    // Deriving the single master asset id.
    var master_asset_id = metadata.related_master_assets[0].id;

    return cip.get_asset(nm, metadata.catalog, master_asset_id)
    .then(function(master_assets) {
        // We assume only one is returned.
        if(master_assets.length !== 1) {
            throw new Error( 'Expected exactly one master asset, received ' +
                master_assets.length );
        }
        var master_asset = master_assets[0];
        var master_asset_metadata = format_result(master_asset.fields);
        // Overwrite where the original asset has no value.
        for(var f in metadata) {
            var original_value = metadata[f];
            var master_value = master_asset_metadata[f];
            if(!original_value && master_value) {
                // Overwrite with the master assets value.
                metadata[f] = master_value[f];
            }
        }
        return metadata;
    });
}

exports.extend_from_master = extend_from_master;
<commit_msg>Bugfixing the extend metadata from master functinality.<commit_after>var cip = require('./cip-methods.js');
var Q = require('q');

var result_mapping = [
    {'key': 'id',
     'short': 'id'},
    {'key': '{af4b2e00-5f6a-11d2-8f20-0000c0e166dc}',
     'short': 'filename'
    },
    {'key': '{f5d1dcd8-c553-4346-8d4d-672c85bb59be}',
     'short': 'license',
    },
    {'key': '{9b071045-118c-4f42-afa1-c3121783ac66}',
     'short': 'creator',
    },
    {'key': '{af4b2e2c-5f6a-11d2-8f20-0000c0e166dc}',
     'short': 'copyright',
    },
    {'key': '{2ce9c8eb-b83d-4a91-9d09-2141cac7de12}',
     'short': 'description',
    },
    {'key': '{af4b2e12-5f6a-11d2-8f20-0000c0e166dc}',
     'short': 'img_height'
    },
    {'key': '{af4b2e11-5f6a-11d2-8f20-0000c0e166dc}',
     'short': 'img_width'
    },
    {'key': '{af4b2e0f-5f6a-11d2-8f20-0000c0e166dc}',
     'short': 'dpi',
    },
    {'key': '{418a4c92-fe63-11d3-9030-0080ad80c556}',
     'short': 'longitude',
    },
    {'key': '{418a4c91-fe63-11d3-9030-0080ad80c556}',
     'short': 'latitude',
    },
    {'key': '{ca6903b8-c3c4-47fa-9592-2d486d766ce0}',
     'short': 'actorname',
    },
    {'key': '{38664623-b081-4251-8c1c-383ef57ac54d}',
     'short': 'locationnote'
    },
    {'key': '{a02dd229-5aa8-4bb4-825a-038cf21f92bd}',
     'short': 'year'
    },
    {'key': '{76f2cca6-3652-40ee-b198-5d0afe931caa}',
     'short': 'assetno'
    },
    {'key': '{59ac5106-a3b4-4152-8647-66cebcb6af48}',
     'short': 'creation_time_from'
    },
    {'key': '{eaf2f030-2bfb-4d75-98ab-fb9bd33affcc}',
     'short': 'creation_time_to'
    },
    {'key': '{65f668d1-b070-494f-a9a3-7b6c3d370e65}',
     'short': 'acceptance_time_from'
    },
    {'key': '{0db7de9e-37fa-47a5-b087-0b1e6066ee86}',
     'short': 'acceptance_time_to'
    },
    {'key': '{1cb94319-9e1f-428e-993f-a78c78947f60}',
     'short': 'timenote'
    },
    {'key': '{8e820869-e338-4761-aa88-3dcd89f8cbae}',
     'short': 'archiveno'
    },
    {'key': '{d6025301-ef5e-4722-b101-78fd28262a98}',
     'short': 'topno'
    },
    {'key': '{8ac71e5d-5ca9-42cf-8c21-02c41e1af5cd}',
     'short': 'archivename'
    },
    {'key': '{9aef60d3-38b4-4e47-8104-d018b83ea6c6}',
     'short': 'unitno'
    },
    {'key': '{51b661a3-585e-4dbd-9e98-85e12ad91190}',
     'short': 'place'
    },
    {'key': '{24252838-de09-46e4-8f7d-f3fb85cde78f}',
     'short': 'city'
    },
    {'key': '{6fb1f61b-14a3-4851-bba0-cf7e71ef59cb}',
     'short': 'short_title'
    },
    {'key': '{af4b2e0c-5f6a-11d2-8f20-0000c0e166dc}',
     'short': 'categories'
    },
    {'key': '{659ca0c6-92d8-4f7a-af58-8a3c69df2ede}',
     'short': 'street'
    },
    {'key': '{ed64a9f8-8d19-4f60-a615-5bd3b188e98a}',
     'short': 'address'
    },
    {'key': '{5bbe594f-d029-4bb5-9c42-8f1ac8c94b7f}',
     'short': 'zipcode'
    },
    {'key': '{af4b2e02-5f6a-11d2-8f20-0000c0e166dc}',
     'short': 'modification_time'
    },
    {'key': '{a493be21-0f70-4cae-9394-703eca848bad}',
     'short': 'review_state'
    },
    {'key': '{bf7a30ac-e53b-4147-95e0-aea8c71340ca}',
     'short': 'cropping_status'
    },
    {'key': '{af4b2e71-5f6a-11d2-8f20-0000c0e166dc}',
     'short': 'related_sub_assets'
    },
    {'key': '{af4b2e72-5f6a-11d2-8f20-0000c0e166dc}',
     'short': 'related_master_assets'
    }
];

exports.result_mapping = result_mapping;

function format_result(fields) {
    var result = {};

    for(var i=0; i < result_mapping.length; ++i) {
        if(result_mapping[i].key in fields) {
            result[result_mapping[i].short] = fields[result_mapping[i].key];
        }
    }

    return result;
}

exports.format_result = format_result;

// This expects that the related_master_assets has been parsed using the
// cip-methods.js's parse_binary_relations
function extend_from_master(nm, metadata) {
    // We expect the formatted metadata to contain a binary field with related
    // master asset ids.
    if(!metadata.related_master_assets || metadata.related_master_assets.length === 0) {
        return metadata;
    }
    // We expect only one master asset.
    if(metadata.related_master_assets.length !== 1) {
        // Compile a textual representation of the master asset id's.
        var master_asset_summary = JSON.stringify(metadata.related_master_assets);
        throw new Error( 'Expected exactly one master asset, received ' +
            metadata.related_master_assets.length+ ': ' +master_asset_summary );
    }
    // Deriving the single master asset id.
    var master_asset_id = metadata.related_master_assets[0].id;

    return cip.get_asset(nm, metadata.catalog, master_asset_id)
    .then(function(master_assets) {
        // We assume only one is returned.
        if(master_assets.length !== 1) {
            throw new Error( 'Expected exactly one master asset, received ' +
                master_assets.length );
        }
        var master_asset = master_assets[0];
        var master_asset_metadata = format_result(master_asset.fields);
        // Overwrite where the original asset has no value.
        for(var f in metadata) {
            var original_value = metadata[f];
            var master_value = master_asset_metadata[f];
            if(!original_value && master_value) {
                // Overwrite with the master assets value.
                metadata[f] = master_value;
            }
        }
        return metadata;
    });
}

exports.extend_from_master = extend_from_master;
<|endoftext|>