<commit_before>var basic_ajax = {
    XMLHttpFactories: [
        function () {return new XMLHttpRequest()},
        function () {return new ActiveXObject("Msxml2.XMLHTTP")},
        function () {return new ActiveXObject("Msxml3.XMLHTTP")},
        function () {return new ActiveXObject("Microsoft.XMLHTTP")}
    ],

    sendRequest: function(url, callback, errback, postData) {
        var req = basic_ajax.createXMLHTTPObject();
        if (!req) return;
        var method = (postData) ? "POST" : "GET";
        req.open(method,url,true);
        if (postData)
            req.setRequestHeader('Content-type','application/x-www-form-urlencoded');
        req.onreadystatechange = function () {
            if (req.readyState != 4) return;
            if (req.status != 200 && req.status != 304) {
                if (errback) errback(req);
                return;
            }
            callback(req);
        }
        if (req.readyState == 4) return;
        req.send(postData);
    },

    createXMLHTTPObject: function() {
        var xmlhttp = false;
        for (var i=0;i<basic_ajax.XMLHttpFactories.length;i++) {
            try {
                xmlhttp = basic_ajax.XMLHttpFactories[i]();
            }
            catch (e) {
                continue;
            }
            break;
        }
        return xmlhttp;
    },
};

window.onload = function() {

    var last_activity_time = (new Date).getTime();

    // Update last activity time
    document.onmousemove = function(event){
        last_activity_time = (new Date).getTime();
    };

    // Load new comments and chats
    function load_new_comments(){
        if ((new Date).getTime() - last_activity_time < 30000) {
            var els = document.getElementsByTagName('div');
            for(var i = els.length - 1; i > -1; i--) {
                var el = els[i];
                if (el.className.indexOf('comment-list-placeholder') > -1) {
                    var url = '/fetch-new-comments-ajax/' + el.getAttribute('content_type_id') + '/' + el.getAttribute('oid') + '/' + el.getAttribute('last_comment_id') + '/';
                    basic_ajax.sendRequest(url, function(xml_obj) {
                        if (xml_obj.responseText)
                            el.outerHTML = xml_obj.responseText;
                    });
                    break;
                }
            }
        }
        window.setTimeout(load_new_comments, 15000);
    }
    window.setTimeout(load_new_comments, 15000);

};

if (typeof $ != 'undefined')
{

$(document).ready(function(){

    if ($.support.ajax)
    {

    // Ajaxify paging and view modifier navigation for (1) standalone listing (2) listing in a tile.
    $('div.foundry-listing div.pagination a, div.foundry-listing div.jmbo-view-modifier div.item a').live('click', function(e){
        e.preventDefault();
        // todo: need a better way to identify target. Ad-hoc listing may need a name.
        var url_provider = $(this).parents('div.foundry-page-tile:first');
        if (url_provider.length)
        {
            var url = url_provider.attr('original_url');
            var target = $('div.foundry-listing:first', url_provider);
        }
        else
        {
            target = $(this).parents('div.foundry-listing:first');
            url = $(location).attr('href');
        }
        var listing_dom_id = target.attr('id');
        if (listing_dom_id == "foundry-listing-")
            listing_dom_id = null;
        // Strip params. Already present in href.
        url = url.split('?')[0];
        url = url + $(this).attr('href');
        $.get(
            url,
            {},
            function(data){
                if (data.search('id="content"') != -1)
                {
                    // Markup that contains fluff. We want only the content.
                    var el = $('
' + data + '
');
                    // If the listing can be identified then use that, else use
                    // first available one.
                    if (listing_dom_id)
                        var content = $('#' + listing_dom_id, el);
                    else
                        var content = $('div#content div.foundry-listing:first', el);
                    target.html(content.html());
                }
                else
                    target.html(data);
                $(document).trigger("onListingRefresh", [target]);
            }
        );
    });

    var _submit_intercept_common = function(sender, event, target){
        // Common functionality
        event.preventDefault();
        var url = $(sender).attr('action');
        if ((!url) || (url == '.'))
            url = target.attr('original_url');
        var data = $(sender).serialize();
        $.ajax({
            url: url,
            data: data,
            async: false,
            type: 'POST',
            cache: false,
            success: function(data){
                if (data.indexOf('{') == 0)
                {
                    var obj = $.parseJSON(data);
                    $(obj.render_target).html(obj.html);
                    // messages todo
                }
                else
                    if (data.search('id="content"') != -1)
                    {
                        // Markup that contains fluff. We want only the content.
                        var el = $('
' + data + '
');
                        var content = $('div#content', el);
                        target.html(content.html());
                    }
                    else
                        target.html(data);
            }
        })
    };

    // Intercept tile form submit for contained items (eg. a listing). The heading must be preserved.
    // An example is a tile containing a listing of polls.
    $('div.foundry-enable-ajax .foundry-container form').live('submit', function(event){
        event.stopImmediatePropagation();
        var target = $(this).parents('div.item:first');
        _submit_intercept_common(this, event, target);
    });

    // Intercept tile form submit for views with a form.
    // An example is a normal standalone form like site_contact.
    $('div.foundry-enable-ajax form').live('submit', function(event){
        var target = $(this).parents('div.foundry-enable-ajax:first');
        _submit_intercept_common(this, event, target);
    });

    // Post a comment
    $('form.comment-form').live('submit', function(event){
        event.preventDefault();
        var form = $(this);
        var url = $(this).attr('action');
        var data = $(this).serialize();
        $.ajax({
            url: url,
            data: data,
            async: false,
            type: 'POST',
            cache: false,
            success: function(data){
                if (data.indexOf('{') == 0)
                {
                    var obj = $.parseJSON(data);
                    $('div.comment-list').html(obj.html);
                    var el = $('#id_comment');
                    el.val('');
                    $('#c'+obj.obj_id).attr('tabindex', -1).focus();
                }
                else
                    form.replaceWith(data);
            }
        })
    });

    }

});

}
<commit_msg>Remove unused code branch<commit_after>var basic_ajax = {
    XMLHttpFactories: [
        function () {return new XMLHttpRequest()},
        function () {return new ActiveXObject("Msxml2.XMLHTTP")},
        function () {return new ActiveXObject("Msxml3.XMLHTTP")},
        function () {return new ActiveXObject("Microsoft.XMLHTTP")}
    ],

    sendRequest: function(url, callback, errback, postData) {
        var req = basic_ajax.createXMLHTTPObject();
        if (!req) return;
        var method = (postData) ? "POST" : "GET";
        req.open(method,url,true);
        if (postData)
            req.setRequestHeader('Content-type','application/x-www-form-urlencoded');
        req.onreadystatechange = function () {
            if (req.readyState != 4) return;
            if (req.status != 200 && req.status != 304) {
                if (errback) errback(req);
                return;
            }
            callback(req);
        }
        if (req.readyState == 4) return;
        req.send(postData);
    },

    createXMLHTTPObject: function() {
        var xmlhttp = false;
        for (var i=0;i<basic_ajax.XMLHttpFactories.length;i++) {
            try {
                xmlhttp = basic_ajax.XMLHttpFactories[i]();
            }
            catch (e) {
                continue;
            }
            break;
        }
        return xmlhttp;
    },
};

window.onload = function() {

    var last_activity_time = (new Date).getTime();

    // Update last activity time
    document.onmousemove = function(event){
        last_activity_time = (new Date).getTime();
    };

    // Load new comments and chats
    function load_new_comments(){
        if ((new Date).getTime() - last_activity_time < 30000) {
            var els = document.getElementsByTagName('div');
            for(var i = els.length - 1; i > -1; i--) {
                var el = els[i];
                if (el.className.indexOf('comment-list-placeholder') > -1) {
                    var url = '/fetch-new-comments-ajax/' + el.getAttribute('content_type_id') + '/' + el.getAttribute('oid') + '/' + el.getAttribute('last_comment_id') + '/';
                    basic_ajax.sendRequest(url, function(xml_obj) {
                        if (xml_obj.responseText)
                            el.outerHTML = xml_obj.responseText;
                    });
                    break;
                }
            }
        }
        window.setTimeout(load_new_comments, 15000);
    }
    window.setTimeout(load_new_comments, 15000);

};

if (typeof $ != 'undefined')
{

$(document).ready(function(){

    if ($.support.ajax)
    {

    // Ajaxify paging and view modifier navigation for (1) standalone listing (2) listing in a tile.
    $('div.foundry-listing div.pagination a, div.foundry-listing div.jmbo-view-modifier div.item a').live('click', function(e){
        e.preventDefault();
        // todo: need a better way to identify target. Ad-hoc listing may need a name.
        var url_provider = $(this).parents('div.foundry-page-tile:first');
        if (url_provider.length)
        {
            var url = url_provider.attr('original_url');
            var target = $('div.foundry-listing:first', url_provider);
        }
        else
        {
            target = $(this).parents('div.foundry-listing:first');
            url = $(location).attr('href');
        }
        var listing_dom_id = target.attr('id');
        if (listing_dom_id == "foundry-listing-")
            listing_dom_id = null;
        // Strip params. Already present in href.
        url = url.split('?')[0];
        url = url + $(this).attr('href');
        $.get(
            url,
            {},
            function(data){
                // Markup contains fluff. We want only the content.
                var el = $('
' + data + '
');
                // If the listing can be identified then use that, else use
                // first available one.
                if (listing_dom_id)
                    var content = $('#' + listing_dom_id, el);
                else
                    var content = $('div#content div.foundry-listing:first', el);
                target.html(content.html());
                $(document).trigger("onListingRefresh", [target]);
            }
        );
    });

    var _submit_intercept_common = function(sender, event, target){
        // Common functionality
        event.preventDefault();
        var url = $(sender).attr('action');
        if ((!url) || (url == '.'))
            url = target.attr('original_url');
        var data = $(sender).serialize();
        $.ajax({
            url: url,
            data: data,
            async: false,
            type: 'POST',
            cache: false,
            success: function(data){
                if (data.indexOf('{') == 0)
                {
                    var obj = $.parseJSON(data);
                    $(obj.render_target).html(obj.html);
                    // messages todo
                }
                else
                    if (data.search('id="content"') != -1)
                    {
                        // Markup that contains fluff. We want only the content.
                        var el = $('
' + data + '
');
                        var content = $('div#content', el);
                        target.html(content.html());
                    }
                    else
                        target.html(data);
            }
        })
    };

    // Intercept tile form submit for contained items (eg. a listing). The heading must be preserved.
    // An example is a tile containing a listing of polls.
    $('div.foundry-enable-ajax .foundry-container form').live('submit', function(event){
        event.stopImmediatePropagation();
        var target = $(this).parents('div.item:first');
        _submit_intercept_common(this, event, target);
    });

    // Intercept tile form submit for views with a form.
    // An example is a normal standalone form like site_contact.
    $('div.foundry-enable-ajax form').live('submit', function(event){
        var target = $(this).parents('div.foundry-enable-ajax:first');
        _submit_intercept_common(this, event, target);
    });

    // Post a comment
    $('form.comment-form').live('submit', function(event){
        event.preventDefault();
        var form = $(this);
        var url = $(this).attr('action');
        var data = $(this).serialize();
        $.ajax({
            url: url,
            data: data,
            async: false,
            type: 'POST',
            cache: false,
            success: function(data){
                if (data.indexOf('{') == 0)
                {
                    var obj = $.parseJSON(data);
                    $('div.comment-list').html(obj.html);
                    var el = $('#id_comment');
                    el.val('');
                    $('#c'+obj.obj_id).attr('tabindex', -1).focus();
                }
                else
                    form.replaceWith(data);
            }
        })
    });

    }

});

}
<|endoftext|>


<commit_before>

module.exports = {
	port: 7867
	,dbOptions: [

		'test1'
		,'test1user'
		,'test1password'

		,{
			host: 'localhost'
			,dialect: 'mysql'
		}
	]

}<commit_msg>deving<commit_after>
const

module.exports = {

	//port
	port: 7867

	//db connect options
	,dbInitOptions: [

		'test1' //db name
		,'test1user' //db user
		,'test1password' //db user password

		,{ //options
			host: 'localhost'
			,dialect: 'mysql'
		}

	]

	,models: {

		//table name
		User: [

			//table defination
			{
				name: {
					type: Sequelize.STRING
				}
				,age: {
					type: Sequelize.INTEGER
				}
			}

			//table option
			,{
				timestamps: true
			}

		]

		//another table name
		Company: [

			//table defination
			{
				name: {
					type: Sequelize.STRING
				}
				,desc: {
					type: Sequelize.STRING
				}
			}

			//table option
			,{
				timestamps: true
			}

		]

	}

}<|endoftext|>


<commit_before>import React, {Component} from 'react';
import List from 'material-ui/List';
import { withStyles } from 'material-ui/styles';
import axios from 'axios';

import CategoryWidget from '../CategoryWidget/CategoryWidget.js'
import CategoryCreator from '../CategoryCreator/CategoryCreator.js'

axios.defaults.xsrfCookieName = 'csrftoken';
axios.defaults.xsrfHeaderName = 'X-CSRFToken';

const styles = theme => ({
  root: {
    margin: '25px auto 0px',
    width: '100%',
    maxWidth: 360,
    backgroundColor: theme.palette.background.paper,
  },
});

class CategoryView extends Component {
  constructor(props) {
    super(props);
    this.state = {
      error: null,
      isLoaded: false,
      data: []
    };
    this.handleDelete = this.handleDelete.bind(this);
    this.handleCreate = this.handleCreate.bind(this);
    this.handleUpdate = this.handleUpdate.bind(this);
  }

  // https://reactjs.org/docs/faq-ajax.html
  componentDidMount() {
    axios.get('/api/categories')
      .then(
        (response) => {
          this.setState({
            isLoaded: true,
            data: response.data
          });
        },
        (error) => {
          this.setState({
            isLoaded: true,
            error
          });
        }
      );
  }

  // Create, Update, Delete handlers.
  handleCreate(e, category, onSuccess, onError) {
    axios.post('/api/categories/', {category: category})
      .then(
        (response) => {
          onSuccess();
          this.setState((prevState) => {
            return {data: prevState.data.concat([response.data])};
          });
        },
        (error) => {
          if (error.response && error.response.status === 400) {
            onError(error);
          } else {
            this.setState({error});
          }
        }
      );
  }

  handleUpdate(e, category, url, onSuccess, onError) {
    axios.patch(url, {category: category})
      .then(
        (response) => {
          onSuccess();
          this.setState((prevState) => {
            let oldData = prevState.data
            let replaceIndex = oldData.findIndex(item => item.url === response.data.url);
            let newData = oldData.splice(replaceIndex, 1, response.data);
            return newData;
          })
        },
        (error) => {
          if (error.response && error.response.status === 400) {
            onError(error);
          } else {
            this.setState({error});
          }
        }
      );
  }

  handleDelete(url) {
    axios.delete(url)
      .then(
        (response) => {
          this.setState((prevState) => {
            return {data: prevState.data.filter(datum => datum.url !==  url)}
          });
        },
        (error) => {
          this.setState({
            error
          });
        }
      );
  }

  render() {
    const { error, isLoaded, data } = this.state;
    if (error) {
      return
Error: {error.message}
;
    } else if (!isLoaded) {
      return
Loading...
;  // TODO loading icon
    } else {
      let categories = data.map(datum =>
        <CategoryWidget
          key={datum.url}
          url={datum.url}
          rank={datum.rank}
          category={datum.category}
          handleDelete={this.handleDelete}
          handleUpdate={this.handleUpdate}>
        </CategoryWidget>
      );
      // TODO do I want to just put the CategoryCreator in the List?
      return (

          <List disablePadding>{categories}</List>
          <CategoryCreator handleCreate={this.handleCreate}></CategoryCreator>

      )
    }
  }
}

export default withStyles(styles)(CategoryView)
<commit_msg>progress for CategoryView<commit_after>import React, {Component} from 'react';
import List from 'material-ui/List';
import { withStyles } from 'material-ui/styles';
import axios from 'axios';

import { CircularProgress } from 'material-ui/Progress';

import CategoryWidget from '../CategoryWidget/CategoryWidget.js'
import CategoryCreator from '../CategoryCreator/CategoryCreator.js'

axios.defaults.xsrfCookieName = 'csrftoken';
axios.defaults.xsrfHeaderName = 'X-CSRFToken';

const styles = theme => ({
  root: {
    margin: '25px auto 0px',
    width: '100%',
    maxWidth: 360,
    backgroundColor: theme.palette.background.paper,
  },
  progressWrapper: {
    display: 'flex',
  },
  progress: {
    margin: '25px auto 0px',
    width: '100%',
  },
});

class CategoryView extends Component {
  constructor(props) {
    super(props);
    this.state = {
      error: null,
      isLoaded: false,
      data: []
    };
    this.handleDelete = this.handleDelete.bind(this);
    this.handleCreate = this.handleCreate.bind(this);
    this.handleUpdate = this.handleUpdate.bind(this);
  }

  // https://reactjs.org/docs/faq-ajax.html
  componentDidMount() {
    axios.get('/api/categories')
      .then(
        (response) => {
          this.setState({
            isLoaded: true,
            data: response.data
          });
        },
        (error) => {
          this.setState({
            isLoaded: true,
            error
          });
        }
      );
  }

  // Create, Update, Delete handlers.
  handleCreate(e, category, onSuccess, onError) {
    axios.post('/api/categories/', {category: category})
      .then(
        (response) => {
          onSuccess();
          this.setState((prevState) => {
            return {data: prevState.data.concat([response.data])};
          });
        },
        (error) => {
          if (error.response && error.response.status === 400) {
            onError(error);
          } else {
            this.setState({error});
          }
        }
      );
  }

  handleUpdate(e, category, url, onSuccess, onError) {
    axios.patch(url, {category: category})
      .then(
        (response) => {
          onSuccess();
          this.setState((prevState) => {
            let oldData = prevState.data
            let replaceIndex = oldData.findIndex(item => item.url === response.data.url);
            let newData = oldData.splice(replaceIndex, 1, response.data);
            return newData;
          })
        },
        (error) => {
          if (error.response && error.response.status === 400) {
            onError(error);
          } else {
            this.setState({error});
          }
        }
      );
  }

  handleDelete(url) {
    axios.delete(url)
      .then(
        (response) => {
          this.setState((prevState) => {
            return {data: prevState.data.filter(datum => datum.url !==  url)}
          });
        },
        (error) => {
          this.setState({
            error
          });
        }
      );
  }

  render() {
    const { error, isLoaded, data } = this.state;
    if (error) {
      return
Error: {error.message}
;
    } else if (!isLoaded) {
      return (

          <CircularProgress className={this.props.classes.progress}/>

      )
    } else {
      let categories = data.map(datum =>
        <CategoryWidget
          key={datum.url}
          url={datum.url}
          rank={datum.rank}
          category={datum.category}
          handleDelete={this.handleDelete}
          handleUpdate={this.handleUpdate}>
        </CategoryWidget>
      );
      // TODO do I want to just put the CategoryCreator in the List?
      return (

          <List disablePadding>{categories}</List>
          <CategoryCreator handleCreate={this.handleCreate}></CategoryCreator>

      )
    }
  }
}

export default withStyles(styles)(CategoryView)
<|endoftext|>


<commit_before>'use strict';

const config = require(`${__dirname}/../config/init`);

/**
 * makeAllRowRequestBody(str)
 * @param string field Field to query parameters from.
 * @param string from Date to query results from.
 * @param string to Date to query results to.
 * @return object Request to be performed body.
 */
exports.makeAllRowRequest = function make(field, from, to, response) {
  config.client.search({
    index: config.index,
    type: config.type,
    body: {
      size: 0,
      query: {
        bool: {
          must: [
            {
              range: {
                "@timestamp": { from, to },
              },
            },
          ],
        },
      },
      aggs: {
        results: {
          terms: {
            size: 10,
            field,
          },
        },
      },
    },
  }).then((body) => {
    response.json({ success: true, hits: body.aggregations.results.buckets });
  }, (error) => {
    response.json({ success: false, message: error.message });
  });
};
<commit_msg>Change the way we retrieve statistics<commit_after>'use strict';

const config = require(`${__dirname}/../config/init`);

/**
 * makeAllRowRequestBody(str)
 * @param string field Field to query parameters from.
 * @param string from Date to query results from.
 * @param string to Date to query results to.
 * @return object Request to be performed body.
 */
exports.makeAllRowRequest = function make(field, from, to, response) {
  config.client.search({
    index: config.index,
    type: config.type,
    body: {
      size: 0,
      query: {
        bool: {
          must: [
            {
              range: {
                "@timestamp": { from, to },
              },
            },
          ],
        },
      },
      aggs: {
        results: {
          terms: {
            size: 10,
            field,
          },
        },
      },
    },
  }).then((body) => {
    response.json({ success: true, hits: body.aggregations.results.buckets });
  }, (error) => {
    response.json({ success: false, message: error.message });
  });
};<|endoftext|>


<commit_before>(function (factory, window) {
  // define an AMD module that relies on 'leaflet'
  if (typeof define === 'function' && define.amd) {
    define(['leaflet'], function (L) {
      factory(L, window.toGeoJSON);
    });

    // define a Common JS module that relies on 'leaflet'
  } else if (typeof exports === 'object') {
    module.exports = function (L) {
      if (L === undefined) {
        if (typeof window !== 'undefined') {
          L = require('leaflet');
        }
      }
      factory(L);
      return L;
    };
  } else if (typeof window !== 'undefined' && window.L) {
    factory(window.L);
  }
}(function (L) {
  L.Polyline.Measure = L.Draw.Polyline.extend({
    addHooks: function () {
      L.Draw.Polyline.prototype.addHooks.call(this);
      if (this._map) {
        this._markerGroup = new L.LayerGroup();
        this._map.addLayer(this._markerGroup);

        this._markers = [];
        this._map.on('click', this._onClick, this);
        this._startShape();
      }
    },

    removeHooks: function () {
      L.Draw.Polyline.prototype.removeHooks.call(this);

      this._clearHideErrorTimeout();

      // !\ Still useful when control is disabled before any drawing (refactor needed?)
      this._map
      .off('pointermove', this._onMouseMove, this)
      .off('mousemove', this._onMouseMove, this)
      .off('click', this._onClick, this);

      this._clearGuides();
      this._container.style.cursor = '';

      this._removeShape();
    },

    _startShape: function () {
      this._drawing = true;
      this._poly = new L.Polyline([], this.options.shapeOptions);
      // this is added as a placeholder, if leaflet doesn't recieve
      // this when the tool is turned off all onclick events are removed
      this._poly._onClick = function () {};

      this._container.style.cursor = 'crosshair';

      this._updateTooltip();
      this._map
      .on('pointermove', this._onMouseMove, this)
      .on('mousemove', this._onMouseMove, this);
    },

    _finishShape: function () {
      this._drawing = false;

      this._cleanUpShape();
      this._clearGuides();

      this._updateTooltip();

      this._map
      .off('pointermove', this._onMouseMove, this)
      .off('mousemove', this._onMouseMove, this);

      this._container.style.cursor = '';
    },

    _removeShape: function () {
      if (!this._poly) return;
      this._map.removeLayer(this._poly);
      delete this._poly;
      this._markers.splice(0);
      this._markerGroup.clearLayers();
    },

    _onClick: function () {
      if (!this._drawing) {
        this._removeShape();
        this._startShape();
        return;
      }
    },

    _getTooltipText: function () {
      var labelText = L.Draw.Polyline.prototype._getTooltipText.call(this);
      if (!this._drawing) {
        labelText.text = '';
      }
      return labelText;
    }
  });

  L.Control.MeasureControl = L.Control.extend({

    statics: {
      TITLE: 'Measure distances'
    },
    options: {
      position: 'topleft',
      handler: {}
    },

    toggle: function () {
      if (this.handler.enabled()) {
        this.handler.disable.call(this.handler);
      } else {
        this.handler.enable.call(this.handler);
      }
    },

    onAdd: function (map) {
      var link = null;
      var className = 'leaflet-control-draw';

      this._container = L.DomUtil.create('div', 'leaflet-bar');

      this.handler = new L.Polyline.Measure(map, this.options.handler);

      this.handler.on('enabled', function () {
        this.enabled = true;
        L.DomUtil.addClass(this._container, 'enabled');
      }, this);

      this.handler.on('disabled', function () {
        delete this.enabled;
        L.DomUtil.removeClass(this._container, 'enabled');
      }, this);

      link = L.DomUtil.create('a', className + '-measure', this._container);
      link.href = '#';
      link.title = L.Control.MeasureControl.TITLE;

      L.DomEvent
      .addListener(link, 'click', L.DomEvent.stopPropagation)
      .addListener(link, 'click', L.DomEvent.preventDefault)
      .addListener(link, 'click', this.toggle, this);

      return this._container;
    }
  });

  L.Map.mergeOptions({
    measureControl: false
  });

  L.Map.addInitHook(function () {
    if (this.options.measureControl) {
      this.measureControl = L.Control.measureControl().addTo(this);
    }
  });

  L.Control.measureControl = function (options) {
    return new L.Control.MeasureControl(options);
  };
}, window));
<commit_msg>Enforce new ESLint setup<commit_after>(function (factory, window) {
  // define an AMD module that relies on 'leaflet'
  if (typeof define === 'function' && define.amd) {
    define(['leaflet'], function (L) {
      factory(L, window.toGeoJSON);
    });

    // define a Common JS module that relies on 'leaflet'
  } else if (typeof exports === 'object') {
    module.exports = function (L) {
      if (L === undefined) {
        if (typeof window !== 'undefined') {
          L = require('leaflet'); // eslint-disable-line import/no-unresolved
        }
      }
      factory(L);
      return L;
    };
  } else if (typeof window !== 'undefined' && window.L) {
    factory(window.L);
  }
}(function (L) {
  L.Polyline.Measure = L.Draw.Polyline.extend({
    addHooks: function () {
      L.Draw.Polyline.prototype.addHooks.call(this);
      if (this._map) {
        this._markerGroup = new L.LayerGroup();
        this._map.addLayer(this._markerGroup);

        this._markers = [];
        this._map.on('click', this._onClick, this);
        this._startShape();
      }
    },

    removeHooks: function () {
      L.Draw.Polyline.prototype.removeHooks.call(this);

      this._clearHideErrorTimeout();

      // !\ Still useful when control is disabled before any drawing (refactor needed?)
      this._map
        .off('pointermove', this._onMouseMove, this)
        .off('mousemove', this._onMouseMove, this)
        .off('click', this._onClick, this);

      this._clearGuides();
      this._container.style.cursor = '';

      this._removeShape();
    },

    _startShape: function () {
      this._drawing = true;
      this._poly = new L.Polyline([], this.options.shapeOptions);
      // this is added as a placeholder, if leaflet doesn't recieve
      // this when the tool is turned off all onclick events are removed
      this._poly._onClick = function () {};

      this._container.style.cursor = 'crosshair';

      this._updateTooltip();
      this._map
        .on('pointermove', this._onMouseMove, this)
        .on('mousemove', this._onMouseMove, this);
    },

    _finishShape: function () {
      this._drawing = false;

      this._cleanUpShape();
      this._clearGuides();

      this._updateTooltip();

      this._map
        .off('pointermove', this._onMouseMove, this)
        .off('mousemove', this._onMouseMove, this);

      this._container.style.cursor = '';
    },

    _removeShape: function () {
      if (!this._poly) return;
      this._map.removeLayer(this._poly);
      delete this._poly;
      this._markers.splice(0);
      this._markerGroup.clearLayers();
    },

    _onClick: function () {
      if (!this._drawing) {
        this._removeShape();
        this._startShape();
      }
    },

    _getTooltipText: function () {
      var labelText = L.Draw.Polyline.prototype._getTooltipText.call(this);
      if (!this._drawing) {
        labelText.text = '';
      }
      return labelText;
    }
  });

  L.Control.MeasureControl = L.Control.extend({

    statics: {
      TITLE: 'Measure distances'
    },
    options: {
      position: 'topleft',
      handler: {}
    },

    toggle: function () {
      if (this.handler.enabled()) {
        this.handler.disable.call(this.handler);
      } else {
        this.handler.enable.call(this.handler);
      }
    },

    onAdd: function (map) {
      var link = null;
      var className = 'leaflet-control-draw';

      this._container = L.DomUtil.create('div', 'leaflet-bar');

      this.handler = new L.Polyline.Measure(map, this.options.handler);

      this.handler.on('enabled', function () {
        this.enabled = true;
        L.DomUtil.addClass(this._container, 'enabled');
      }, this);

      this.handler.on('disabled', function () {
        delete this.enabled;
        L.DomUtil.removeClass(this._container, 'enabled');
      }, this);

      link = L.DomUtil.create('a', className + '-measure', this._container);
      link.href = '#';
      link.title = L.Control.MeasureControl.TITLE;

      L.DomEvent
        .addListener(link, 'click', L.DomEvent.stopPropagation)
        .addListener(link, 'click', L.DomEvent.preventDefault)
        .addListener(link, 'click', this.toggle, this);

      return this._container;
    }
  });

  L.Map.mergeOptions({
    measureControl: false
  });

  L.Map.addInitHook(function () {
    if (this.options.measureControl) {
      this.measureControl = L.Control.measureControl().addTo(this);
    }
  });

  L.Control.measureControl = function (options) {
    return new L.Control.MeasureControl(options);
  };
}, window));
<|endoftext|>


<commit_before>var ArgsParser = require('./args-parser');
var FS = require('./fs');
var File = require('./file');
var stream = require('stream');

var CommandManager = {
  commands: {},
  aliases: {},
};

CommandManager.isValid = function (cmd) {
  return !!(this.commands[cmd] || this.aliases[cmd]);
};

CommandManager.autocomplete = function (cmd) {
  var matches = [];
  cmd = cmd.toLowerCase();

  (Object.keys(this.commands).concat(Object.keys(this.aliases))).forEach(function (command) {
    if (command.substr(0, cmd.length).toLowerCase() === cmd) {
      matches.push(command);
    }
  });

  return matches;
};
CommandManager.parse = function (cmd) {
  if (~cmd.indexOf('|')) {
    cmd = cmd.split('|');
    cmd.forEach(CommandManager.parse);
  }

  cmd = cmd.split(' ');
  var command = cmd.shift();
  var args = cmd.join(' ');
  var stdin = Terminal.stdin;
  var stdout = Terminal.stdout;
  var stderr = Terminal.stderr;
  var next = function () {
    Terminal.prompt();
  };

  var index;

  if (~(index = args.indexOf('>'))) {
    var prev = args[index-1];
    var append = args[index+1] === '>';
    var init = index;

    if (~(['1','2','&']).indexOf(prev)) {
      init--;
    }

    var _args = args.substr(0, init);
    args = args.substr(index+append+1).split(' ').filter(String);
    var path = args.shift();
    args = _args + args.join(' ');

    if (!path) {
      stdout.write('zsh: parse error near `\\n\'');
      return;
    }

    var file = new File(path);

    if (!file.parentExists()) {
      stdout.write('zsh: no such file or directory: ' + file.path);
      return;
    } else if (!file.isValid()) {
      stdout.write('zsh: not a directory: ' + file.path);
      return;
    } else if (file.isDir()) {
      stdout.write('zsh: is a directory: ' + file.path);
      return;
    }

    if (!append) {
      file.clear();
    }

    stdout = new stream.PassThrough();
    stdout.on('data', function(data) {
      file.write(data + '\n', true, true);
    });

    if (prev === '2' || prev === '&') {
      stderr = stdout;
    }
  }

  CommandManager.exec(command, args, stdin, stdout, stderr, next);
};

CommandManager.exec = function (cmd, args, stdin, stdout, stderr, next) {
  if (this.aliases[cmd]) {
    var line = (this.aliases[cmd] + ' ' + args).trim().split(' ');
    return this.exec(line.shift(), line.join(' '), stdin, stdout, stderr, next);
  }

  if (!this.commands[cmd]) {
    stderr.write('zsh: command not found: ' + cmd);
    next();
  } else {
    try {
      args = ArgsParser.parse(args);
      this.commands[cmd].call(undefined, args, stdin, stdout, stderr, next);
    } catch (err) {
      stderr.write('zsh: ' + err.message);
      next();
    }

  }
};

CommandManager.register = function (cmd, fn) {
  this.commands[cmd] = fn;
};

CommandManager.alias = function (cmd, original) {
  if (arguments.length === 0) {
    return this.aliases;
  }
  this.aliases[cmd] = original;
};

CommandManager.unalias = function (cmd) {
  delete this.aliases[cmd];
};

CommandManager.get = function(cmd) {
  return this.commands[cmd];
};

module.exports = CommandManager;
<commit_msg>fix: redirect stdout to file writes file-system<commit_after>var ArgsParser = require('./args-parser');
var FS = require('./fs');
var File = require('./file');
var stream = require('stream');

var CommandManager = {
  commands: {},
  aliases: {},
};

CommandManager.isValid = function (cmd) {
  return !!(this.commands[cmd] || this.aliases[cmd]);
};

CommandManager.autocomplete = function (cmd) {
  var matches = [];
  cmd = cmd.toLowerCase();

  (Object.keys(this.commands).concat(Object.keys(this.aliases))).forEach(function (command) {
    if (command.substr(0, cmd.length).toLowerCase() === cmd) {
      matches.push(command);
    }
  });

  return matches;
};
CommandManager.parse = function (cmd) {
  if (~cmd.indexOf('|')) {
    cmd = cmd.split('|');
    cmd.forEach(CommandManager.parse);
  }

  cmd = cmd.split(' ');
  var command = cmd.shift();
  var args = cmd.join(' ');
  var stdin = Terminal.stdin;
  var stdout = Terminal.stdout;
  var stderr = Terminal.stderr;
  var next = function () {
    Terminal.prompt();
  };

  var index;

  if (~(index = args.indexOf('>'))) {
    var prev = args[index-1];
    var append = args[index+1] === '>';
    var init = index;

    if (~(['1','2','&']).indexOf(prev)) {
      init--;
    }

    var _args = args.substr(0, init);
    args = args.substr(index+append+1).split(' ').filter(String);
    var path = args.shift();
    args = _args + args.join(' ');

    if (!path) {
      stdout.write('zsh: parse error near `\\n\'');
      return;
    }

    var file = new File(path);

    if (!file.parentExists()) {
      stdout.write('zsh: no such file or directory: ' + file.path);
      return;
    } else if (!file.isValid()) {
      stdout.write('zsh: not a directory: ' + file.path);
      return;
    } else if (file.isDir()) {
      stdout.write('zsh: is a directory: ' + file.path);
      return;
    }

    if (!append) {
      file.clear();
    }

    stdout = new stream.PassThrough();
    stdout.on('data', function(data) {
      file.write(data + '\n', true, true);
    });

    if (prev === '2' || prev === '&') {
      stderr = stdout;
    }

    var _next = next;
    next = function () {
      FS.writeFS();
      _next();
    };
  }

  CommandManager.exec(command, args, stdin, stdout, stderr, next);
};

CommandManager.exec = function (cmd, args, stdin, stdout, stderr, next) {
  if (this.aliases[cmd]) {
    var line = (this.aliases[cmd] + ' ' + args).trim().split(' ');
    return this.exec(line.shift(), line.join(' '), stdin, stdout, stderr, next);
  }

  if (!this.commands[cmd]) {
    stderr.write('zsh: command not found: ' + cmd);
    next();
  } else {
    try {
      args = ArgsParser.parse(args);
      this.commands[cmd].call(undefined, args, stdin, stdout, stderr, next);
    } catch (err) {
      stderr.write('zsh: ' + err.message);
      next();
    }

  }
};

CommandManager.register = function (cmd, fn) {
  this.commands[cmd] = fn;
};

CommandManager.alias = function (cmd, original) {
  if (arguments.length === 0) {
    return this.aliases;
  }
  this.aliases[cmd] = original;
};

CommandManager.unalias = function (cmd) {
  delete this.aliases[cmd];
};

CommandManager.get = function(cmd) {
  return this.commands[cmd];
};

module.exports = CommandManager;
<|endoftext|>


<commit_before>/**
 * TimeSide - Web Audio Components
 * Copyright (c) 2008-2009 Samalyse
 * Author: Olivier Guilyardi <olivier samalyse com>
 * License: GNU General Public License version 2.0
 */

TimeSide(function($N) {

    $N.Class.create("Controller", $N.Core, {

        initialize: function($super, cfg) {
            $super();
            this.configure(cfg, {
                player: null,
                soundProvider: null,
                map: null,
                markersDiv: document.getElementById("markers_div_id")
            });
            if (this.cfg.player && !$N.isInstanceOf(this.cfg.player, 'Player')) {
                this.cfg.player = new $N.Player(this.cfg.player);
            }
            this._setupPlayer();
        },

        _setupPlayer: function() {
            this.attach(this.updateMarkersDiv);
            this.cfg.player
            .setSoundProvider(this.cfg.soundProvider)
            .setMarkerMap(this.cfg.map)
            .observe('play', $N.attachFunction(this.cfg.soundProvider, this.cfg.soundProvider.play))
            .observe('pause', $N.attachFunction(this.cfg.soundProvider, this.cfg.soundProvider.pause))
            .observe('move', this.attach(this._onMove))
            .observe('markeradd', this.attach(this._onMarkerAdd))
            .observe('markermove', this.attach(this._onMarkerMove))
            .observe('markeradd2',this.attach(this._onMarkerAdd2))
            .draw();

        },

        _onMarkerAdd2: function(e,data){
            if (this.cfg.map) {
                alert(this.cfg.map._toString());
            }
        },

        _onMove: function(e, data) {
            this.cfg.soundProvider.seek(data.offset);
        },

        updateMarkersDiv: function(nonNullMarkersMap, selectedMarkOffset){
            var div = this.cfg.markersDiv;
            var m = nonNullMarkersMap.markers;
            var l = m.length;
            if(div){
                var d = new Date();
                var textWithFocus;
                div.style.display = "block";
                var doc = document;
                var divChildren = div.childNodes;
                var round = Math.round;
                for(var i=0; i<l; i++){
                    var marker = m[i];
                    var subdiv, text;
                    if(divChildren.length<=i){
                        //create new div
                        subdiv = doc.createElement('div');
                        var header = doc.createElement('div');
                        //creating marker, see marker.js
                        //would be better not to copy this code but to
                        //reference it.
                        var label = doc.createElement('span');
                        label.style.cssText = "color:#fff;background-color:#009;width: '2ex';textAlign: 'center';font-family: 'monospace'";
                        //label.setAttribute("class", $N.cssPrefix + this.cfg.className);
                        label.innerHTML = (i+1);
                        header.appendChild(label);
                        var timeSpan = doc.createElement('span');
                        timeSpan.style.cssText="margin-left:1ex";
                        header.appendChild(timeSpan);
                        subdiv.appendChild(header);

                        text = doc.createElement('textarea');
                        text.style.cssText="margin:0;padding:0;width:100%";

                        var ok = doc.createElement('a');
                        ok.setAttribute("href","#");
                        ok.innerHTML = "OK";
                        subdiv.appendChild(text);
                        subdiv.appendChild(ok);
                        subdiv.style.cssText="margin-bottom:1em;margin-top:1ex";
                        div.appendChild(subdiv);
                    }else{
                        subdiv = divChildren[i];
                        text = subdiv.childNodes[1];
                        header = subdiv.childNodes[0];
                    }
                    var timeStr = this.formatMarkerOffset(marker.offset);

                    header.childNodes[1].innerHTML = timeStr;
                    //updating text
                    text.innerHTML = marker.desc;
                    if(selectedMarkOffset==marker.offset){
                        textWithFocus = text;
                    }
                }
                if(textWithFocus){
                    textWithFocus.focus();
                }
            }
        },

        formatMarkerOffset: function(markerOffset){
            //marker offset is in float format second.decimalPart
            var hours = parseInt(markerOffset/(60*24));
            markerOffset-=hours*(60*24);
            var minutes = parseInt(markerOffset/(60));
            markerOffset-=minutes*(60);
            var seconds = parseInt(markerOffset);
            markerOffset-=seconds;
            var msec = Math.round(markerOffset*100); //show only centiseconds
            //(use 1000* to show milliseconds)
            var format = (hours<10 ? "0"+hours : hours )+":"+
            (minutes<10 ? "0"+minutes : minutes )+":"+
            (seconds<10 ? "0"+seconds : seconds )+"."+
            msec;
            return format;
        },
        _onMarkerMove: function(e, data) {
            if (this.cfg.map) {
                this.cfg.map.move(this.cfg.map.byId(data.id), data.offset);
                this.updateMarkersDiv(this.cfg.map, data.offset);
            }
        },

        _onMarkerAdd: function(e, data) {
            if (this.cfg.map) {
                //this.cfg.map.add(data.offset, 'marker at ' + data.offset);
                this.cfg.map.add(data.offset, '');
                this.updateMarkersDiv(this.cfg.map, data.offset);
            }
        }

    });

    $N.notifyScriptLoad();

});
<commit_msg>fixed bugs in marker move which reset also textarea changes. Now text is saved from textarea into marker description BEFORE markers add/move<commit_after>/**
 * TimeSide - Web Audio Components
 * Copyright (c) 2008-2009 Samalyse
 * Author: Olivier Guilyardi <olivier samalyse com>
 * License: GNU General Public License version 2.0
 */

TimeSide(function($N) {

    $N.Class.create("Controller", $N.Core, {

        initialize: function($super, cfg) {
            $super();
            this.configure(cfg, {
                player: null,
                soundProvider: null,
                map: null,
                markersDiv: document.getElementById("markers_div_id")
            });
            if (this.cfg.player && !$N.isInstanceOf(this.cfg.player, 'Player')) {
                this.cfg.player = new $N.Player(this.cfg.player);
            }
            this._setupPlayer();
        },

        _setupPlayer: function() {
            this.attach(this.updateMarkersDiv);
            this.cfg.player
            .setSoundProvider(this.cfg.soundProvider)
            .setMarkerMap(this.cfg.map)
            .observe('play', $N.attachFunction(this.cfg.soundProvider, this.cfg.soundProvider.play))
            .observe('pause', $N.attachFunction(this.cfg.soundProvider, this.cfg.soundProvider.pause))
            .observe('move', this.attach(this._onMove))
            .observe('markeradd', this.attach(this._onMarkerAdd))
            .observe('markermove', this.attach(this._onMarkerMove))
            .observe('markeradd2',this.attach(this._onMarkerAdd2))
            .draw();

        },

        _onMarkerAdd2: function(e,data){
            if (this.cfg.map) {
                alert(this.cfg.map._toString());
            }
        },

        _onMove: function(e, data) {
            this.cfg.soundProvider.seek(data.offset);
        },

        formatMarkerOffset: function(markerOffset){
            //marker offset is in float format second.decimalPart
            var hours = parseInt(markerOffset/(60*24));
            markerOffset-=hours*(60*24);
            var minutes = parseInt(markerOffset/(60));
            markerOffset-=minutes*(60);
            var seconds = parseInt(markerOffset);
            markerOffset-=seconds;
            var msec = Math.round(markerOffset*100); //show only centiseconds
            //(use 1000* to show milliseconds)
            var format = (hours<10 ? "0"+hours : hours )+":"+
            (minutes<10 ? "0"+minutes : minutes )+":"+
            (seconds<10 ? "0"+seconds : seconds )+"."+
            msec;
            return format;
        },
        _onMarkerMove: function(e, data) {
            if (this.cfg.map) {
                this.refreshMarkersText(this.cfg.map);
                this.cfg.map.move(this.cfg.map.byId(data.id), data.offset);
                this.updateMarkersDiv(this.cfg.map, data.offset);
            }
        },

        _onMarkerAdd: function(e, data) {
            if (this.cfg.map) {
                this.refreshMarkersText(this.cfg.map);
                this.cfg.map.add(data.offset, '');
                this.updateMarkersDiv(this.cfg.map, data.offset);
            }
        },

        refreshMarkersText: function(nonNullMarkersMap){
            var div = this.cfg.markersDiv;
            var m = nonNullMarkersMap.markers;
            var l = m.length;
            if(div){
                var divChildren = div.childNodes;
                for(var i=0; i<l; i++){
                    var marker = m[i];
                    var subdiv = divChildren[i];
                    var text = subdiv.childNodes[1];
                    marker.desc = text.value;
                }
            }

        },
        updateMarkersDiv: function(nonNullMarkersMap, selectedMarkOffset){
            var div = this.cfg.markersDiv;
            var m = nonNullMarkersMap.markers;
            var l = m.length;
            if(div){
                var d = new Date();
                var textWithFocus;
                div.style.display = "block";
                var doc = document;
                var divChildren = div.childNodes;
                var round = Math.round;
                for(var i=0; i<l; i++){
                    var marker = m[i];
                    var subdiv, text;
                    if(divChildren.length<=i){
                        //create new div
                        subdiv = doc.createElement('div');
                        var header = doc.createElement('div');
                        //creating marker, see marker.js
                        //would be better not to copy this code but to
                        //reference it.
                        var label = doc.createElement('span');
                        label.style.cssText = "color:#fff;background-color:#009;width: '2ex';textAlign: 'center';font-family: 'monospace'";
                        //label.setAttribute("class", $N.cssPrefix + this.cfg.className);
                        label.innerHTML = (i+1);
                        header.appendChild(label);
                        var timeSpan = doc.createElement('span');
                        timeSpan.style.cssText="margin-left:1ex";
                        header.appendChild(timeSpan);
                        subdiv.appendChild(header);

                        text = doc.createElement('textarea');
                        text.style.cssText="margin:0;padding:0;width:100%";

                        var ok = doc.createElement('a');
                        ok.setAttribute("href","#");
                        ok.innerHTML = "OK";
                        subdiv.appendChild(text);
                        subdiv.appendChild(ok);
                        subdiv.style.cssText="margin-bottom:1em;margin-top:1ex";
                        div.appendChild(subdiv);
                    }else{
                        subdiv = divChildren[i];
                        text = subdiv.childNodes[1];
                        header = subdiv.childNodes[0];
                    }
                    var timeStr = this.formatMarkerOffset(marker.offset);

                    header.childNodes[1].innerHTML = timeStr;
                    //updating text
                    text.value = marker.desc;

                    if(selectedMarkOffset==marker.offset){
                        textWithFocus = text;
                    }
                }
                if(textWithFocus){
                    textWithFocus.focus();
                }
            }
        }

    });

    $N.notifyScriptLoad();

});
<|endoftext|>


<commit_before>/*
 Licensed to the Apache Software Foundation (ASF) under one or more
 contributor license agreements.  See the NOTICE file distributed with
 this work for additional information regarding copyright ownership.
 The ASF licenses this file to You 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.
*/

function setupUserFromLua(json) {
    if (json.login) {
        setupUser(json.login)
        login = json.login
    }
}

// Callback for hasSeen - marks the email as seen inside the browser and decreases notification count.
function hasSeenResult(json, tid) {
    // Only decrease number if backend says 'seen' has changed
    if (json && json.marked) {
        document.getElementById('notif_' + tid).style.fontWeight = "normal"
        login.notifications--;
        setupUser(login)
    }
}

// Function for telling the backend that we've seen a specific message, as denoted by the MID
function hasSeen(mid, tid) {
    GetAsync("/api/notifications.lua?seen=" + mid, tid, hasSeenResult)
}

// Func for rendering the list of notifications
function renderNotifications(json) {
    var now = new Date().getTime() / 1000
    var deep = true
    // Do we have notifications to show?
    if (json.notifications && json.notifications.length > 0) {
        current_flat_json = json.notifications

        // Make an unordered list, dirty innerHTML style for now.
        var nest = "
"
        for (var i in current_flat_json) {
            var notif = current_flat_json[i]
            if (!notif.epoch) {
                continue;
            }

            var eml = notif
            current_thread_json[i] = eml
            if (eml.subject.length > 90) {
                eml.subject = eml.subject.substr(0, 90) + "..."
            }
            var pmid = eml.nid
            eml.mid = eml.id

            // Have we read this notification already? if not, bold it.
            var bold = eml.seen == 0 ? 'bold' : 'normal'
            var ld = 'default'
            var ti = ''
            if (eml.epoch > (now - 86400)) {
                ld = 'warning'
                ti = "Has activity in the past 24 hours"
            }
            // This sets the list the notif is from and shortens the subject line
            if (deep  && typeof eml.list != undefined && eml.list != null) {
                var elist = (eml.list ? eml.list : "").replace(/[<>]/g, "").replace(/^([^.]+)\./, "$1@")
                var elist2 = eml.list.replace(/[<>]/g, "").replace(/^([^.]+)\./, "$1@")
                if (pm_config.shortLists) {
                    elist = elist.replace(/\.[^.]+\.[^.]+$/, "")
                }
                d = "" + elist + "  "
                if (eml.subject.length > 75) {
                    eml.subject = eml.subject.substr(0, 75) + "..."
                }
            }
            // Convert email date into locale format, firefox or ecma style.
            mdate = new Date(eml.epoch * 1000)
            mdate = mdate.toLocaleFormat ? mdate.toLocaleFormat('%Y-%m-%d %T') : mdate.toLocaleString('en-GB', {
                hour12: false
            })

            // Escape HTML and make the From header have just the sender name
            var subject = eml.subject.replace(/</mg, "<")
            var from = eml.from.replace(/<.*>/, "").length > 0 ? eml.from.replace(/<.*>/, "") : eml.from.replace(/[<>]+/g, "")
            from = from.replace(/\"/g, "")

            // If not viewed, add a hasSeen callback inside it when clicked
            var extras = ""
            if (eml.seen == 0 ) {
                extras = "hasSeen(\"" + pmid + "\", " + i + "); "
            }

            // Add notif to list
            nest += "
   " + subject + " " + d + " " + from + "(" + mdate + ")

"
        }
        nest += "
"
        document.getElementById('notifications').innerHTML = nest
    }
}

// onLoad function, fetches the needed JSON and renders the notif list
function listNotifications() {
    GetAsync("/api/notifications.lua", null, renderNotifications)
    GetAsync("/api/preferences.lua", null, setupUserFromLua)
}<commit_msg>fix user menu on notification page<commit_after>/*
 Licensed to the Apache Software Foundation (ASF) under one or more
 contributor license agreements.  See the NOTICE file distributed with
 this work for additional information regarding copyright ownership.
 The ASF licenses this file to You 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.
*/

function setupUserFromLua(json) {
    if (typeof json.login != undefined && json.login) {
        login = json.login
        if (login.credentials) {
            setupUser(json.login)
        }
    }
}

// Callback for hasSeen - marks the email as seen inside the browser and decreases notification count.
function hasSeenResult(json, tid) {
    // Only decrease number if backend says 'seen' has changed
    if (json && json.marked) {
        document.getElementById('notif_' + tid).style.fontWeight = "normal"
        login.notifications--;
        setupUser(login)
    }
}

// Function for telling the backend that we've seen a specific message, as denoted by the MID
function hasSeen(mid, tid) {
    GetAsync("/api/notifications.lua?seen=" + mid, tid, hasSeenResult)
}

// Func for rendering the list of notifications
function renderNotifications(json) {
    var now = new Date().getTime() / 1000
    var deep = true
    // Do we have notifications to show?
    if (json.notifications && json.notifications.length > 0) {
        current_flat_json = json.notifications

        // Make an unordered list, dirty innerHTML style for now.
        var nest = "
"
        for (var i in current_flat_json) {
            var notif = current_flat_json[i]
            if (!notif.epoch) {
                continue;
            }

            var eml = notif
            current_thread_json[i] = eml
            if (eml.subject.length > 90) {
                eml.subject = eml.subject.substr(0, 90) + "..."
            }
            var pmid = eml.nid
            eml.mid = eml.id

            // Have we read this notification already? if not, bold it.
            var bold = eml.seen == 0 ? 'bold' : 'normal'
            var ld = 'default'
            var ti = ''
            if (eml.epoch > (now - 86400)) {
                ld = 'warning'
                ti = "Has activity in the past 24 hours"
            }
            // This sets the list the notif is from and shortens the subject line
            if (deep  && typeof eml.list != undefined && eml.list != null) {
                var elist = (eml.list ? eml.list : "").replace(/[<>]/g, "").replace(/^([^.]+)\./, "$1@")
                var elist2 = eml.list.replace(/[<>]/g, "").replace(/^([^.]+)\./, "$1@")
                if (pm_config.shortLists) {
                    elist = elist.replace(/\.[^.]+\.[^.]+$/, "")
                }
                d = "" + elist + "  "
                if (eml.subject.length > 75) {
                    eml.subject = eml.subject.substr(0, 75) + "..."
                }
            }
            // Convert email date into locale format, firefox or ecma style.
            mdate = new Date(eml.epoch * 1000)
            mdate = mdate.toLocaleFormat ? mdate.toLocaleFormat('%Y-%m-%d %T') : mdate.toLocaleString('en-GB', {
                hour12: false
            })

            // Escape HTML and make the From header have just the sender name
            var subject = eml.subject.replace(/</mg, "<")
            var from = eml.from.replace(/<.*>/, "").length > 0 ? eml.from.replace(/<.*>/, "") : eml.from.replace(/[<>]+/g, "")
            from = from.replace(/\"/g, "")

            // If not viewed, add a hasSeen callback inside it when clicked
            var extras = ""
            if (eml.seen == 0 ) {
                extras = "hasSeen(\"" + pmid + "\", " + i + "); "
            }

            // Add notif to list
            nest += "
   " + subject + " " + d + " " + from + "(" + mdate + ")

"
        }
        nest += "
"
        document.getElementById('notifications').innerHTML = nest
    }
}

// onLoad function, fetches the needed JSON and renders the notif list
function listNotifications() {
    GetAsync("/api/notifications.lua", null, renderNotifications)
    GetAsync("/api/preferences.lua", null, setupUserFromLua)
}<|endoftext|>


<commit_before>import React from 'react';
import PropTypes from 'prop-types';

import SpellLink from 'common/SpellLink';
import { captureException } from 'common/errorLogger';

import Requirement from './Requirement';

/**
 * This is a common requirement for all checklists that uses settings for CastEfficiency to create a Requirement. It shows the spell and your efficiency as performance depending on the configured cast efficiency efficiency thresholds.
 *
 * This requirement is automatically disabled if the ability's CastEfficiency suggestion is disabled (i.e. if the ability's castEfficiency: { suggestion } is unset or false), or the ability is disabled completely. If you set `onlyWithSuggestion` to `false` in the object when creating this requirement you can change this behavior to always show if the ability is enabled, regardless of the CastEfficiency suggestion property being set.
 */
class GenericMaxCastEfficiencyRequirement extends React.PureComponent {
  static propTypes = {
    spell: PropTypes.number.isRequired,
    name: PropTypes.node,
    castEfficiency: PropTypes.shape({
      efficiency: PropTypes.number.isRequired,
      gotMaxCasts: PropTypes.bool.isRequired,
      recommendedEfficiency: PropTypes.number.isRequired,
      averageIssueEfficiency: PropTypes.number.isRequired,
      majorIssueEfficiency: PropTypes.number.isRequired,
    }).isRequired,
  };

  get thresholds() {
    if (!this.props.castEfficiency) {
      captureException(new Error(`GenericMaxCastEfficiencyRequirement requires that you pass the castEfficiency object yourself. Spell: ${this.props.spell}`));
      return null;
    }
    const {
      casts,
      maxCasts,
    } = this.props.castEfficiency;

    return {
      actual: casts,
      max: maxCasts,
      isLessThan: {
        minor: maxCasts,
        average: maxCasts - 1,
        major: maxCasts - 2,
      },
      style: 'number',
    };
  }

  render() {
    const { spell, name, ...others } = this.props;

    const thresholds = this.thresholds;
    if (!thresholds) {
      return null;
    }

    console.log(thresholds);

    return (
      <Requirement
        name={name || <SpellLink id={spell} />}
        thresholds={thresholds}
        {...others}
      />
    );
  }
}

export default GenericMaxCastEfficiencyRequirement;
<commit_msg>Updated MaxCast component proptypes<commit_after>import React from 'react';
import PropTypes from 'prop-types';

import SpellLink from 'common/SpellLink';
import { captureException } from 'common/errorLogger';

import Requirement from './Requirement';

/**
 * This is a common requirement for all checklists that uses settings for CastEfficiency to create a Requirement. It shows the spell and your efficiency as performance depending on the configured cast efficiency efficiency thresholds.
 *
 * This requirement is automatically disabled if the ability's CastEfficiency suggestion is disabled (i.e. if the ability's castEfficiency: { suggestion } is unset or false), or the ability is disabled completely. If you set `onlyWithSuggestion` to `false` in the object when creating this requirement you can change this behavior to always show if the ability is enabled, regardless of the CastEfficiency suggestion property being set.
 */
class GenericMaxCastEfficiencyRequirement extends React.PureComponent {
  static propTypes = {
    spell: PropTypes.number.isRequired,
    name: PropTypes.node,
    castEfficiency: PropTypes.shape({
      casts: PropTypes.number.isRequired,
      maxCasts: PropTypes.number.isRequired,
    }).isRequired,
  };

  get thresholds() {
    if (!this.props.castEfficiency) {
      captureException(new Error(`GenericMaxCastEfficiencyRequirement requires that you pass the castEfficiency object yourself. Spell: ${this.props.spell}`));
      return null;
    }
    const {
      casts,
      maxCasts,
    } = this.props.castEfficiency;

    return {
      actual: casts,
      max: maxCasts,
      isLessThan: {
        minor: maxCasts,
        average: maxCasts - 1,
        major: maxCasts - 2,
      },
      style: 'number',
    };
  }

  render() {
    const { spell, name, ...others } = this.props;

    const thresholds = this.thresholds;
    if (!thresholds) {
      return null;
    }

    console.log(thresholds);

    return (
      <Requirement
        name={name || <SpellLink id={spell} />}
        thresholds={thresholds}
        {...others}
      />
    );
  }
}

export default GenericMaxCastEfficiencyRequirement;
<|endoftext|>


<commit_before>var expect = require("chai").expect;

var requireHelper = require('../../require-helper');

var CalculatorPrototype = requireHelper('sample/SampleTask');

describe('SampleTask', function () {

  var sampleTask;

  beforeEach(function () {
    sampleTask = new SampleTask();
  });

  xit('Should find both roots of an equation', function (done) {
  });

  xit('Should find a single root for this equation', function (done) {
  });

  xit('Should return an empty array in case no roots are found', function (done) {
  });

  xit('Should return null in case the equation is not valid(non quadratic)', function (done) {
  });
});<commit_msg>Wrong name<commit_after>var expect = require("chai").expect;

var requireHelper = require('../../require-helper');

var SampleTask = requireHelper('sample/SampleTask');

describe('SampleTask', function () {

  var sampleTask;

  beforeEach(function () {
    sampleTask = new SampleTask();
  });

  xit('Should find both roots of an equation', function (done) {
  });

  xit('Should find a single root for this equation', function (done) {
  });

  xit('Should return an empty array in case no roots are found', function (done) {
  });

  xit('Should return null in case the equation is not valid(non quadratic)', function (done) {
  });
});<|endoftext|>


<commit_before>//! annyang
//! version : 1.0.0
//! author  : Tal Ater @TalAter
//! license : MIT
//! https://www.TalAter.com/annyang/
(function () {
  "use strict";

  // Save a reference to the global object (window in the browser)
  var root = this;

  // Get the SpeechRecognition object, while handling browser prefixes
  var SpeechRecognition = root.webkitSpeechRecognition ||
                          root.mozSpeechRecognition ||
                          root.msSpeechRecognition ||
                          root.oSpeechRecognition ||
                          root.SpeechRecognition;

  // Check browser support
  // This is done as early as possible, to make it as fast as possible for unsupported browsers
  if ( !SpeechRecognition ) {
    root.annyang = null;
    return null;
  }

  var commandsList;
  var recognition;
  var lang = 'en-US';
  var callbacks = { start: [], error: [], end: [], result: [], resultMatch: [], resultNoMatch: [], errorNetwork: [], errorPermissionBlocked: [], errorPermissionDenied: [] };
  var autoRestart;
  var lastStartedAt = 0;
  var debugState = false;
  var debugStyle = 'font-weight: bold; color: #00f;';

  // The command matching code is a modified version of Backbone.Router by Jeremy Ashkenas, under the MIT license.
  var optionalParam = /\s*\((.*?)\)\s*/g;
  var optionalRegex = /(\(\?:[^)]+\))\?/g;
  var namedParam    = /(\(\?)?:\w+/g;
  var splatParam    = /\*\w+/g;
  var escapeRegExp  = /[\-{}\[\]+?.,\\\^$|#]/g;
  var commandToRegExp = function(command) {
    command = command.replace(escapeRegExp, '\\$&')
                  .replace(optionalParam, '(?:$1)?')
                  .replace(namedParam, function(match, optional) {
                    return optional ? match : '([^\\s]+)';
                  })
                  .replace(splatParam, '(.*?)')
                  .replace(optionalRegex, '\\s*$1?\\s*');
    return new RegExp('^' + command + '$', 'i');
  };

  // This method receives an array of callbacks to iterate over, and invokes each of them
  var invokeCallbacks = function(callbacks) {
    callbacks.forEach(function(callback) {
      callback.callback.apply(callback.context);
    });
  };

  root.annyang = {
    // Initialize annyang with a list of commands to recognize.
    // e.g. annyang.init({'hello :name': helloFunction})
    // annyang understands commands with named variables, splats, and optional words.
    init: function(commands) {

      // Abort previous instances of recognition already running
      if (recognition && recognition.abort) {
        recognition.abort();
      }

      // initiate SpeechRecognition
      recognition = new SpeechRecognition();

      // Set the max number of alternative transcripts to try and match with a command
      recognition.maxAlternatives = 5;
      recognition.continuous = true;
      // Sets the language to the default 'en-US'. This can be changed with annyang.setLanguage()
      recognition.lang = lang;

      recognition.onstart   = function()      { invokeCallbacks(callbacks.start); };

      recognition.onerror   = function(event) {
        invokeCallbacks(callbacks.error);
        switch (event.error) {
        case 'network':
          invokeCallbacks(callbacks.errorNetwork);
          break;
        case 'not-allowed':
        case 'service-not-allowed':
          // if permission to use the mic is denied, turn off auto-restart
          autoRestart = false;
          // determine if permission was denied by user or automatically.
          if (new Date().getTime()-lastStartedAt < 200) {
            invokeCallbacks(callbacks.errorPermissionBlocked);
          } else {
            invokeCallbacks(callbacks.errorPermissionDenied);
          }
          break;
        }
      };

      recognition.onend     = function() {
        invokeCallbacks(callbacks.end);
        // annyang will auto restart if it is closed automatically and not by user action.
        if (autoRestart) {
          // play nicely with the browser, and never restart annyang automatically more than once per second
          var timeSinceLastStart = new Date().getTime()-lastStartedAt;
          if (timeSinceLastStart < 1000) {
            setTimeout(root.annyang.start, 1000-timeSinceLastStart);
          } else {
            root.annyang.start();
          }
        }
      };

      recognition.onresult  = function(event) {
        invokeCallbacks(callbacks.result);
        var results = event.results[event.resultIndex];
        var commandText;
        // go over each of the 5 results and alternative results received (we've set maxAlternatives to 5 above)
        for (var i = 0; i<results.length; i++) {
          // the text recognized
          commandText = results[i].transcript.trim();
          if (debugState) {
            root.console.log('Speech recognized: %c'+commandText, debugStyle);
          }

          // try and match recognized text to one of the commands on the list
          for (var j = 0, l = commandsList.length; j < l; j++) {
            var result = commandsList[j].command.exec(commandText);
            if (result) {
              var parameters = result.slice(1);
              if (debugState) {
                root.console.log('command matched: %c'+commandsList[j].originalPhrase, debugStyle);
                if (parameters.length) {
                  root.console.log('with parameters', parameters);
                }
              }
              // execute the matched command
              commandsList[j].callback.apply(this, parameters);
              invokeCallbacks(callbacks.resultMatch);
              return true;
            }
          }
        }
        invokeCallbacks(callbacks.resultNoMatch);
        return false;
      };

      // build commands list
      commandsList = [];
      this.addCommands(commands);
    },

    // Start listening (asking for permission first, if needed).
    // Call this after you've initialized annyang with commands.
    // Receives an optional options object:
    // { autoRestart: true }
    start: function(options) {
      options = options || {};
      if (options.autoRestart !== void 0) {
        autoRestart = !!options.autoRestart;
      } else {
        autoRestart = true;
      }
      lastStartedAt = new Date().getTime();
      recognition.start();
    },

    // abort the listening session (aka stop)
    abort: function() {
      autoRestart = false;
      recognition.abort();
    },

    // Turn on output of debug messages to the console. Ugly, but super-handy!
    debug: function(newState) {
      if (arguments.length > 0) {
        debugState = !!newState;
      } else {
        debugState = true;
      }
    },

    // Set the language the user will speak in. If not called, defaults to 'en-US'.
    // e.g. 'fr-FR' (French-France), 'es-CR' (Español-Costa Rica)
    setLanguage: function(language) {
      lang = language;
      if (recognition && recognition.abort) {
        recognition.lang = language;
      }
    },

    // Add additional commands that annyang will respond to. Similar in syntax to annyang.init()
    addCommands: function(commands) {
      var cb,
          command;
      for (var phrase in commands) {
        if (commands.hasOwnProperty(phrase)) {
          cb = root[commands[phrase]] || commands[phrase];
          if (typeof cb !== 'function') {
            continue;
          }
          //convert command to regex
          command = commandToRegExp(phrase);

          commandsList.push({ command: command, callback: cb, originalPhrase: phrase });
        }
      }
      if (debugState) {
        root.console.log('Commands successfully loaded: %c'+commandsList.length, debugStyle);
      }
    },

    // Remove existing commands. Called with a single phrase or an array of phrases
    removeCommands: function(commandsToRemove) {
      commandsToRemove = Array.isArray(commandsToRemove) ? commandsToRemove : [commandsToRemove];
      commandsList = commandsList.filter(function(command) {
        for (var i = 0; i<commandsToRemove.length; i++) {
          if (commandsToRemove[i] === command.originalPhrase) {
            return false;
          }
        }
        return true;
      });
    },

    // Lets the user add a callback of one of 9 types:
    // start, error, end, result, resultMatch, resultNoMatch, errorNetwork, errorPermissionBlocked, errorPermissionDenied
    // Can also optionally receive a context for the callback function as the third argument
    addCallback: function(type, callback, context) {
      if (callbacks[type]  === void 0) {
        return;
      }
      var cb = root[callback] || callback;
      if (typeof cb !== 'function') {
        return;
      }
      callbacks[type].push({callback: cb, context: context || this});
    }
  };

}).call(this);
<commit_msg>Removed whitespace<commit_after>//! annyang
//! version : 1.0.0
//! author  : Tal Ater @TalAter
//! license : MIT
//! https://www.TalAter.com/annyang/
(function () {
  "use strict";

  // Save a reference to the global object (window in the browser)
  var root = this;

  // Get the SpeechRecognition object, while handling browser prefixes
  var SpeechRecognition = root.webkitSpeechRecognition ||
                          root.mozSpeechRecognition ||
                          root.msSpeechRecognition ||
                          root.oSpeechRecognition ||
                          root.SpeechRecognition;

  // Check browser support
  // This is done as early as possible, to make it as fast as possible for unsupported browsers
  if (!SpeechRecognition) {
    root.annyang = null;
    return null;
  }

  var commandsList;
  var recognition;
  var lang = 'en-US';
  var callbacks = { start: [], error: [], end: [], result: [], resultMatch: [], resultNoMatch: [], errorNetwork: [], errorPermissionBlocked: [], errorPermissionDenied: [] };
  var autoRestart;
  var lastStartedAt = 0;
  var debugState = false;
  var debugStyle = 'font-weight: bold; color: #00f;';

  // The command matching code is a modified version of Backbone.Router by Jeremy Ashkenas, under the MIT license.
  var optionalParam = /\s*\((.*?)\)\s*/g;
  var optionalRegex = /(\(\?:[^)]+\))\?/g;
  var namedParam    = /(\(\?)?:\w+/g;
  var splatParam    = /\*\w+/g;
  var escapeRegExp  = /[\-{}\[\]+?.,\\\^$|#]/g;
  var commandToRegExp = function(command) {
    command = command.replace(escapeRegExp, '\\$&')
                  .replace(optionalParam, '(?:$1)?')
                  .replace(namedParam, function(match, optional) {
                    return optional ? match : '([^\\s]+)';
                  })
                  .replace(splatParam, '(.*?)')
                  .replace(optionalRegex, '\\s*$1?\\s*');
    return new RegExp('^' + command + '$', 'i');
  };

  // This method receives an array of callbacks to iterate over, and invokes each of them
  var invokeCallbacks = function(callbacks) {
    callbacks.forEach(function(callback) {
      callback.callback.apply(callback.context);
    });
  };

  root.annyang = {
    // Initialize annyang with a list of commands to recognize.
    // e.g. annyang.init({'hello :name': helloFunction})
    // annyang understands commands with named variables, splats, and optional words.
    init: function(commands) {

      // Abort previous instances of recognition already running
      if (recognition && recognition.abort) {
        recognition.abort();
      }

      // initiate SpeechRecognition
      recognition = new SpeechRecognition();

      // Set the max number of alternative transcripts to try and match with a command
      recognition.maxAlternatives = 5;
      recognition.continuous = true;
      // Sets the language to the default 'en-US'. This can be changed with annyang.setLanguage()
      recognition.lang = lang;

      recognition.onstart   = function()      { invokeCallbacks(callbacks.start); };

      recognition.onerror   = function(event) {
        invokeCallbacks(callbacks.error);
        switch (event.error) {
        case 'network':
          invokeCallbacks(callbacks.errorNetwork);
          break;
        case 'not-allowed':
        case 'service-not-allowed':
          // if permission to use the mic is denied, turn off auto-restart
          autoRestart = false;
          // determine if permission was denied by user or automatically.
          if (new Date().getTime()-lastStartedAt < 200) {
            invokeCallbacks(callbacks.errorPermissionBlocked);
          } else {
            invokeCallbacks(callbacks.errorPermissionDenied);
          }
          break;
        }
      };

      recognition.onend     = function() {
        invokeCallbacks(callbacks.end);
        // annyang will auto restart if it is closed automatically and not by user action.
        if (autoRestart) {
          // play nicely with the browser, and never restart annyang automatically more than once per second
          var timeSinceLastStart = new Date().getTime()-lastStartedAt;
          if (timeSinceLastStart < 1000) {
            setTimeout(root.annyang.start, 1000-timeSinceLastStart);
          } else {
            root.annyang.start();
          }
        }
      };

      recognition.onresult  = function(event) {
        invokeCallbacks(callbacks.result);
        var results = event.results[event.resultIndex];
        var commandText;
        // go over each of the 5 results and alternative results received (we've set maxAlternatives to 5 above)
        for (var i = 0; i<results.length; i++) {
          // the text recognized
          commandText = results[i].transcript.trim();
          if (debugState) {
            root.console.log('Speech recognized: %c'+commandText, debugStyle);
          }

          // try and match recognized text to one of the commands on the list
          for (var j = 0, l = commandsList.length; j < l; j++) {
            var result = commandsList[j].command.exec(commandText);
            if (result) {
              var parameters = result.slice(1);
              if (debugState) {
                root.console.log('command matched: %c'+commandsList[j].originalPhrase, debugStyle);
                if (parameters.length) {
                  root.console.log('with parameters', parameters);
                }
              }
              // execute the matched command
              commandsList[j].callback.apply(this, parameters);
              invokeCallbacks(callbacks.resultMatch);
              return true;
            }
          }
        }
        invokeCallbacks(callbacks.resultNoMatch);
        return false;
      };

      // build commands list
      commandsList = [];
      this.addCommands(commands);
    },

    // Start listening (asking for permission first, if needed).
    // Call this after you've initialized annyang with commands.
    // Receives an optional options object:
    // { autoRestart: true }
    start: function(options) {
      options = options || {};
      if (options.autoRestart !== void 0) {
        autoRestart = !!options.autoRestart;
      } else {
        autoRestart = true;
      }
      lastStartedAt = new Date().getTime();
      recognition.start();
    },

    // abort the listening session (aka stop)
    abort: function() {
      autoRestart = false;
      recognition.abort();
    },

    // Turn on output of debug messages to the console. Ugly, but super-handy!
    debug: function(newState) {
      if (arguments.length > 0) {
        debugState = !!newState;
      } else {
        debugState = true;
      }
    },

    // Set the language the user will speak in. If not called, defaults to 'en-US'.
    // e.g. 'fr-FR' (French-France), 'es-CR' (Español-Costa Rica)
    setLanguage: function(language) {
      lang = language;
      if (recognition && recognition.abort) {
        recognition.lang = language;
      }
    },

    // Add additional commands that annyang will respond to. Similar in syntax to annyang.init()
    addCommands: function(commands) {
      var cb,
          command;
      for (var phrase in commands) {
        if (commands.hasOwnProperty(phrase)) {
          cb = root[commands[phrase]] || commands[phrase];
          if (typeof cb !== 'function') {
            continue;
          }
          //convert command to regex
          command = commandToRegExp(phrase);

          commandsList.push({ command: command, callback: cb, originalPhrase: phrase });
        }
      }
      if (debugState) {
        root.console.log('Commands successfully loaded: %c'+commandsList.length, debugStyle);
      }
    },

    // Remove existing commands. Called with a single phrase or an array of phrases
    removeCommands: function(commandsToRemove) {
      commandsToRemove = Array.isArray(commandsToRemove) ? commandsToRemove : [commandsToRemove];
      commandsList = commandsList.filter(function(command) {
        for (var i = 0; i<commandsToRemove.length; i++) {
          if (commandsToRemove[i] === command.originalPhrase) {
            return false;
          }
        }
        return true;
      });
    },

    // Lets the user add a callback of one of 9 types:
    // start, error, end, result, resultMatch, resultNoMatch, errorNetwork, errorPermissionBlocked, errorPermissionDenied
    // Can also optionally receive a context for the callback function as the third argument
    addCallback: function(type, callback, context) {
      if (callbacks[type]  === void 0) {
        return;
      }
      var cb = root[callback] || callback;
      if (typeof cb !== 'function') {
        return;
      }
      callbacks[type].push({callback: cb, context: context || this});
    }
  };

}).call(this);
<|endoftext|>


<commit_before>'use strict';

// MODULES //

var isArray = require( '@stdlib/utils/is-array' );
var isTypedArrayLike = require( '@stdlib/utils/is-typed-array-like' );
var isInteger = require( '@stdlib/utils/is-integer' );
var popObject = require( './pop_object.js' );
var popTypedArray = require( './pop_typed_array.js' );

// MAIN //

/**
* Removes and returns the last element of a collection.
*
* @param {(Array|TypedArray|Object)} collection - collection
* @throws {TypeError} must provide either an Array, Typed Array, or an array-like Object
* @returns {Array} updated collection and the removed element
*
* @example
* var arr = [ 1.0, 2.0, 3.0, 4.0, 5.0 ];
*
* var out = pop( arr );
* // returns [ [ 1.0, 2.0, 3.0, 4.0 ], 5.0 ]
*
* @example
* var arr = new Float64Array( [ 1.0, 2.0, 3.0, 4.0, 5.0 ] );
* // returns <Float64Array>[ 1.0, 2.0, 3.0, 4.0, 5.0 ]
*
* var out = pop( arr )
* // returns [ <Float64Array>[ 1.0, 2.0, 3.0, 4.0 ], 5.0 ]
*/
function pop( collection ) {
	var v;
	if ( isArray( collection ) ) {
		v = collection.pop();
		return [ collection, v ];
	}
	// Check for a typed-array-like object, as verifying actual typed arrays is expensive...
	if ( isTypedArrayLike( collection ) ) {
		return popTypedArray( collection );
	}
	// Check for an array-like object...
	if (
		collection !== null &&
		typeof collection === 'object' &&
		typeof collection.length === 'number' &&
		isInteger( collection.length ) &&
		collection.length >= 0
	) {
		return popObject( collection );
	}
	throw new TypeError( 'invalid input argument. Must provide either an Array, Typed Array, or an array-like Object. Value: `'+collection+'`.' );
} // end FUNCTION pop()

// EXPORTS //

module.exports = pop;
<commit_msg>Update description<commit_after>'use strict';

// MODULES //

var isArray = require( '@stdlib/utils/is-array' );
var isTypedArrayLike = require( '@stdlib/utils/is-typed-array-like' );
var isInteger = require( '@stdlib/utils/is-integer' );
var popObject = require( './pop_object.js' );
var popTypedArray = require( './pop_typed_array.js' );

// MAIN //

/**
* Removes and returns the last element of a collection.
*
* @param {(Array|TypedArray|Object)} collection - collection
* @throws {TypeError} must provide either an array, typed array, or an array-like object
* @returns {Array} updated collection and the removed element
*
* @example
* var arr = [ 1.0, 2.0, 3.0, 4.0, 5.0 ];
*
* var out = pop( arr );
* // returns [ [ 1.0, 2.0, 3.0, 4.0 ], 5.0 ]
*
* @example
* var arr = new Float64Array( [ 1.0, 2.0, 3.0, 4.0, 5.0 ] );
* // returns <Float64Array>[ 1.0, 2.0, 3.0, 4.0, 5.0 ]
*
* var out = pop( arr )
* // returns [ <Float64Array>[ 1.0, 2.0, 3.0, 4.0 ], 5.0 ]
*/
function pop( collection ) {
	var v;
	if ( isArray( collection ) ) {
		v = collection.pop();
		return [ collection, v ];
	}
	// Check for a typed-array-like object, as verifying actual typed arrays is expensive...
	if ( isTypedArrayLike( collection ) ) {
		return popTypedArray( collection );
	}
	// Check for an array-like object...
	if (
		collection !== null &&
		typeof collection === 'object' &&
		typeof collection.length === 'number' &&
		isInteger( collection.length ) &&
		collection.length >= 0
	) {
		return popObject( collection );
	}
	throw new TypeError( 'invalid input argument. Must provide either an Array, Typed Array, or an array-like Object. Value: `'+collection+'`.' );
} // end FUNCTION pop()

// EXPORTS //

module.exports = pop;
<|endoftext|>


<commit_before>'use strict';

var helpers = require('../helpers');
var stormpath = require('stormpath');
/**
 * Assert that a user has specified valid API credentials before allowing them
 * to continue.  If the user's credentials are invalid, a 401 will be returned
 * along with an appropriate error message.
 *
 * @method
 *
 * @param {Object} req - The http request.
 * @param {Object} res - The http response.
 * @param {nextCallback} next - The callback which is called to continue
 *   processing the request if the user is authenticated.
 */
module.exports = function (req, res, next) {
  var application = req.app.get('stormpathApplication');
  var config = req.app.get('stormpathConfig');
  var logger = req.app.get('stormpathLogger');

  // Wipe user data in case it was previously set by helpers.getUser().
  req.authenticationResult = undefined;
  req.user = undefined;
  req.permissions = undefined;
  res.locals.authenticationResult = undefined;
  res.locals.user = undefined;
  res.locals.permissions = undefined;

  function handleAuthResponse(err, authResult) {
    if (err) {
      logger.info('Attempted to authenticate a user via the HTTP authorization header, but invalid credentials were supplied.');
      return helpers.writeJsonError(res, { status: 401, message: 'Invalid API credentials.' });
    }

    authResult.getAccount(function (err, account) {
      if (err) {
        logger.info('Attempted to retrieve a user\'s account, but this operation failed.');
        return helpers.writeJsonError(res, { status: 401, message: 'Invalid API credentials.' });
      }

      helpers.expandAccount(account, config.expand, logger, function (err, expandedAccount) {
        if (err) {
          logger.info('Attempted to expand a user\'s account, but this operation failed.');
          return helpers.writeJsonError(res, { status: 401, message: 'Invalid API credentials.' });
        }

        res.locals.authenticationResult = authResult;
        res.locals.user = expandedAccount;
        res.locals.permissions = authResult.grantedScopes;
        req.authenticationResult = authResult;
        req.user = expandedAccount;
        req.permissions = authResult.grantedScopes;

        next();
      });
    });
  }

  var authHeader = req.headers.authorization;

  var token = authHeader && authHeader.match(/Bearer .+/) ? authHeader.split('Bearer ')[1] : '';

  var isBasic = req.headers.authorization && req.headers.authorization.match(/Basic .+/);

  if (token) {
    return new stormpath.JwtAuthenticator(application).authenticate(token, handleAuthResponse);
  } else if (isBasic) {
    return application.authenticateApiRequest({ request: req }, handleAuthResponse);
  } else {
    res.status(401).send('Unauthorized');
  }

};
<commit_msg>Pass validation option inside of apiAuthenticationRequired<commit_after>'use strict';

var helpers = require('../helpers');
var stormpath = require('stormpath');
/**
 * Assert that a user has specified valid API credentials before allowing them
 * to continue.  If the user's credentials are invalid, a 401 will be returned
 * along with an appropriate error message.
 *
 * @method
 *
 * @param {Object} req - The http request.
 * @param {Object} res - The http response.
 * @param {nextCallback} next - The callback which is called to continue
 *   processing the request if the user is authenticated.
 */
module.exports = function (req, res, next) {
  var application = req.app.get('stormpathApplication');
  var config = req.app.get('stormpathConfig');
  var logger = req.app.get('stormpathLogger');

  // Wipe user data in case it was previously set by helpers.getUser().
  req.authenticationResult = undefined;
  req.user = undefined;
  req.permissions = undefined;
  res.locals.authenticationResult = undefined;
  res.locals.user = undefined;
  res.locals.permissions = undefined;

  function handleAuthResponse(err, authResult) {
    if (err) {
      logger.info('Attempted to authenticate a user via the HTTP authorization header, but invalid credentials were supplied.');
      return helpers.writeJsonError(res, { status: 401, message: 'Invalid API credentials.' });
    }

    authResult.getAccount(function (err, account) {
      if (err) {
        logger.info('Attempted to retrieve a user\'s account, but this operation failed.');
        return helpers.writeJsonError(res, { status: 401, message: 'Invalid API credentials.' });
      }

      helpers.expandAccount(account, config.expand, logger, function (err, expandedAccount) {
        if (err) {
          logger.info('Attempted to expand a user\'s account, but this operation failed.');
          return helpers.writeJsonError(res, { status: 401, message: 'Invalid API credentials.' });
        }

        res.locals.authenticationResult = authResult;
        res.locals.user = expandedAccount;
        res.locals.permissions = authResult.grantedScopes;
        req.authenticationResult = authResult;
        req.user = expandedAccount;
        req.permissions = authResult.grantedScopes;

        next();
      });
    });
  }

  var authHeader = req.headers.authorization;

  var token = authHeader && authHeader.match(/Bearer .+/) ? authHeader.split('Bearer ')[1] : '';

  var isBasic = req.headers.authorization && req.headers.authorization.match(/Basic .+/);

  if (token) {
    var authenticator = new stormpath.JwtAuthenticator(application).authenticate(token, handleAuthResponse);
    if (config.web.oauth2.password.validationStrategy === 'local') {
      authenticator.withLocalValidation();
    }
    return authenticator;
  } else if (isBasic) {
    return application.authenticateApiRequest({ request: req }, handleAuthResponse);
  } else {
    res.status(401).send('Unauthorized');
  }

};
<|endoftext|>


<commit_before>
(function() {

	'use strict';

	const serverKey = 'key=AAAAJrMVIEw:APA91bEmBIZ3u8kEiKSAh6QOsnpvux9tYPobyRKILZwDT3B4q3eaOOa4Y_zD6kWbAQRojgySBT3j_5Vu9XCn7drTlSClYOGyXrnqtTc3qVG3lAQJzSLpspsw-eccBEvqP8pUsWaPog7d';

	let bloodButtonsActive = [];
	let notification;
	let form;
	let submitBtn;

	Polymer({
		is: 'my-notifications-blood',

		ready: function() {
			form = this.$.notificationForm;
			submitBtn = this.$.submitBtn;
		},

		sendNotification: function(e) {

			let bloodButtonsActive = [];
			let bloodButtons = this.$.buttonsContainer.children;
			let title = this.$.title.value;
			let body = this.$.body.value;
			let toastContainer = this.$.toastContainer;
			let toastSuccess = this.$.toastSuccess;

			for (let i = 0; i < bloodButtons.length; i++) {
				if (bloodButtons[i].hasAttribute('active')) {
					bloodButtonsActive.push(bloodButtons[i]);
				}
			}

			if ((bloodButtonsActive.length !== 0) && (title.length !== 0) && (body.length !== 0)) {
				for (let i = 0; i < bloodButtonsActive.length; i++) {
					let to = bloodButtonsActive[i].getAttribute('value');
					notification =
						{
							'notification':
								{
									'title': title,
									'body': body
								},
							'to': '/topics/' + to
						};

					$.ajax({
						headers: { 'Authorization': serverKey },
						type: 'POST',
						url : 'https://fcm.googleapis.com/fcm/send',
						contentType : 'application/json',
						data : JSON.stringify(notification),
						dataType : 'json',
						success : function(data) {
							toastSuccess.fitInto = toastContainer;
							toastSuccess.open();
							setTimeout(function() {
								form.reset();
								bloodButtonsActive[i].removeAttribute("active");
								bloodButtonsActive[i].setAttribute("area-pressed", false);
								bloodButtonsActive[i].setAttribute("elevation", 1);
							}, 1400);
						},
						error : function() {
							console.log("De notificatie kon niet verzonden worden.");
						}
					})
				}
			}

		}

	});

	form.addEventListener('input', function(event) {
		// Validate the entire form to see if the `Submit` button should be enabled.
		submitBtn.disabled = !form.validate();
	});

})();<commit_msg>input validation completed<commit_after>
(function() {

	'use strict';

	const serverKey = 'key=AAAAJrMVIEw:APA91bEmBIZ3u8kEiKSAh6QOsnpvux9tYPobyRKILZwDT3B4q3eaOOa4Y_zD6kWbAQRojgySBT3j_5Vu9XCn7drTlSClYOGyXrnqtTc3qVG3lAQJzSLpspsw-eccBEvqP8pUsWaPog7d';

	let bloodButtonsActive = [];
	let notification;
	let form;
	let submitBtn;

	Polymer({
		is: 'my-notifications-blood',

		ready: function() {
			form = this.$.notificationForm;
			submitBtn = this.$.submitBtn;
		},

		sendNotification: function(e) {

			let bloodButtonsActive = [];
			let bloodButtons = this.$.buttonsContainer.children;
			let title = this.$.title.value;
			let body = this.$.body.value;
			let toastContainer = this.$.toastContainer;
			let toastSuccess = this.$.toastSuccess;

			for (let i = 0; i < bloodButtons.length; i++) {
				if (bloodButtons[i].hasAttribute('active')) {
					bloodButtonsActive.push(bloodButtons[i]);
				}
			}

			if ((bloodButtonsActive.length !== 0) && (title.length !== 0) && (body.length !== 0)) {
				for (let i = 0; i < bloodButtonsActive.length; i++) {
					let to = bloodButtonsActive[i].getAttribute('value');
					notification =
						{
							'notification':
								{
									'title': title,
									'body': body
								},
							'to': '/topics/' + to
						};

					$.ajax({
						headers: { 'Authorization': serverKey },
						type: 'POST',
						url : 'https://fcm.googleapis.com/fcm/send',
						contentType : 'application/json',
						data : JSON.stringify(notification),
						dataType : 'json',
						success : function(data) {
							toastSuccess.fitInto = toastContainer;
							toastSuccess.open();
							setTimeout(function() {
								form.reset();
								bloodButtonsActive[i].removeAttribute("active");
								bloodButtonsActive[i].setAttribute("area-pressed", false);
								bloodButtonsActive[i].setAttribute("elevation", 1);
							}, 1400);
						},
						error : function() {
							console.log("De notificatie kon niet verzonden worden.");
						}
					})
				}
			}

		}

	});

	form.addEventListener('input', function(event) {
		// Validate the entire form to see if the `Submit` button should be enabled.
		submitBtn.disabled = !form.validate();
	});

})();<|endoftext|>