<commit_before>var fs = require('fs');
var path = require('path');
var words = require('../lib/words')
var lists = words.get();
var _ = require('lodash');
var chalk = require('chalk');
var pluralize = require('pluralize');

exports.add = function(type) {
  var options = [].pop.call(arguments);
  var items = [].slice.call(arguments, 1);
  var list = _.get(lists, type);
  var newList = list.concat(_.difference(items, list));
  if (newList.length !== list.length) {
    _.set(lists, type, newList);
    fs.writeFile(path.resolve(__dirname, './parts-of-speech.json'), words.stringify(lists), { encoding: 'utf8' }, function(err) {
      exports.logBlock(chalk.green(newList.length - list.length), type, 'added');
    });
  }
};

//exports.remove = function(

exports.logBlock = function(count, noun, verb) {
  console.log();
  console.log('  ', count, pluralize(noun, count), verb);
  console.log();
};

<commit_msg>Fix jshint error<commit_after>var fs = require('fs');
var path = require('path');
var words = require('../lib/words');
var lists = words.get();
var _ = require('lodash');
var chalk = require('chalk');
var pluralize = require('pluralize');

exports.add = function(type) {
  var options = [].pop.call(arguments);
  var items = [].slice.call(arguments, 1);
  var list = _.get(lists, type);
  var newList = list.concat(_.difference(items, list));
  if (newList.length !== list.length) {
    _.set(lists, type, newList);
    fs.writeFile(path.resolve(__dirname, './parts-of-speech.json'), words.stringify(lists), { encoding: 'utf8' }, function(err) {
      exports.logBlock(chalk.green(newList.length - list.length), type, 'added');
    });
  }
};

//exports.remove = function(

exports.logBlock = function(count, noun, verb) {
  console.log();
  console.log('  ', count, pluralize(noun, count), verb);
  console.log();
};

<|endoftext|>


<commit_before>import React, { Component } from 'react';
import $ from 'jquery';
import './Filters.css'

class Filters extends Component {
  componentDidMount() {
    //More (Expand) or Less (Collapse)
    $('.categories-menu.menu.nested').each(function(){
      const filterAmount = $(this).find('li').length;
      if( filterAmount > 5){
        $('li', this).eq(4).nextAll().hide().addClass('toggleable');
        $(this).append('
More
');
      }
    });

    $('.categories-menu.menu.nested').on('click','.more', function(){
      if( $(this).hasClass('less') ){
        $(this).text('More').removeClass('less');
      }else{
        $(this).text('Less').addClass('less');
      }
      $(this).siblings('li.toggleable').slideToggle();
    });
  }

  render() {
    return (

SUCHFILTER

             Alle aufheben

           {this.getFilterList({})}

SUCHFILTER

         Alle aufheben

       {this.getFilterList({hideForSmallOnly: true})}

    );
  }

  getFilterList({ hideForSmallOnly }) {
    let classNames = "vertical menu accordion-menu";
    if (hideForSmallOnly) {
      classNames += "hide-for-small-only";
    }
    return (

          Ort

<input className="category-clear-selection" id="category-checkbox1" type="checkbox"/>Category 1

<input className="category-clear-selection" id="category-checkbox2" type="checkbox"/>Category 2

<input className="category-clear-selection" id="category-checkbox3" type="checkbox"/>Category 3

<input className="category-clear-selection" id="category-checkbox4" type="checkbox"/>Category 4

<input className="category-clear-selection" id="category-checkbox5" type="checkbox"/>Category 5

<input className="category-clear-selection" id="category-checkbox6" type="checkbox"/>Category 6

<input className="category-clear-selection" id="category-checkbox7" type="checkbox"/>Category 7

<input className="category-clear-selection" id="category-checkbox8" type="checkbox"/>Category 8

<input className="category-clear-selection" id="category-checkbox9" type="checkbox"/>Category 9

<input className="category-clear-selection" id="category-checkbox10" type="checkbox"/>Category 10

<input className="category-clear-selection" id="category-checkbox11" type="checkbox"/>Category 11

<input className="category-clear-selection" id="category-checkbox12" type="checkbox"/>Category 12

<input className="category-clear-selection" id="category-checkbox13" type="checkbox"/>Category 13

<input className="category-clear-selection" id="category-checkbox14" type="checkbox"/>Category 14

<input className="category-clear-selection" id="category-checkbox15" type="checkbox"/>Category 15

          Anlass

<input id="size-checkbox1" type="checkbox"/>Small

<input id="size-checkbox2" type="checkbox"/>Medium

<input id="size-checkbox3" type="checkbox"/>Large

<input id="size-checkbox3" type="checkbox"/>X-Large

<input id="size-checkbox3" type="checkbox"/>XX-Large

          Personen

<input id="color-checkbox1" type="checkbox"/>All Color

<input id="color-checkbox2" type="checkbox"/>Black

<input id="color-checkbox3" type="checkbox"/>White

<input id="color-checkbox4" type="checkbox"/>Grey

<input id="color-checkbox5" type="checkbox"/>Red

<input id="color-checkbox6" type="checkbox"/>Blue

<input id="color-checkbox7" type="checkbox"/>Green

<input id="color-checkbox8" type="checkbox"/>Purple

<input id="color-checkbox8" type="checkbox"/>Multi-color

          Zertifikate

<input id="price-checkbox1" type="checkbox"/>Under $25

<input id="price-checkbox2" type="checkbox"/>$25–$50

<input id="price-checkbox3" type="checkbox"/>$50–$250

<input id="price-checkbox4" type="checkbox"/>$250–$600

<input id="price-checkbox4" type="checkbox"/>$600–$1,000

    );
  }
}

export default Filters;
<commit_msg>Put filters in `<form>` tags and verify that label clicking wasn't working because of duplicate IDs<commit_after>import React, { Component } from 'react';
import $ from 'jquery';
import './Filters.css'

class Filters extends Component {
  componentDidMount() {
    //More (Expand) or Less (Collapse)
    $('.categories-menu.menu.nested').each(function(){
      const filterAmount = $(this).find('li').length;
      if( filterAmount > 5){
        $('li', this).eq(4).nextAll().hide().addClass('toggleable');
        $(this).append('
More
');
      }
    });

    $('.categories-menu.menu.nested').on('click','.more', function(){
      if( $(this).hasClass('less') ){
        $(this).text('More').removeClass('less');
      }else{
        $(this).text('Less').addClass('less');
      }
      $(this).siblings('li.toggleable').slideToggle();
    });
  }

  render() {
    return (

        <form className="mobile-form">

SUCHFILTER

                Alle aufheben

              {this.getFilterList({isMobileForm: true})}

        </form>

        <form className="desktop-form hide-for-small-only">

SUCHFILTER

            Alle aufheben

          {this.getFilterList({})}
        </form>

    );
  }

  getFilterList({ isMobileForm }) {
    let classNames = "vertical menu accordion-menu";
    let idPrefix = 'mobile-category-checkbox';
    if (!isMobileForm) {
      idPrefix = 'category-checkbox';
      classNames += "hide-for-small-only";
    }
    return (

          Ort

<input className="category-clear-selection" id={idPrefix + "1"} type="checkbox"/>Category 1

<input className="category-clear-selection" id={idPrefix + "2"} type="checkbox"/>Category 2

<input className="category-clear-selection" id={idPrefix + "3"} type="checkbox"/>Category 3

<input className="category-clear-selection" id={idPrefix + "4"} type="checkbox"/>Category 4

<input className="category-clear-selection" id={idPrefix + "5"} type="checkbox"/>Category 5

<input className="category-clear-selection" id={idPrefix + "6"} type="checkbox"/>Category 6

<input className="category-clear-selection" id={idPrefix + "7"} type="checkbox"/>Category 7

<input className="category-clear-selection" id={idPrefix + "8"} type="checkbox"/>Category 8

<input className="category-clear-selection" id={idPrefix + "9"} type="checkbox"/>Category 9

<input className="category-clear-selection" id={idPrefix + "10"} type="checkbox"/>Category 10

<input className="category-clear-selection" id={idPrefix + "11"} type="checkbox"/>Category 11

<input className="category-clear-selection" id={idPrefix + "12"} type="checkbox"/>Category 12

<input className="category-clear-selection" id={idPrefix + "13"} type="checkbox"/>Category 13

<input className="category-clear-selection" id={idPrefix + "14"} type="checkbox"/>Category 14

<input className="category-clear-selection" id={idPrefix + "15"} type="checkbox"/>Category 15

          Anlass

<input id="size-checkbox1" type="checkbox"/>Small

<input id="size-checkbox2" type="checkbox"/>Medium

<input id="size-checkbox3" type="checkbox"/>Large

<input id="size-checkbox3" type="checkbox"/>X-Large

<input id="size-checkbox3" type="checkbox"/>XX-Large

          Personen

<input id="color-checkbox1" type="checkbox"/>All Color

<input id="color-checkbox2" type="checkbox"/>Black

<input id="color-checkbox3" type="checkbox"/>White

<input id="color-checkbox4" type="checkbox"/>Grey

<input id="color-checkbox5" type="checkbox"/>Red

<input id="color-checkbox6" type="checkbox"/>Blue

<input id="color-checkbox7" type="checkbox"/>Green

<input id="color-checkbox8" type="checkbox"/>Purple

<input id="color-checkbox8" type="checkbox"/>Multi-color

          Zertifikate

<input id="price-checkbox1" type="checkbox"/>Under $25

<input id="price-checkbox2" type="checkbox"/>$25–$50

<input id="price-checkbox3" type="checkbox"/>$50–$250

<input id="price-checkbox4" type="checkbox"/>$250–$600

<input id="price-checkbox4" type="checkbox"/>$600–$1,000

    );
  }
}

export default Filters;
<|endoftext|>


<commit_before>/*global define, $, brackets, Mustache*/
define(function (require, exports, module) {
    'use strict';

    var Dialogs = brackets.getModule('widgets/Dialogs'),
		PreferencesManager = brackets.getModule('preferences/PreferencesManager'),
		ProjectManager = brackets.getModule('project/ProjectManager'),
        EditorManager = brackets.getModule('editor/EditorManager'),
        DocumentManager = brackets.getModule('document/DocumentManager'),
		Strings = brackets.getModule('strings'),
		OptionsTemplate = require('text!options.html');

    /**
	 * Displays dialog with JSLint options.
	*/
    function showOptionsDialog() {
        var currentDoc = DocumentManager.getCurrentDocument(),
            opts = [],
			promise,
            dialog,
            varEls,
            varLen,
            inputs,
            inputsLen,
            result,
            i;

		/**
		 * Clears all dialog's options.
		 */
		function clearOptions() {
			varEls.removeClass('true false').
				addClass('default').
				html('default');                // Reset all var elements.

			inputs.val('');                     // Clear input elements' values.
			result.val('');                     // Clear the directive textarea.
			opts = [];                          // Empty options array.
		}

		/**
		 * Generates JSLint Directive.
		*/
        function generateDirective() {
            var optionName,
                optionValue,
                varElement;

            opts = [];                         // Empty options array.

			// Loop through all var element.
            for (i = 0; i < varLen; i += 1) {
                varElement = varEls[i];

                if (!$(varElement).hasClass('default')) {
                    optionName = $(varElement).parent().attr('title');
                    optionValue = $(varElement).attr('class');

                    opts.push(optionName + ': ' + optionValue);
                }
            }

			// Loop through all input elements.
            for (i = 0; i < inputsLen; i += 1) {
                if ($(inputs[i]).val() !== '') {
                    optionName = $(inputs[i]).attr('title');
                    optionValue = $(inputs[i]).val();

                    opts.push(optionName + ': ' + optionValue);
                }
            }

			if (opts.length >= 1) {											// If options array is NOT empty...
				result.val('/*jslint ' + opts.join(', ') + '*/');			// ...display the options as string in results placeholder.
			} else {														// If options array is empty...
				result.val('');											    // ...empty the results placeholder.
			}
		}

        /**
         * Generates JSON string out of options selected.
         */
        function generateJsonString() {
            var i = 0,
                parsedData = {},
                jsonString,
                val;

            for (i; i < opts.length; i += 1) {
                val = opts[i].substr(opts[i].indexOf(':') + 2);

                if (val === 'true') {
                    parsedData[opts[i].substr(0, opts[i].indexOf(':'))] = true;
                } else if (val === 'false') {
                    parsedData[opts[i].substr(0, opts[i].indexOf(':'))] = false;
                } else if (!isNaN(val)) {
                    parsedData[opts[i].substr(0, opts[i].indexOf(':'))] = +val;
                }
            }

            jsonString = JSON.stringify(parsedData, null, '\t');
            result.val(jsonString);
        }

		/**
		 * Inserts JSLint directive on editor body.
		*/
		function insertDirectiveToEditor() {
			var editor = EditorManager.getCurrentFullEditor(),
				editorDoc = editor.document,
                startPosition = {line: 0, ch: 0},
                firstLineContent = currentDoc.getLine(0);

            editor.setCursorPos(startPosition);                             // Set cursor to line 0 and column 0.
            editorDoc.replaceRange(result.val() + '\n', startPosition);	    // Insert directive at first line and push document one line down.

			// Check if document already has a JSLint directive
			// and remove the line with the old directive.
			if (firstLineContent.indexOf('/*jslint') >= 0) {
				editorDoc.replaceRange('', {line: 1, ch: 0}, {line: 2, ch: 0});
			}
		}

        /**
		 * Inserts JSLint directive on editor body.
		*/
        function toggleCheckbox(checkbox, checked) {
            var jsonInput = dialog.find(checkbox);
            jsonInput.attr('checked', checked);
        }

        /**
         * Gets directive from editor and populates the appropriate options in dialog.
         * Assumes that the directive is on the first line of the document.
         */
        function getDirectiveFromEditor() {
            var firstLineContent = currentDoc.getLine(0),
                tempArr = [],
                arr = [],
                tempArrLen,
                arrLen,
                tempArrItem,
                arrItem,
                subStr,
                option,
                i;

            if (firstLineContent.indexOf('/*jslint') >= 0) {
                subStr = firstLineContent.replace('/*jslint', '');
                subStr = subStr.replace('*/', '');
                tempArr = subStr.split(',');
                tempArr = $.map(tempArr, $.trim);
                tempArrLen = tempArr.length;

                for (i = 0; i < tempArrLen; i += 1) {
                    tempArrItem = tempArr[i];

                    option = {
                        name: tempArrItem.substr(0, tempArrItem.indexOf(':')),
                        value: $.trim(tempArrItem.substr(tempArrItem.indexOf(':')).replace(':', ''))
                    };

                    arr.push(option);
                }

                arrLen = arr.length;

                for (i = 0; i < arrLen; i += 1) {
                    arrItem = arr[i];

					// Update the dialog's options only if the values specified are valid (true or false).
                    if (arrItem.value === 'true' || arrItem.value === 'false') {
						dialog.find('.modal-body div[title="' + arrItem.name + '"] var').
							removeClass('default').
							addClass(arrItem.value).
							html(arrItem.value);
					}

					if (arrItem.name === 'indent' || arrItem.name === 'maxlen' || arrItem.name === 'maxerr') {
						dialog.find('.modal-body input[title="' + arrItem.name + '"]').val(arrItem.value);
					}
				}

                generateDirective();
            }
        }

		promise = Dialogs.showModalDialogUsingTemplate(Mustache.render(OptionsTemplate, Strings)).
            done(function (id) {
				// if button OK clicked...
                if (id === Dialogs.DIALOG_BTN_OK) {
					if (opts.length >= 1) {
						insertDirectiveToEditor();
                        dialog.off('click');
					}
                }

                // if button CANCEL clicked...
                if (id === Dialogs.DIALOG_BTN_CANCEL) {
                    dialog.off('click');
                }
			});

		dialog = $('.georapbox-jslint-settings-dialog.instance');		    // dialog modal
        varEls = dialog.find('.modal-body').find('var');                    // dialog buttons
        varLen = varEls.length;                                             // dialog buttons length
        inputs = dialog.find('.modal-body').find('input[type="number"]');   // dialog inputs
        inputsLen = inputs.length;                                          // inputs length
        result = dialog.find('#georapbox-jsl-conf-result');			        // result placeholder

        getDirectiveFromEditor();

        // Add event handlers.
        dialog.
            on('click', '.modal-body button', function () {
                var varEl = $(this).next();

                toggleCheckbox('input[name="jsonConvert"]', false);

                if (varEl.hasClass('default')) {
                    varEl.removeClass('default').addClass('true').html('true');
                    generateDirective();
                    return;
                }

                if (varEl.hasClass('true')) {
                    varEl.removeClass('true').addClass('false').html('false');
                    generateDirective();
                    return;
                }

                if (varEl.hasClass('false')) {
                    varEl.removeClass('false').addClass('default').html('default');
                    generateDirective();
                    return;
                }
            }).
            on('click', '.modal-body var', function () {
                $(this).prev().click();
            }).
            on('click', '.modal-header a.clear-options', function () {
                clearOptions();
            }).
            on('click', '.modal-footer .select-button', function () {
                result.focus();
                result.select();
            }).
			on('change', '.modal-body input[type="number"]', function () {
                generateDirective();
                toggleCheckbox('input[name="jsonConvert"]', false);
            }).
            on('change', '.modal-footer input[name="jsonConvert"]', function () {
                var insertButton = dialog.find('a[data-button-id="ok"]'),
                    textareaVal = result.val();

                if (textareaVal.trim() !== '') {
                    if ($(this).is(':checked')) {
                        insertButton.attr('disabled', true).prop('disabled', true);
                        generateJsonString();
                    } else {
                        insertButton.attr('disabled', false).prop('disabled', false);
                        generateDirective();
                    }
                }
            });

		return promise;
	}

    exports.showOptionsDialog = showOptionsDialog;
});
<commit_msg>Uncheck checkbox when Clear options is clicked<commit_after>/*global define, $, brackets, Mustache*/
define(function (require, exports, module) {
    'use strict';

    var Dialogs = brackets.getModule('widgets/Dialogs'),
		PreferencesManager = brackets.getModule('preferences/PreferencesManager'),
		ProjectManager = brackets.getModule('project/ProjectManager'),
        EditorManager = brackets.getModule('editor/EditorManager'),
        DocumentManager = brackets.getModule('document/DocumentManager'),
		Strings = brackets.getModule('strings'),
		OptionsTemplate = require('text!options.html');

    /**
	 * Displays dialog with JSLint options.
	*/
    function showOptionsDialog() {
        var currentDoc = DocumentManager.getCurrentDocument(),
            opts = [],
			promise,
            dialog,
            varEls,
            varLen,
            inputs,
            inputsLen,
            result,
            i;

		/**
		 * Clears all dialog's options.
		 */
		function clearOptions() {
			varEls.removeClass('true false').
				addClass('default').
				html('default');                // Reset all var elements.

			inputs.val('');                     // Clear input elements' values.
			result.val('');                     // Clear the directive textarea.
			opts = [];                          // Empty options array.
		}

		/**
		 * Generates JSLint Directive.
		*/
        function generateDirective() {
            var optionName,
                optionValue,
                varElement;

            opts = [];                         // Empty options array.

			// Loop through all var element.
            for (i = 0; i < varLen; i += 1) {
                varElement = varEls[i];

                if (!$(varElement).hasClass('default')) {
                    optionName = $(varElement).parent().attr('title');
                    optionValue = $(varElement).attr('class');

                    opts.push(optionName + ': ' + optionValue);
                }
            }

			// Loop through all input elements.
            for (i = 0; i < inputsLen; i += 1) {
                if ($(inputs[i]).val() !== '') {
                    optionName = $(inputs[i]).attr('title');
                    optionValue = $(inputs[i]).val();

                    opts.push(optionName + ': ' + optionValue);
                }
            }

			if (opts.length >= 1) {											// If options array is NOT empty...
				result.val('/*jslint ' + opts.join(', ') + '*/');			// ...display the options as string in results placeholder.
			} else {														// If options array is empty...
				result.val('');											    // ...empty the results placeholder.
			}
		}

        /**
         * Generates JSON string out of options selected.
         */
        function generateJsonString() {
            var i = 0,
                parsedData = {},
                jsonString,
                val;

            for (i; i < opts.length; i += 1) {
                val = opts[i].substr(opts[i].indexOf(':') + 2);

                if (val === 'true') {
                    parsedData[opts[i].substr(0, opts[i].indexOf(':'))] = true;
                } else if (val === 'false') {
                    parsedData[opts[i].substr(0, opts[i].indexOf(':'))] = false;
                } else if (!isNaN(val)) {
                    parsedData[opts[i].substr(0, opts[i].indexOf(':'))] = +val;
                }
            }

            jsonString = JSON.stringify(parsedData, null, '\t');
            result.val(jsonString);
        }

		/**
		 * Inserts JSLint directive on editor body.
		*/
		function insertDirectiveToEditor() {
			var editor = EditorManager.getCurrentFullEditor(),
				editorDoc = editor.document,
                startPosition = {line: 0, ch: 0},
                firstLineContent = currentDoc.getLine(0);

            editor.setCursorPos(startPosition);                             // Set cursor to line 0 and column 0.
            editorDoc.replaceRange(result.val() + '\n', startPosition);	    // Insert directive at first line and push document one line down.

			// Check if document already has a JSLint directive
			// and remove the line with the old directive.
			if (firstLineContent.indexOf('/*jslint') >= 0) {
				editorDoc.replaceRange('', {line: 1, ch: 0}, {line: 2, ch: 0});
			}
		}

        /**
		 * Inserts JSLint directive on editor body.
		*/
        function toggleCheckbox(checkbox, checked) {
            var jsonInput = dialog.find(checkbox);
            jsonInput.attr('checked', checked);
        }

        /**
         * Gets directive from editor and populates the appropriate options in dialog.
         * Assumes that the directive is on the first line of the document.
         */
        function getDirectiveFromEditor() {
            var firstLineContent = currentDoc.getLine(0),
                tempArr = [],
                arr = [],
                tempArrLen,
                arrLen,
                tempArrItem,
                arrItem,
                subStr,
                option,
                i;

            if (firstLineContent.indexOf('/*jslint') >= 0) {
                subStr = firstLineContent.replace('/*jslint', '');
                subStr = subStr.replace('*/', '');
                tempArr = subStr.split(',');
                tempArr = $.map(tempArr, $.trim);
                tempArrLen = tempArr.length;

                for (i = 0; i < tempArrLen; i += 1) {
                    tempArrItem = tempArr[i];

                    option = {
                        name: tempArrItem.substr(0, tempArrItem.indexOf(':')),
                        value: $.trim(tempArrItem.substr(tempArrItem.indexOf(':')).replace(':', ''))
                    };

                    arr.push(option);
                }

                arrLen = arr.length;

                for (i = 0; i < arrLen; i += 1) {
                    arrItem = arr[i];

					// Update the dialog's options only if the values specified are valid (true or false).
                    if (arrItem.value === 'true' || arrItem.value === 'false') {
						dialog.find('.modal-body div[title="' + arrItem.name + '"] var').
							removeClass('default').
							addClass(arrItem.value).
							html(arrItem.value);
					}

					if (arrItem.name === 'indent' || arrItem.name === 'maxlen' || arrItem.name === 'maxerr') {
						dialog.find('.modal-body input[title="' + arrItem.name + '"]').val(arrItem.value);
					}
				}

                generateDirective();
            }
        }

		promise = Dialogs.showModalDialogUsingTemplate(Mustache.render(OptionsTemplate, Strings)).
            done(function (id) {
				// if button OK clicked...
                if (id === Dialogs.DIALOG_BTN_OK) {
					if (opts.length >= 1) {
						insertDirectiveToEditor();
                        dialog.off('click');
					}
                }

                // if button CANCEL clicked...
                if (id === Dialogs.DIALOG_BTN_CANCEL) {
                    dialog.off('click');
                }
			});

		dialog = $('.georapbox-jslint-settings-dialog.instance');		    // dialog modal
        varEls = dialog.find('.modal-body').find('var');                    // dialog buttons
        varLen = varEls.length;                                             // dialog buttons length
        inputs = dialog.find('.modal-body').find('input[type="number"]');   // dialog inputs
        inputsLen = inputs.length;                                          // inputs length
        result = dialog.find('#georapbox-jsl-conf-result');			        // result placeholder

        getDirectiveFromEditor();

        // Add event handlers.
        dialog.
            on('click', '.modal-body button', function () {
                var varEl = $(this).next();

                toggleCheckbox('input[name="jsonConvert"]', false);

                if (varEl.hasClass('default')) {
                    varEl.removeClass('default').addClass('true').html('true');
                    generateDirective();
                    return;
                }

                if (varEl.hasClass('true')) {
                    varEl.removeClass('true').addClass('false').html('false');
                    generateDirective();
                    return;
                }

                if (varEl.hasClass('false')) {
                    varEl.removeClass('false').addClass('default').html('default');
                    generateDirective();
                    return;
                }
            }).
            on('click', '.modal-body var', function () {
                $(this).prev().click();
            }).
            on('click', '.modal-header a.clear-options', function () {
                clearOptions();
                toggleCheckbox('input[name="jsonConvert"]', false);
            }).
            on('click', '.modal-footer .select-button', function () {
                result.focus();
                result.select();
            }).
			on('change', '.modal-body input[type="number"]', function () {
                generateDirective();
                toggleCheckbox('input[name="jsonConvert"]', false);
            }).
            on('change', '.modal-footer input[name="jsonConvert"]', function () {
                var insertButton = dialog.find('a[data-button-id="ok"]'),
                    textareaVal = result.val();

                if (textareaVal.trim() !== '') {
                    if ($(this).is(':checked')) {
                        insertButton.attr('disabled', true).prop('disabled', true);
                        generateJsonString();
                    } else {
                        insertButton.attr('disabled', false).prop('disabled', false);
                        generateDirective();
                    }
                }
            });

		return promise;
	}

    exports.showOptionsDialog = showOptionsDialog;
});
<|endoftext|>


<commit_before>import Reflux from 'reflux'
import Immutable from 'immutable'

import notificationActions from './notificationActions'

let notificationStore = Reflux.createStore({
	listenables: notificationActions,

	init() {
		this.notifications = Immutable.Map()
		this.errorIndex = 0
	},

	getInitialState() {
		return this.notifications
	},

	_postChange() {
		this.errorIndex += 1
		this.trigger(this.notifications)
	},

	removeNotification(id, delay=0) {
		if (delay) {
			setTimeout(() => {
				// console.log('removeNotification')
				this.notifications = this.notifications.delete(id)
				this._postChange()
			}, delay)
		}
		else {
			// console.log('removeNotification')
			this.notifications = this.notifications.delete(id)
			this._postChange()
		}
	},

	logError(error={}, ...args) {
		// console.log('logError')
		if (!error.quiet)
			console.error(error, ...args)
		let id = this.errorIndex
		let notification = {id, message: error.message, type: 'error'}
		this.notifications = this.notifications.set(id, notification)
		this._postChange()
	},

	logMessage(id, message) {
		// console.log('logMessage')
		let notification = {id, message, type: 'message'}
		this.notifications = this.notifications.set(id, notification)
		this._postChange()
	},

	startProgress(id, message='', progress={}, hideButton=false) {
		// console.log('startProgress')
		let value = progress.value || 0
		let max = progress.max || 1
		let notification = {id, message, value, max, type: 'progress', hideButton}
		this.notifications = this.notifications.set(id, notification)
		this._postChange()
	},

	incrementProgress(id, by) {
		let progress = this.notifications.get(id)
		progress.value += by || 1

		this.notifications = this.notifications.set(id, progress)
		this._postChange()
	},
})

window.notifications = notificationStore

export default notificationStore
<commit_msg>Refuse to increment the progress's value past the max<commit_after>import Reflux from 'reflux'
import Immutable from 'immutable'

import notificationActions from './notificationActions'

let notificationStore = Reflux.createStore({
	listenables: notificationActions,

	init() {
		this.notifications = Immutable.Map()
		this.errorIndex = 0
	},

	getInitialState() {
		return this.notifications
	},

	_postChange() {
		this.errorIndex += 1
		this.trigger(this.notifications)
	},

	removeNotification(id, delay=0) {
		if (delay) {
			setTimeout(() => {
				// console.log('removeNotification')
				this.notifications = this.notifications.delete(id)
				this._postChange()
			}, delay)
		}
		else {
			// console.log('removeNotification')
			this.notifications = this.notifications.delete(id)
			this._postChange()
		}
	},

	logError(error={}, ...args) {
		// console.log('logError')
		if (!error.quiet)
			console.error(error, ...args)
		let id = this.errorIndex
		let notification = {id, message: error.message, type: 'error'}
		this.notifications = this.notifications.set(id, notification)
		this._postChange()
	},

	logMessage(id, message) {
		// console.log('logMessage')
		let notification = {id, message, type: 'message'}
		this.notifications = this.notifications.set(id, notification)
		this._postChange()
	},

	startProgress(id, message='', progress={}, hideButton=false) {
		// console.log('startProgress')
		let value = progress.value || 0
		let max = progress.max || 1
		let notification = {id, message, value, max, type: 'progress', hideButton}
		this.notifications = this.notifications.set(id, notification)
		this._postChange()
	},

	incrementProgress(id, by) {
		let progress = this.notifications.get(id)
		progress.value += by || 1
		progress.value = progress.value <= progress.max ? progress.value : progress.max

		this.notifications = this.notifications.set(id, progress)
		this._postChange()
	},
})

window.notifications = notificationStore

export default notificationStore
<|endoftext|>


<commit_before>/*
 * Copyright (c) Novedia Group 2012.
 *
 *     This file is part of Hubiquitus.
 *
 *     Hubiquitus is free software: you can redistribute it and/or modify
 *     it under the terms of the GNU General Public License as published by
 *     the Free Software Foundation, either version 3 of the License, or
 *     (at your option) any later version.
 *
 *     Hubiquitus is distributed in the hope that it will be useful,
 *     but WITHOUT ANY WARRANTY; without even the implied warranty of
 *     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *     GNU General Public License for more details.
 *
 *     You should have received a copy of the GNU General Public License
 *     along with Hubiquitus.  If not, see <http://www.gnu.org/licenses/>.
 */

var log = require('winston');

var xmpp = require('../server_connectors/xmpp_client.js');
var CommandController = require('../hcommand_controller.js').Controller;
var errors = require('../codes.js').errors;
var status = require('../codes.js').statuses;
var clients = {};
var options;

/**
 * Runs a SocketIO Connector with the given arguments.
 * @param args - {
 *     logLevel : DEBUG, INFO, WARN or ERROR
 *     port : int
 *     namespace : string
 *     discTimeout : int (Time to wait before disconnecting client)
 *     ridWindow : int (Accepted RIDs when reattaching),
 *     commandOptions : {} Command Controller Options
 * }
 */
exports.run = function(args){
    options = args;
    var io = require('socket.io').listen(options.port); //Creates the HTTP server

    var logLevels = { DEBUG: 3, INFO: 2, WARN: 1, ERROR: 0 };
    io.set('log level', logLevels[options.logLevel]);

    //If an hResult is received from the parent, pass it to the correct client
    process.on('message', function(res){
        if(res && res.args && res.args.to && clients[res.args.to])
            clients[res.args.to].socket.emit('hResult', res.hResult);
    });

    var channel = io
        .of(options.namespace)
        .on('connection', function (socket) {
            var id = socket.id;
            clients[id] = {
                id : id,
                rid: Math.floor(Math.random()*100000001),
                socket : socket
            };
            socket.on('hConnect', function(data){ connect(clients[id], data); });
            socket.on('attach', function(data){ attach(clients[id], data); });
            socket.once('disconnect', function(){ disconnect(clients[id]); });
        });
};

/**
 * @param client - Reference to the client
 * @param data - Expected {jid, password, (host), (port)}
 */
function connect(client, data){
    if(!client){
        log.warn('A client sent an invalid ID with data', data);
        return;
    }

    log.info("Client ID " + client.id +  " sent connection data", data);

    if(!data || !data.publisher || !data.password){
        log.info("Client ID " + client.id +  " is trying to connect without mandatory attribute", data);
        return;
    }

    client.xmppConnector = new xmpp.XMPPConnector(data);

    //Relay all server status messages
    client.xmppConnector.on('hStatus', function(msg){
        client.socket.emit('hStatus', msg);
    });

    client.xmppConnector.on('connection', function(attrs){
        //Store our jid and send attrs to client
        client.publisher = attrs.publisher;
        client.domain = attrs.domain;
        client.socket.emit('attrs', {
            publisher: attrs.publisher,
            rid: client.rid,
            sid: client.id});

        //Start the command controller
        var cmdOptions = options.commandOptions;
        cmdOptions.jid = client.publisher;
        client.cmdController = new CommandController(cmdOptions);

        //Start listening for client actions
        addSocketListeners(client);

        //Start listening for messages from XMPP and relaying them
        client.xmppConnector.on('hMessage', function(hMessage){
            log.info("Sent message to client " + client.id, hMessage);
            client.socket.emit('hMessage', hMessage);
            client.rid++;
        });

        client.xmppConnector.on('hResult', function(hResult){
            log.info("Sent message to client " + client.id, hResult);
            client.socket.emit('hResult', hResult);
            client.rid++;
        });
    });

    //Connect to XMPP Server
    client.xmppConnector.establishConnection();

    //Login to XMPP Server
    client.xmppConnector.connect();
}

function addSocketListeners(client){
    client.socket.on('hCommand', function(hCommand) {
        log.info('Client ID ' + client.id + ' sent hCommand', hCommand);

        if(hCommand && hCommand.entity == 'hnode.' + client.domain)
            client.cmdController.execCommand(hCommand, function(hResult){
                log.info("Sent message to client " + client.id, hResult);
                client.socket.emit('hResult', hResult);
                client.rid++;
            });

        else if(hCommand)
            client.xmppConnector.hCommand(hCommand);
    });
}

/**
 *
 * @param client - Reference to the client
 * @param data - expected {sid, rid, publisher}
 */
function attach(client, data){
    if(!client){
        log.warn('A client sent an invalid ID with data', data);
        return;
    }

    log.info("Client ID " + client.id +  " sent reattach data", data);
    /*
     To do an attach, we first confirm if the client is well authenticated,
     then we need to change the reference in the old client and delete it.
     */

    /*Check authentication
     Authentication consists of verifying
     1. if the SID given is valid (corresponds to an active user)
     2. if the RID is in a valid RID window
     3. if the publisher corresponds to that of the identified client
     */
    var ridWindow = options.ridWindow;
    var supposedClient = clients[data.sid];

    if( supposedClient &&
        data.sid !== client.id &&
        data.rid <= supposedClient.rid + ridWindow&&
        data.rid >= supposedClient.rid - ridWindow &&
        data.publisher === supposedClient.publisher
        ){
        //Attached successfully
        clearTimeout(supposedClient.discTimeout);
        supposedClient.socket.emit('disconnect');

        supposedClient.socket = client.socket;
        addSocketListeners(supposedClient);
        supposedClient.socket.emit('hStatus', {status: status.REATTACHED, errorCode: errors.NO_ERROR});
        //Send the attrs for next attachment
        supposedClient.socket.emit('attrs', {
            publisher: supposedClient.publisher,
            rid: supposedClient.rid,
            sid: supposedClient.id});

        delete clients[client.id];
        delete supposedClient.discTimeout;
        log.info('Client ID ' + supposedClient.id  + ' has attached');
    }
    else{
        //Wrong authentication, send error
        log.info('Client ID ' + client.id  + ' tried to attach but failed');
        client.socket.emit('hStatus', {status: status.CONNECTING, errorCode: errors.ATTACH_FAILED});
    }
}

/**
 * Disconnects the current session and socket. The socket is closed but not
 * the XMPP Connection (for reattaching). It will be closed after timeout.
 * @param client - Reference to the client to close
 */
function disconnect(client){
    if (client && client.xmppConnector){
        log.info('Activating timeout for Client ' + client.id);
        var timeout = options.discTimeout;
        client.discTimeout = setTimeout(function(){
            log.info('Disconnecting Client ' + client.id);
            client.xmppConnector.disconnect();
            delete clients[client.id];
        }, timeout);
    }
    else if (client){
        delete clients[client.id];
    }
}<commit_msg>Changed passthrough to be client connection complient<commit_after>/*
 * Copyright (c) Novedia Group 2012.
 *
 *     This file is part of Hubiquitus.
 *
 *     Hubiquitus is free software: you can redistribute it and/or modify
 *     it under the terms of the GNU General Public License as published by
 *     the Free Software Foundation, either version 3 of the License, or
 *     (at your option) any later version.
 *
 *     Hubiquitus is distributed in the hope that it will be useful,
 *     but WITHOUT ANY WARRANTY; without even the implied warranty of
 *     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *     GNU General Public License for more details.
 *
 *     You should have received a copy of the GNU General Public License
 *     along with Hubiquitus.  If not, see <http://www.gnu.org/licenses/>.
 */

var log = require('winston');

var xmpp = require('../server_connectors/xmpp_client.js');
var CommandController = require('../hcommand_controller.js').Controller;
var errors = require('../codes.js').errors;
var status = require('../codes.js').statuses;
var clients = {};
var options;

/**
 * Runs a SocketIO Connector with the given arguments.
 * @param args - {
 *     logLevel : DEBUG, INFO, WARN or ERROR
 *     port : int
 *     namespace : string
 *     discTimeout : int (Time to wait before disconnecting client)
 *     ridWindow : int (Accepted RIDs when reattaching),
 *     commandOptions : {} Command Controller Options
 * }
 */
exports.run = function(args){
    options = args;
    var io = require('socket.io').listen(options.port); //Creates the HTTP server

    var logLevels = { DEBUG: 3, INFO: 2, WARN: 1, ERROR: 0 };
    io.set('log level', logLevels[options.logLevel]);

    //If an hResult is received from the parent, pass it to the correct client
    process.on('message', function(res){
        if(res && res.args && res.args.to && clients[res.args.to])
            clients[res.args.to].socket.emit('hResult', res.hResult);
    });

    var channel = io
        .of(options.namespace)
        .on('connection', function (socket) {
            var id = socket.id;
            clients[id] = {
                id : id,
                rid: Math.floor(Math.random()*100000001),
                socket : socket
            };
            socket.on('hConnect', function(data){ connect(clients[id], data); });
            socket.on('attach', function(data){ attach(clients[id], data); });
            socket.once('disconnect', function(){ disconnect(clients[id]); });
        });
};

/**
 * @param client - Reference to the client
 * @param data - Expected {jid, password, (host), (port)}
 */
function connect(client, data){
    if(!client){
        log.warn('A client sent an invalid ID with data', data);
        return;
    }

    log.info("Client ID " + client.id +  " sent connection data", data);

    if(!data || !data.publisher || !data.password){
        log.info("Client ID " + client.id +  " is trying to connect without mandatory attribute", data);
        return;
    }

    client.xmppConnector = new xmpp.XMPPConnector(data);

    //Relay all server status messages
    client.xmppConnector.on('hStatus', function(msg){
        client.socket.emit('hStatus', msg);
    });

    client.xmppConnector.on('connection', function(attrs){
        //Store our jid and send attrs to client
        client.publisher = attrs.publisher;
        client.domain = attrs.domain;
        client.socket.emit('attrs', {
            publisher: attrs.publisher,
            rid: client.rid,
            sid: client.id});

        //Start the command controller
        var cmdOptions = options.commandOptions;
        cmdOptions.jid = client.publisher;
        client.cmdController = new CommandController(cmdOptions);

        //Start listening for client actions
        addSocketListeners(client);

        //Start listening for messages from XMPP and relaying them
        client.xmppConnector.on('hMessage', function(hMessage){
            log.info("Sent message to client " + client.id, hMessage);
            client.socket.emit('hMessage', hMessage);
            client.rid++;
        });

        client.xmppConnector.on('hResult', function(hResult){
            log.info("Sent message to client " + client.id, hResult);
            client.socket.emit('hResult', hResult);
            client.rid++;
        });
    });

    //Connect to XMPP Server
    client.xmppConnector.establishConnection();

    //Login to XMPP Server
    client.xmppConnector.connect();
}

function addSocketListeners(client){
    client.socket.on('hCommand', function(hCommand) {
        log.info('Client ID ' + client.id + ' sent hCommand', hCommand);

        if(hCommand && hCommand.entity == 'hnode@' + client.domain)
            client.cmdController.execCommand(hCommand, function(hResult){
                log.info("Sent message to client " + client.id, hResult);
                client.socket.emit('hResult', hResult);
                client.rid++;
            });

        else if(hCommand)
            client.xmppConnector.hCommand(hCommand);
    });
}

/**
 *
 * @param client - Reference to the client
 * @param data - expected {sid, rid, publisher}
 */
function attach(client, data){
    if(!client){
        log.warn('A client sent an invalid ID with data', data);
        return;
    }

    log.info("Client ID " + client.id +  " sent reattach data", data);
    /*
     To do an attach, we first confirm if the client is well authenticated,
     then we need to change the reference in the old client and delete it.
     */

    /*Check authentication
     Authentication consists of verifying
     1. if the SID given is valid (corresponds to an active user)
     2. if the RID is in a valid RID window
     3. if the publisher corresponds to that of the identified client
     */
    var ridWindow = options.ridWindow;
    var supposedClient = clients[data.sid];

    if( supposedClient &&
        data.sid !== client.id &&
        data.rid <= supposedClient.rid + ridWindow&&
        data.rid >= supposedClient.rid - ridWindow &&
        data.publisher === supposedClient.publisher
        ){
        //Attached successfully
        clearTimeout(supposedClient.discTimeout);
        supposedClient.socket.emit('disconnect');

        supposedClient.socket = client.socket;
        addSocketListeners(supposedClient);
        supposedClient.socket.emit('hStatus', {status: status.REATTACHED, errorCode: errors.NO_ERROR});
        //Send the attrs for next attachment
        supposedClient.socket.emit('attrs', {
            publisher: supposedClient.publisher,
            rid: supposedClient.rid,
            sid: supposedClient.id});

        delete clients[client.id];
        delete supposedClient.discTimeout;
        log.info('Client ID ' + supposedClient.id  + ' has attached');
    }
    else{
        //Wrong authentication, send error
        log.info('Client ID ' + client.id  + ' tried to attach but failed');
        client.socket.emit('hStatus', {status: status.CONNECTING, errorCode: errors.ATTACH_FAILED});
    }
}

/**
 * Disconnects the current session and socket. The socket is closed but not
 * the XMPP Connection (for reattaching). It will be closed after timeout.
 * @param client - Reference to the client to close
 */
function disconnect(client){
    if (client && client.xmppConnector){
        log.info('Activating timeout for Client ' + client.id);
        var timeout = options.discTimeout;
        client.discTimeout = setTimeout(function(){
            log.info('Disconnecting Client ' + client.id);
            client.xmppConnector.disconnect();
            delete clients[client.id];
        }, timeout);
    }
    else if (client){
        delete clients[client.id];
    }
}<|endoftext|>


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

var sys = require("sys");
var fs = require("fs");
var parser = require("./jsonlint").parser;
var options = require("nomnom")
  .scriptName("jsonlint")
  .opts({
    file: {
      position: 0,
      help: "file to parse; otherwise uses stdin"
    },
    version: {
      string: '-v, --version',
      help: 'print version and exit',
      callback: function() {
        return JSON.parse(fs.readFileSync(__dirname + "/../package.json", "utf8")).version;
      }
    },
    inplace : {
      string: '-i, --in-place',
      help: 'overwrite the file'
    },
    indent : {
      string: '-t CHAR, --indent CHAR',
      default: "  ",
      help: 'character(s) to use for indentation'
    }
  })
  .parseArgs();

function parse (source) {
  try {
    return JSON.stringify(parser.parse(source),null,options.indent);
  } catch (e) {
    sys.puts(e);
    process.exit(1);
  }
}

function main (args) {
  var source = '';
  if (options.file) {
    var path = require('path').join(process.cwd(), options.file);
    source = fs.readFileSync(path, "utf8");
    if (options.inplace) {
      fs.writeSync(fs.openSync(path,'w+'), parse(source), 0, "utf8");
    } else {
      sys.pupts(parse(source));
    }
  } else {
    var stdin = process.openStdin();
    stdin.setEncoding('utf8');

    stdin.on('data', function (chunk) {
      source += chunk.toString('utf8');
    });
    stdin.on('end', function () {
      sys.puts(parse(source));
    });
  }
}

main(process.argv.slice(1));
<commit_msg>add option to sort object keys<commit_after>#!/usr/bin/env node

var sys = require("sys");
var fs = require("fs");
var parser = require("./jsonlint").parser;
var options = require("nomnom")
  .scriptName("jsonlint")
  .opts({
    file: {
      position: 0,
      help: "file to parse; otherwise uses stdin"
    },
    version: {
      string: '-v, --version',
      help: 'print version and exit',
      callback: function() {
        return JSON.parse(fs.readFileSync(__dirname + "/../package.json", "utf8")).version;
      }
    },
    sort : {
      string: '-s, --sort-keys',
      help: 'sort object keys'
    },
    inplace : {
      string: '-i, --in-place',
      help: 'overwrite the file'
    },
    indent : {
      string: '-t CHAR, --indent CHAR',
      default: "  ",
      help: 'character(s) to use for indentation'
    }
  })
  .parseArgs();

function parse (source) {
  try {
    var parsed = options.sort ?
                    sortObject(parser.parse(source)) :
                    parser.parse(source);
    return JSON.stringify(parsed,null,options.indent);
  } catch (e) {
    sys.puts(e);
    process.exit(1);
  }
}

function main (args) {
  var source = '';
  if (options.file) {
    var path = require('path').join(process.cwd(), options.file);
    source = fs.readFileSync(path, "utf8");
    if (options.inplace) {
      fs.writeSync(fs.openSync(path,'w+'), parse(source), 0, "utf8");
    } else {
      sys.puts(parse(source));
    }
  } else {
    var stdin = process.openStdin();
    stdin.setEncoding('utf8');

    stdin.on('data', function (chunk) {
      source += chunk.toString('utf8');
    });
    stdin.on('end', function () {
      sys.puts(parse(source));
    });
  }
}

// from http://stackoverflow.com/questions/1359761/sorting-a-json-object-in-javascript
function sortObject(o) {
  if (Object.prototype.toString.call(o) != '[object Object]')
    return o;
  var sorted = {},
  key, a = [];

  for (key in o) {
    if (o.hasOwnProperty(key)) {
      a.push(key);
    }
  }

  a.sort();

  for (key = 0; key < a.length; key++) {
    sorted[a[key]] = sortObject(o[a[key]]);
  }
  return sorted;
}

main(process.argv.slice(1));
<|endoftext|>


<commit_before>'use strict';

var async = require("async");
var RequestPromise = require("request-promise");
var Promise = require("bluebird");
var itemModel = require('./../models/itemModel');

var eveItemCrestEndpoint = 'https://crest-tq.eveonline.com/inventory/types/';

//ORE : 1
var oreIds = [

    '22' ,    // Arkonor
    '17425',  // Crimson Arkonor
    '17426',  // Prime Arkonor
    '1223',   // Bistot
    '17428',  // Triclinic Bistot
    '17429',  // Monoclinic Bistot
    '1225',   // Crokite
    '17432',  // Sharp Crokite
    '17433',  // Crystalline Crokite
    '1232',   // Dark Ochre
    '17436',  // Onyx Ochre
    '17437',  // Obsidian Ochre
    '21',     // Hedbergite
    '17440',  // Vitric Hedbergite
    '17441',  // Glazed Hedbergite
    '1231',   // Hemorphite
    '17444',  // Vivid Hemorphite
    '17445',  // Radiant Hemorphite
    '1226',   // Jaspet
    '17448',  // Pure Jaspet
    '17449',  // Pristine Jaspet
    '20',     // Kernite
    '17452',  // Luminous Kernite
    '17453',  // Fiery Kernite
    '18',     // Plagioclase
    '17455',  // Azure Plagioclase
    '17456',  // Rich Plagioclase
    '1224',   // Pyroxeres
    '17459',  // Solid Pyroxeres
    '17460',  // Viscous Pyroxeres
    '1228',   // Scordite
    '17463',  // Condensed Scordite
    '17464',  // Massive Scordite
    '19',     // Spodumain
    '17466',  // Bright Spodumain
    '17467',  // Gleaming Spodumain
    '1230',   // Veldspar
    '17470',  // Concentrated Veldspar
    '17471',  // Dense Veldspar
    '1229',   // Gneiss
    '17865',  // Iridescent Gneiss
    '17866',  // Prismatic Gneiss
    '11396',  // Mercoxit
    '17869',  // Magma Mercoxit
    '17870',  // Vitreous Mercoxit
    '1227',   // Omber
    '17867',  // Silvery Omber
    '17868'  // Golden Omber
];
//ICE - 2
var iceIds = [
    '16262', //   Clear Icicle
    '17978', //   Enriched Clear Icicle
    '16263', //   Glacial Mass
    '17977', //   Smooth Glacial Mass
    '16264', //   Blue Ice
    '17975', //   Thick Blue Ice
    '16265', //   White Glaze
    '17976', //   Pristine White Glaze
    '16266', //   Glare Crust
    '16267'  //   Dark Glitter
];

//TODO: Reduce Redundancy
exports.updateOreData = function updateOreData(req, res) {
    var items = [];
    var allPromises = [];
    for(var oreId in oreIds) {
        var options = {
            uri: eveItemCrestEndpoint + oreIds[oreId] +'/',
            json: true
        };
        allPromises.push(RequestPromise(options));
    }
    Promise.all(allPromises).then(function (responseItems){
        for(var item in responseItems){
            var newItem = new itemModel({
                _id : responseItems[item].id,
                name: responseItems[item].name,
                description: responseItems[item].description,
                itemType: 1,
                volume: responseItems[item].volume,
                imgUrlLrg: 'https://imageserver.eveonline.com/Type/'+responseItems[item].id+'_64.png',
                imgUrlSml: 'https://imageserver.eveonline.com/Type/'+responseItems[item].id+'_32.png'
            });
            newItem.save();
            items.push(newItem);
        }
        res.json(items);
    }).catch(function(err){
        console.log(err);
    });
};

exports.updateIceData = function updateIceData(req, res) {
    var items = [];
    var allPromises = [];
    for(var iceId in iceIds) {
        var options = {
            uri: eveItemCrestEndpoint + iceIds[iceId] +'/',
            json: true
        };
        allPromises.push(RequestPromise(options));
    }
    Promise.all(allPromises).then(function (responseItems){
        for(var item in responseItems){
            var newItem = new itemModel({
                _id : responseItems[item].id,
                name: responseItems[item].name,
                description: responseItems[item].description,
                itemType: 2,
                volume: responseItems[item].volume,
                imgUrlLrg: 'https://imageserver.eveonline.com/Type/'+responseItems[item].id+'_64.png',
                imgUrlSml: 'https://imageserver.eveonline.com/Type/'+responseItems[item].id+'_32.png'
            });
            newItem.save();
            items.push(newItem);
        }
        res.json(items);
    }).catch(function(err){
        console.log(err);
    });
};

<commit_msg>clean up item ctrl<commit_after>'use strict';

var async = require("async");
var RequestPromise = require("request-promise");
var Promise = require("bluebird");
var itemModel = require('./../models/itemModel');

var eveItemCrestEndpoint = 'https://crest-tq.eveonline.com/inventory/types/';

//ORE : 1
var oreIds = [

    '22' ,    // Arkonor
    '17425',  // Crimson Arkonor
    '17426',  // Prime Arkonor
    '1223',   // Bistot
    '17428',  // Triclinic Bistot
    '17429',  // Monoclinic Bistot
    '1225',   // Crokite
    '17432',  // Sharp Crokite
    '17433',  // Crystalline Crokite
    '1232',   // Dark Ochre
    '17436',  // Onyx Ochre
    '17437',  // Obsidian Ochre
    '21',     // Hedbergite
    '17440',  // Vitric Hedbergite
    '17441',  // Glazed Hedbergite
    '1231',   // Hemorphite
    '17444',  // Vivid Hemorphite
    '17445',  // Radiant Hemorphite
    '1226',   // Jaspet
    '17448',  // Pure Jaspet
    '17449',  // Pristine Jaspet
    '20',     // Kernite
    '17452',  // Luminous Kernite
    '17453',  // Fiery Kernite
    '18',     // Plagioclase
    '17455',  // Azure Plagioclase
    '17456',  // Rich Plagioclase
    '1224',   // Pyroxeres
    '17459',  // Solid Pyroxeres
    '17460',  // Viscous Pyroxeres
    '1228',   // Scordite
    '17463',  // Condensed Scordite
    '17464',  // Massive Scordite
    '19',     // Spodumain
    '17466',  // Bright Spodumain
    '17467',  // Gleaming Spodumain
    '1230',   // Veldspar
    '17470',  // Concentrated Veldspar
    '17471',  // Dense Veldspar
    '1229',   // Gneiss
    '17865',  // Iridescent Gneiss
    '17866',  // Prismatic Gneiss
    '11396',  // Mercoxit
    '17869',  // Magma Mercoxit
    '17870',  // Vitreous Mercoxit
    '1227',   // Omber
    '17867',  // Silvery Omber
    '17868'  // Golden Omber
];
//ICE - 2
var iceIds = [
    '16262', //   Clear Icicle
    '17978', //   Enriched Clear Icicle
    '16263', //   Glacial Mass
    '17977', //   Smooth Glacial Mass
    '16264', //   Blue Ice
    '17975', //   Thick Blue Ice
    '16265', //   White Glaze
    '17976', //   Pristine White Glaze
    '16266', //   Glare Crust
    '16267'  //   Dark Glitter
];

exports.updateOreData = function updateOreData(req, res) {
    var itemType = 1;
    getItemData(oreIds, itemType).then(function (retrievedItems){
        res.json(retrievedItems);
    }).catch(function (err){
        console.log('An Error Occurred: ', err)
    })
};

exports.updateIceData = function updateIceData(req, res) {
    var itemType = 2;
    getItemData(iceIds, itemType).then(function (retrievedItems){
        res.json(retrievedItems);
    }).catch(function (err){
        console.log('An Error Occurred: ', err)
    })
};

function getItemData(itemIds, itemType){
    var items = [];
    var allPromises = [];
    for (var id in itemIds) {
        if(itemIds.hasOwnProperty(id)){
            var options = {
                uri: eveItemCrestEndpoint + itemIds[id] + '/',
                json: true
            };
            allPromises.push(RequestPromise(options));
        }
    }
    return Promise.all(allPromises).then(function (responseItems) {
        for (var item in responseItems) {
            if(responseItems.hasOwnProperty(item)){
                var newItem = new itemModel({
                    _id : responseItems[item].id,
                    name: responseItems[item].name,
                    description: responseItems[item].description,
                    itemType: itemType,
                    volume: responseItems[item].volume,
                    imgUrlLrg: 'https://imageserver.eveonline.com/Type/'+responseItems[item].id+'_64.png',
                    imgUrlSml: 'https://imageserver.eveonline.com/Type/'+responseItems[item].id+'_32.png'
                });
                newItem.save();
                items.push(newItem);
            }
        }
        return items;
    }).catch(function (err) {
        console.log(err);
    });
}

<|endoftext|>


<commit_before>import Input from '../../mixins/input'

export default {
  name: 'text-field',

  mixins: [Input],

  data () {
    return {
      hasFocused: false,
      inputHeight: null
    }
  },

  computed: {
    classes () {
      return {
        'input-group--text-field': true,
        'input-group--single-line': this.singleLine,
        'input-group--multi-line': this.multiLine,
        'input-group--full-width': this.fullWidth
      }
    },
    hasError () {
      return this.errors.length !== 0 ||
        !this.counterIsValid() ||
        !this.validateIsValid()
    },
    count () {
      const inputLength = (this.inputValue && this.inputValue.toString() || '').length
      let min = inputLength

      if (this.min !== 0 && inputLength < this.min) {
        min = this.min
      }

      return `${min} / ${this.max}`
    },
    inputValue: {
      get () {
        return this.value
      },
      set (val) {
        if (this.modifiers.trim) {
          val = val.trim()
        }

        if (this.modifiers.number) {
          val = Number(val)
        }

        if (!this.modifiers.lazy) {
          this.$emit('input', val)
        }

        this.lazyValue = val
      }
    },
    isDirty () {
      return this.lazyValue !== null &&
        typeof this.lazyValue !== 'undefined' &&
        this.lazyValue.toString().length > 0
    }
  },

  props: {
    autofocus: Boolean,
    autoGrow: Boolean,
    counter: Boolean,
    fullWidth: Boolean,
    min: {
      type: [Number, String],
      default: 0
    },
    max: {
      type: [Number, String],
      default: 25
    },
    multiLine: Boolean,
    singleLine: Boolean,
    type: {
      type: String,
      default: 'text'
    },
    name: String,
    rows: {
      default: 5
    }
  },

  watch: {
    focused () {
      this.hasFocused = true

      if (!this.focused) {
        this.$emit('blur')
        this.$emit('change', this.lazyValue)
      } else {
        this.$emit('focus')
      }
    },
    value () {
      this.lazyValue = this.value
      this.validate()
      this.multiLine && this.autoGrow && this.calculateInputHeight()
    }
  },

  mounted () {
    this.$vuetify.load(() => {
      this.multiLine && this.autoGrow && this.calculateInputHeight()
      this.autofocus && this.$refs.input.focus()
    })
  },

  methods: {
    calculateInputHeight () {
      const height = this.$refs.input.scrollHeight
      const minHeight = this.rows * 24
      this.inputHeight = height < minHeight ? minHeight : height
    },
    onInput (e) {
      this.inputValue = e.target.value
      this.multiLine && this.autoGrow && this.calculateInputHeight()
    },
    blur () {
      this.validate()
      this.$nextTick(() => (this.focused = false))
    },
    genCounter () {
      return this.$createElement('div', {
        'class': {
          'input-group__counter': true,
          'input-group__counter--error': !this.counterIsValid()
        }
      }, this.count)
    },
    genInput () {
      const tag = this.multiLine ? 'textarea' : 'input'

      const inputData = {
        style: {
          'height': this.inputHeight && `${this.inputHeight}px`
        },
        domProps: {
          disabled: this.disabled,
          required: this.required,
          value: this.lazyValue,
          autofucus: this.autofocus
        },
        attrs: {
          tabindex: this.tabindex
        },
        on: {
          blur: this.blur,
          input: this.onInput,
          focus: () => (this.focused = true)
        },
        ref: 'input'
      }

      if (this.autocomplete) inputData.domProps.autocomplete = true

      // add only if set
      if (this.name) {
        inputData.attrs = { name: this.name }
      }

      if (this.multiLine) {
        inputData.domProps.rows = this.rows
      } else {
        inputData.domProps.type = this.type
      }

      return this.$createElement(tag, inputData)
    },
    counterIsValid: function counterIsValid () {
      const val = (this.inputValue && this.inputValue.toString() || '')
      return (!this.counter ||
        !this.inputValue.toString() ||
        (val.length >= this.min && val.length <= this.max)
      )
    },
    validateIsValid () {
      return (!this.required ||
        (this.required &&
          this.inputValue) ||
        !this.hasFocused ||
        (this.hasFocused && this.focused))
    }
  },

  render () {
    return this.genInputGroup(this.genInput(), {
      attrs: {
        tabindex: -1
      }
    })
  }
}
<commit_msg>bug fix for #323<commit_after>import Input from '../../mixins/input'

export default {
  name: 'text-field',

  mixins: [Input],

  data () {
    return {
      hasFocused: false,
      inputHeight: null
    }
  },

  computed: {
    classes () {
      return {
        'input-group--text-field': true,
        'input-group--single-line': this.singleLine,
        'input-group--multi-line': this.multiLine,
        'input-group--full-width': this.fullWidth
      }
    },
    hasError () {
      return this.errors.length !== 0 ||
        !this.counterIsValid() ||
        !this.validateIsValid()
    },
    count () {
      const inputLength = (this.inputValue && this.inputValue.toString() || '').length
      let min = inputLength

      if (this.min !== 0 && inputLength < this.min) {
        min = this.min
      }

      return `${min} / ${this.max}`
    },
    inputValue: {
      get () {
        return this.value
      },
      set (val) {
        if (this.modifiers.trim) {
          val = val.trim()
        }

        if (this.modifiers.number) {
          val = Number(val)
        }

        if (!this.modifiers.lazy) {
          this.$emit('input', val)
        }

        this.lazyValue = val
      }
    },
    isDirty () {
      return this.lazyValue !== null &&
        typeof this.lazyValue !== 'undefined' &&
        this.lazyValue.toString().length > 0
    }
  },

  props: {
    autofocus: Boolean,
    autoGrow: Boolean,
    counter: Boolean,
    fullWidth: Boolean,
    min: {
      type: [Number, String],
      default: 0
    },
    max: {
      type: [Number, String],
      default: 25
    },
    multiLine: Boolean,
    singleLine: Boolean,
    type: {
      type: String,
      default: 'text'
    },
    name: String,
    rows: {
      default: 5
    }
  },

  watch: {
    focused () {
      this.hasFocused = true

      if (!this.focused) {
        this.$emit('blur')
        this.$emit('change', this.lazyValue)
      } else {
        this.$emit('focus')
      }
    },
    value () {
      this.lazyValue = this.value
      this.validate()
      this.multiLine && this.autoGrow && this.calculateInputHeight()
    }
  },

  mounted () {
    this.$vuetify.load(() => {
      this.multiLine && this.autoGrow && this.calculateInputHeight()
      this.autofocus && this.$refs.input.focus()
    })
  },

  methods: {
    calculateInputHeight () {
      const height = this.$refs.input.scrollHeight
      const minHeight = this.rows * 24
      this.inputHeight = height < minHeight ? minHeight : height
    },
    onInput (e) {
      this.inputValue = e.target.value
      this.multiLine && this.autoGrow && this.calculateInputHeight()
    },
    blur () {
      this.validate()
      this.$nextTick(() => (this.focused = false))
    },
    genCounter () {
      return this.$createElement('div', {
        'class': {
          'input-group__counter': true,
          'input-group__counter--error': !this.counterIsValid()
        }
      }, this.count)
    },
    genInput () {
      const tag = this.multiLine ? 'textarea' : 'input'

      const inputData = {
        style: {
          'height': this.inputHeight && `${this.inputHeight}px`
        },
        domProps: {
          disabled: this.disabled,
          required: this.required,
          value: this.lazyValue,
          autofucus: this.autofocus
        },
        attrs: {
          tabindex: this.tabindex
        },
        on: {
          blur: this.blur,
          input: this.onInput,
          focus: () => (this.focused = true)
        },
        ref: 'input'
      }

      if (this.autocomplete) inputData.domProps.autocomplete = true

      // add only if set
      if (this.name) {
        inputData.attrs = { name: this.name }
      }

      if (this.multiLine) {
        inputData.domProps.rows = this.rows
      } else {
        inputData.domProps.type = this.type
      }

      return this.$createElement(tag, inputData)
    },
    counterIsValid: function counterIsValid () {
      const val = (this.inputValue && this.inputValue.toString() || '')
      return (!this.counter ||
        (val.length >= this.min && val.length <= this.max)
      )
    },
    validateIsValid () {
      return (!this.required ||
        (this.required &&
          this.inputValue) ||
        !this.hasFocused ||
        (this.hasFocused && this.focused))
    }
  },

  render () {
    return this.genInputGroup(this.genInput(), {
      attrs: {
        tabindex: -1
      }
    })
  }
}
<|endoftext|>


<commit_before>import {SecurityServiceServer} from "../../server/service/SecurityServiceServer"
import {ServerTaskService} from "../../server/service/ServerTaskService"

/** @class ServerUserService */
export class ServerUserService {

    /**
     * @summary GroupRoles.after.update hook
     * @description
     * If group roles' roles are updated user roles are update as well.
     * @locus server
     * @param userId
     * @param doc
     * @param fieldNames
     * @param modifier
     * @param options
     */
    static propagateGroupRoles(userId, doc, fieldNames, modifier, options) {
        if (_.contains(fieldNames, "roles")) {

            //users having the updated groupRole
            var users = Users.find({groupRoles: doc._id}).fetch();
            users.forEach(user => {
                //update user roles, Account roles will be update by hooks
                var modifier = {
                    $set: {groupRoles: user.groupRoles}
                };
                //will fire the Users after hook and call propagateRoles
                Users.update(user._id, modifier);
            });
        }
    }

    /**
     * @summary Users.after.update hook.
     * @description
     * About roles, we only add roles to the custom Users collection, **not** with the Roles library. This hooks is responsible to propagate roles to the
     * Meteor.users linked account.
     * @locus server
     * @param userId
     * @param doc
     * @param fieldNames
     * @param modifier
     * @param options
     */
    static propagateRoles(userId, doc, fieldNames, modifier, options) {
        if (_.contains(fieldNames, "groupRoles")) {
            if (modifier.$set.groupRoles) {
                //we have to merge roles and roles from groups
                var newGroups = GroupRoles.find({_id: {$in: modifier.$set.groupRoles}}).fetch(); //get all related roles
                var result = []; //reduce to get only the roles array
                newGroups.forEach(group => {
                    result.push(group.roles);
                });
                var allGroupRolesMerged = _.uniq(_.flatten(result)); //obtain a single array
            } else {
                //we have to remove all roles
                var allGroupRolesMerged = [];
            }
            Roles.setUserRoles(doc.loginUserId, allGroupRolesMerged); //add to Account package
        }

    }

    /**
     * @summary  Users.before.insert
     * @description
     * - Collection Hooks :  Users.before.insert
     * - Needed role : USERWRITE
     */
    static allowInsert(userId, doc) {
        SecurityServiceServer.grantAccessToItem(userId, RolesEnum.USERWRITE, doc, 'user');
    }

    /**
     * @summary  Users.before.update
     * @description
     * - Collection Hooks :  Users.before.update
     * - Needed role : USERWRITE
     *    - ROLE
     *    - ASSIGNMENTTASKUSER
     *
     * if userId is the doc being updated, no need of USERWRITE (a user can update itself)
     */
    static allowUpdate(userId, doc, fieldNames, modifier, options) {

        if (userId !== doc.loginUserId)
            SecurityServiceServer.grantAccessToItem(userId, RolesEnum.USERWRITE, doc, 'user');

        if (_.contains(fieldNames, "groupRoles"))
            if (modifier.$set.groupRoles)
                SecurityServiceServer.grantAccessToItem(userId, RolesEnum.ROLE, doc, 'user');

        if (_.contains(fieldNames, "assignments")) {
            if (modifier.$pull)
                if (modifier.$pull.assignments)
                    SecurityServiceServer.grantAccessToItem(userId, RolesEnum.ASSIGNMENTTASKUSER, doc, 'user');
            if (modifier.$set) //TODO a virer
                if (modifier.$set.assignments)
                    SecurityServiceServer.grantAccessToItem(userId, RolesEnum.ASSIGNMENTTASKUSER, doc, 'user');
            if (modifier.$push)
                if (modifier.$push.assignments)
                    SecurityServiceServer.grantAccessToItem(userId, RolesEnum.ASSIGNMENTTASKUSER, doc, 'user');
        }

    }

    /**
     * @summary  Users.before.remove
     * @description
     * - Collection Hooks :  Users.before.remove
     * - Needed role : USERDELETE
     */
    static allowDelete(userId, doc) {
        SecurityServiceServer.grantAccessToItem(userId, RolesEnum.USERDELETE, doc, 'task');
    }

}<commit_msg>[RPI] feature (superadmin) : superadmin user cannot be deleted nor updated<commit_after>import {SecurityServiceServer} from "../../server/service/SecurityServiceServer"
import {ServerTaskService} from "../../server/service/ServerTaskService"

/** @class ServerUserService */
export class ServerUserService {

    /**
     * @summary GroupRoles.after.update hook
     * @description
     * If group roles' roles are updated user roles are update as well.
     * @locus server
     * @param userId
     * @param doc
     * @param fieldNames
     * @param modifier
     * @param options
     */
    static propagateGroupRoles(userId, doc, fieldNames, modifier, options) {
        if (_.contains(fieldNames, "roles")) {

            //users having the updated groupRole
            var users = Users.find({groupRoles: doc._id}).fetch();
            users.forEach(user => {
                //update user roles, Account roles will be update by hooks
                var modifier = {
                    $set: {groupRoles: user.groupRoles}
                };
                //will fire the Users after hook and call propagateRoles
                Users.update(user._id, modifier);
            });
        }
    }

    /**
     * @summary Users.after.update hook.
     * @description
     * About roles, we only add roles to the custom Users collection, **not** with the Roles library. This hooks is responsible to propagate roles to the
     * Meteor.users linked account.
     * @locus server
     * @param userId
     * @param doc
     * @param fieldNames
     * @param modifier
     * @param options
     */
    static propagateRoles(userId, doc, fieldNames, modifier, options) {
        if (_.contains(fieldNames, "groupRoles")) {
            if (modifier.$set.groupRoles) {
                //we have to merge roles and roles from groups
                var newGroups = GroupRoles.find({_id: {$in: modifier.$set.groupRoles}}).fetch(); //get all related roles
                var result = []; //reduce to get only the roles array
                newGroups.forEach(group => {
                    result.push(group.roles);
                });
                var allGroupRolesMerged = _.uniq(_.flatten(result)); //obtain a single array
            } else {
                //we have to remove all roles
                var allGroupRolesMerged = [];
            }
            Roles.setUserRoles(doc.loginUserId, allGroupRolesMerged); //add to Account package
        }

    }

    /**
     * @summary  Users.before.insert
     * @description
     * - Collection Hooks :  Users.before.insert
     * - Needed role : USERWRITE
     */
    static allowInsert(userId, doc) {
        SecurityServiceServer.grantAccessToItem(userId, RolesEnum.USERWRITE, doc, 'user');
    }

    /**
     * @summary  Users.before.update
     * @description
     * - Collection Hooks :  Users.before.update
     * - Needed role : USERWRITE
     *    - ROLE
     *    - ASSIGNMENTTASKUSER
     *
     * if userId is the doc being updated, no need of USERWRITE (a user can update itself)
     */
    static allowUpdate(userId, doc, fieldNames, modifier, options) {

        if (userId !== doc.loginUserId)
            SecurityServiceServer.grantAccessToItem(userId, RolesEnum.USERWRITE, doc, 'user');

        if (_.contains(fieldNames, "groupRoles"))
            if (modifier.$set.groupRoles)
                SecurityServiceServer.grantAccessToItem(userId, RolesEnum.ROLE, doc, 'user');

        if (_.contains(fieldNames, "assignments")) {
            if (modifier.$pull)
                if (modifier.$pull.assignments)
                    SecurityServiceServer.grantAccessToItem(userId, RolesEnum.ASSIGNMENTTASKUSER, doc, 'user');
            if (modifier.$set) //TODO a virer
                if (modifier.$set.assignments)
                    SecurityServiceServer.grantAccessToItem(userId, RolesEnum.ASSIGNMENTTASKUSER, doc, 'user');
            if (modifier.$push)
                if (modifier.$push.assignments)
                    SecurityServiceServer.grantAccessToItem(userId, RolesEnum.ASSIGNMENTTASKUSER, doc, 'user');
        }

        if(Users.findOne(doc._id).name === SUPERADMIN){
            throw new Meteor.Error("403","User superadmin can not be updated");
        }
    }

    /**
     * @summary  Users.before.remove
     * @description
     * - Collection Hooks :  Users.before.remove
     * - Needed role : USERDELETE
     */
    static allowDelete(userId, doc) {
        SecurityServiceServer.grantAccessToItem(userId, RolesEnum.USERDELETE, doc, 'task');

        if(Users.findOne(doc._id).name === SUPERADMIN){
            throw new Meteor.Error("403","User superadmin can not be deleted");
        }
    }

}<|endoftext|>


<commit_before>import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import ReactModal from 'react-modal';
import RaisedButton from 'material-ui/RaisedButton';

// Grid imports
import {GridList, GridTile} from 'material-ui/GridList';
import Subheader from 'material-ui/Subheader';
import StarBorder from 'material-ui/svg-icons/toggle/star-border';

// NavBar imports
import AppBar from 'material-ui/AppBar';
import IconButton from 'material-ui/IconButton';
import NavigationClose from 'material-ui/svg-icons/navigation/close';
import Link from 'material-ui/svg-icons/content/link';

import Tabs from 'react-simpletabs';
import FloatingActionButton from 'material-ui/FloatingActionButton';

// BottomNavigation imports
import FontIcon from 'material-ui/FontIcon';
import Paper from 'material-ui/Paper';
import {BottomNavigation, BottomNavigationItem} from 'material-ui/BottomNavigation';
import IconLocationOn from 'material-ui/svg-icons/communication/location-on';

const recentsIcon = <FontIcon className="material-icons">restore</FontIcon>;
const favoritesIcon = <FontIcon className="material-icons">favorite</FontIcon>;
const nearbyIcon = <IconLocationOn />;
const linkIcon = <NavigationClose color="#008AFF" />;//<Link color="black" hoverColor="#008AFF"/>;
const closeIcon = <NavigationClose color="#008AFF" />;

const styles = {
  root: {
    display: 'flex',
    flexWrap: 'wrap',
    justifyContent: 'space-around',
    alignItems: 'flex-start'
  },
  gridList: {
    width: 450,
    height: 450,
    overflowY: 'auto',
  },
};

class MyAwesomeReactComponent extends Component {
  constructor(props) {
    super(props);

    this.state = {
      selectedIndex: 0
    }

    // this.projectTitle = this.props.projectTitle;
    this.handleDrawerToggle = this.handleDrawerToggle.bind(this);
    this.handleCloseModal = this.handleCloseModal.bind(this);
  }

  handleDrawerToggle() {
    this.props.toggleDrawer();
  }

  select = (index) => this.setState({selectedIndex: index});

  handleCloseModal () {
    this.props.closeModal();
  }

  componentDidMount() {

  }

  render() {
    var link;
    if (this.props.projectContent.link) {
        link = (
          <FloatingActionButton
            className='linkButton'
            href={this.props.projectContent.link}
            mini={true} backgroundColor="#008AFF"
            target='_blank'>
            <Link />
          </FloatingActionButton>
        );
      }

    return (

        <AppBar
          title={this.props.projectTitle}
          className="modalNavBar"
          // iconClassNameRight="muidocs-icon-navigation-expand-more"
          onLeftIconButtonTouchTap={this.handleDrawerToggle}
          iconElementRight={<IconButton onClick={this.handleCloseModal}><NavigationClose /></IconButton>}
        >

        </AppBar>

          {/* Text */}

                  {this.props.projectContent.client}
                  {this.props.projectContent.course}

                  {link}

                  { this.props.projectContent.text }

          {/* Pictures */}

            <Tabs>
              {
                this.props.projectContent.categories.map((category) =>
                <Tabs.Panel
                  key={category}
                  title={category}
                  >

                    <GridList
                      cols={2}
                      cellHeight={category==='mobile' ? 200 : 225}
                      padding={1}
                      style={styles.gridList}
                    >
                      {
                        this.props.projectContent.pictures.filter(function(picture) {
                            return category===picture.category;
                          }).map((picture) =>
                        <GridTile
                          key={picture.src}
                          title={picture.title}
                          actionPosition="left"
                          titlePosition="top"
                          titleBackground="linear-gradient(to bottom, rgba(0,0,0,0.7) 0%,rgba(0,0,0,0.3) 70%,rgba(0,0,0,0) 100%)"
                          cols={category==='mobile' ? 1 : 2}
                          rows={category==='mobile' ? 2 : 1}
                        >
                          <img src={require(`${picture.src}`)} alt="picture" />
                        </GridTile>
                        )
                      }
                    </GridList>

                </Tabs.Panel>
              )
            }
            </Tabs>

          {/* <RaisedButton backgroundColor="#008AFF" label="Close" onClick={this.handleCloseModal} /> */}

          <Paper zDepth={1}>
            <BottomNavigation selectedIndex={this.state.selectedIndex}>
              <BottomNavigationItem
                icon={closeIcon}
                onClick={() => this.handleCloseModal()}
              />
            </BottomNavigation>
          </Paper>

    );
  }
}

export default MyAwesomeReactComponent;
<commit_msg>done trying with fade. It is fine right now<commit_after>import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import ReactModal from 'react-modal';
import RaisedButton from 'material-ui/RaisedButton';

// Grid imports
import {GridList, GridTile} from 'material-ui/GridList';
import Subheader from 'material-ui/Subheader';
import StarBorder from 'material-ui/svg-icons/toggle/star-border';

// NavBar imports
import AppBar from 'material-ui/AppBar';
import IconButton from 'material-ui/IconButton';
import NavigationClose from 'material-ui/svg-icons/navigation/close';
import Link from 'material-ui/svg-icons/content/link';

import Tabs from 'react-simpletabs';
import FloatingActionButton from 'material-ui/FloatingActionButton';

// BottomNavigation imports
import FontIcon from 'material-ui/FontIcon';
import Paper from 'material-ui/Paper';
import {BottomNavigation, BottomNavigationItem} from 'material-ui/BottomNavigation';
import IconLocationOn from 'material-ui/svg-icons/communication/location-on';

const recentsIcon = <FontIcon className="material-icons">restore</FontIcon>;
const favoritesIcon = <FontIcon className="material-icons">favorite</FontIcon>;
const nearbyIcon = <IconLocationOn />;
const linkIcon = <NavigationClose color="#008AFF" />;//<Link color="black" hoverColor="#008AFF"/>;
const closeIcon = <NavigationClose color="#008AFF" />;

const styles = {
  root: {
    display: 'flex',
    flexWrap: 'wrap',
    justifyContent: 'space-around',
    alignItems: 'flex-start'
  },
  gridList: {
    width: 450,
    height: 450,
    overflowY: 'auto',
  },
};

class MyAwesomeReactComponent extends Component {
  constructor(props) {
    super(props);

    this.state = {
      selectedIndex: 0
    }

    // this.projectTitle = this.props.projectTitle;
    this.handleDrawerToggle = this.handleDrawerToggle.bind(this);
    this.handleCloseModal = this.handleCloseModal.bind(this);
  }

  handleDrawerToggle() {
    this.props.toggleDrawer();
  }

  select = (index) => this.setState({selectedIndex: index});

  handleCloseModal () {
    this.props.closeModal();
  }

  render() {
    var link;
    if (this.props.projectContent.link) {
        link = (
          <FloatingActionButton
            className='linkButton'
            href={this.props.projectContent.link}
            mini={true} backgroundColor="#008AFF"
            target='_blank'>
            <Link />
          </FloatingActionButton>
        );
      }

    return (

        <AppBar
          title={this.props.projectTitle}
          className="modalNavBar"
          // iconClassNameRight="muidocs-icon-navigation-expand-more"
          onLeftIconButtonTouchTap={this.handleDrawerToggle}
          iconElementRight={<IconButton onClick={this.handleCloseModal}><NavigationClose /></IconButton>}
        >

        </AppBar>

          {/* Text */}

                  {this.props.projectContent.client}
                  {this.props.projectContent.course}

                  {link}

                  { this.props.projectContent.text }

          {/* Pictures */}

            <Tabs>
              {
                this.props.projectContent.categories.map((category) =>
                <Tabs.Panel
                  key={category}
                  title={category}
                  >

                    <GridList
                      cols={2}
                      cellHeight={category==='mobile' ? 200 : 225}
                      padding={1}
                      style={styles.gridList}
                    >
                      {
                        this.props.projectContent.pictures.filter(function(picture) {
                            return category===picture.category;
                          }).map((picture) =>
                        <GridTile
                          key={picture.src}
                          title={picture.title}
                          actionPosition="left"
                          titlePosition="top"
                          titleBackground="linear-gradient(to bottom, rgba(0,0,0,0.7) 0%,rgba(0,0,0,0.3) 70%,rgba(0,0,0,0) 100%)"
                          cols={category==='mobile' ? 1 : 2}
                          rows={category==='mobile' ? 2 : 1}
                        >
                          <img src={require(`${picture.src}`)} alt="picture" />
                        </GridTile>
                        )
                      }
                    </GridList>

                </Tabs.Panel>
              )
            }
            </Tabs>

          {/* <RaisedButton backgroundColor="#008AFF" label="Close" onClick={this.handleCloseModal} /> */}

          <Paper zDepth={1}>
            <BottomNavigation selectedIndex={this.state.selectedIndex}>
              <BottomNavigationItem
                icon={closeIcon}
                onClick={() => this.handleCloseModal()}
              />
            </BottomNavigation>
          </Paper>

    );
  }
}

export default MyAwesomeReactComponent;
<|endoftext|>


<commit_before>"use strict";

exports.log = log;
exports.request = request;

function log(...args) {
    const now = new Date().toLocaleString("en-US", {
        month: "short",
        day: "2-digit",
        hour12: false,
        hour: "2-digit",
        minute: "2-digit",
        second: "2-digit"
    });

    console.log(now, ...args); /* eslint no-console:off */
}

const urlParse = require("url").parse;
const https = require("https");
const querystring = require("querystring");
const EventEmitter = require("events");
const HttpsProxyAgent = require("https-proxy-agent");

function request({
    url = "",
    method = "GET",
    headers = {},
    body = null,
    qs = {}
} = {}, callback) {
    const ee = new EventEmitter();
    const reqUrl = urlParse(url);
    const host = reqUrl.hostname;
    const port = reqUrl.port || 443;

    let path = reqUrl.path;

    if (method === "GET") {
        path += `?${querystring.stringify(qs)}`;
    }

    if (body) {
        headers["Content-Type"] = "application/json";
        headers["Content-Length"] = JSON.stringify(body).length;
    }

    const requestOptions = {
        host,
        port,
        path,
        method,
        headers
    };

    function requestResponse(res) {
        ee.emit("response");

        res.setEncoding("utf8");

        let rawData = "";

        res.on("data", chunk => {
            ee.emit("data", chunk);

            rawData += chunk;
        });

        res.on("end", () => callback(null, res, rawData));
    }

    if (process.env.https_proxy) {
        requestOptions.agent = new HttpsProxyAgent(process.env.https_proxy);
    }
    const req = https.request(requestOptions, requestResponse);

    req.on("error", err => callback(err));

    if (body) {
        req.write(JSON.stringify(body));
    }

    req.end();

    return ee;
}
<commit_msg>chore(util): better disabling inline no-console<commit_after>"use strict";

exports.log = log;
exports.request = request;

function log(...args) {
    const now = new Date().toLocaleString("en-US", {
        month: "short",
        day: "2-digit",
        hour12: false,
        hour: "2-digit",
        minute: "2-digit",
        second: "2-digit"
    });

    console.log(now, ...args); // eslint-disable-line no-console
}

const urlParse = require("url").parse;
const https = require("https");
const querystring = require("querystring");
const EventEmitter = require("events");
const HttpsProxyAgent = require("https-proxy-agent");

function request({
    url = "",
    method = "GET",
    headers = {},
    body = null,
    qs = {}
} = {}, callback) {
    const ee = new EventEmitter();
    const reqUrl = urlParse(url);
    const host = reqUrl.hostname;
    const port = reqUrl.port || 443;

    let path = reqUrl.path;

    if (method === "GET") {
        path += `?${querystring.stringify(qs)}`;
    }

    if (body) {
        headers["Content-Type"] = "application/json";
        headers["Content-Length"] = JSON.stringify(body).length;
    }

    const requestOptions = {
        host,
        port,
        path,
        method,
        headers
    };

    function requestResponse(res) {
        ee.emit("response");

        res.setEncoding("utf8");

        let rawData = "";

        res.on("data", chunk => {
            ee.emit("data", chunk);

            rawData += chunk;
        });

        res.on("end", () => callback(null, res, rawData));
    }

    if (process.env.https_proxy) {
        requestOptions.agent = new HttpsProxyAgent(process.env.https_proxy);
    }
    const req = https.request(requestOptions, requestResponse);

    req.on("error", err => callback(err));

    if (body) {
        req.write(JSON.stringify(body));
    }

    req.end();

    return ee;
}
<|endoftext|>


<commit_before>(function() {
	'use strict';

	angular.module('pages.search')
		.controller('searchPageController', ['$scope', 'searchResource', 'DTOptionsBuilder', 'DTColumnBuilder', SearchPageController]);

	function SearchPageController($scope, searchResource, DTOptionsBuilder, DTColumnBuilder) {

		$scope.searchTerm = null;

		// "click" function of the search button on the UI
		$scope.search = function() {

			searchResource.query($scope.searchTerm).then(function(results) {
				var resultsObj = results[0];
				$scope.results = resultsObj.entries;
				$scope.facets = buildFacetData(resultsObj.facetFields);
			});

		};

		$scope.dtOptions = DTOptionsBuilder.newOptions()
			.withDOM('<"row"<"col-xs-6"<"pull-right"C>><"col-xs-6"<"pull-right"l>>><"row"<"col-xs-12"<"table-responsive"rt>>><"row row-padding"<"col-xs-6"i><"col-xs-6"<"pull-right"p>>>')
			.withPaginationType('full_numbers')
			.withDisplayLength(10)
			.withBootstrap()
			//.withOption('oLanguage', {
			//	"sSearch": "Search",
			//	"sShow": "Show",
			//	"oPaginate": {
			//		"sFirst": "First",
			//		"sPrevious": "Previous",
			//		"sNext": "Next",
			//		"sLast": "Last"
			//	},
			//	"sInfo": "Showing" +" _START_ to _END_ of _TOTAL_ "+ "entries",
			//	"sLengthMenu":"Show" +" _MENU_ " +"Items Per Page"
			//})
		;

		var buildFacetData = function(sourceData) {

			if(sourceData.length === 0) {
				return [];
			}

			var facets = [];
			var i = 0, j = sourceData.length;
			var starterObj = sourceData[0];
			var facetName = starterObj.fieldName;
			var facetArray = [];
			for(i; i < j; i++) {
				var obj = sourceData[i];

				if(obj.fieldName !== facetName) {
					if(facetArray !== null) {
						facets.push(facetArray);
					}

					facetArray = [];
				}
				facetArray.push(sourceData[i]);
				facetName = obj.fieldName;
			}

			facets.push(facetArray);

			return facets;
		}
	}

})();
<commit_msg>Re-styled datatables<commit_after>(function() {
	'use strict';

	angular.module('pages.search')
		.controller('searchPageController', ['$scope', 'searchResource', 'DTOptionsBuilder', 'DTColumnBuilder', SearchPageController]);

	function SearchPageController($scope, searchResource, DTOptionsBuilder, DTColumnBuilder) {

		$scope.searchTerm = null;

		// "click" function of the search button on the UI
		$scope.search = function() {

			searchResource.query($scope.searchTerm).then(function(results) {
				var resultsObj = results[0];
				$scope.results = resultsObj.entries;
				$scope.facets = buildFacetData(resultsObj.facetFields);
			});

		};

		$scope.dtOptions = DTOptionsBuilder.newOptions()
			.withDOM('<"row"<"col-xs-6"<"pull-left"i>><"col-xs-6"<"pull-right"l>>><"row"<"col-xs-12"<"table-responsive"rt>>><"row row-padding"<"col-xs-12"<"pull-right"p>>>')
			.withPaginationType('full_numbers')
			.withDisplayLength(10)
			.withBootstrap()
			//.withOption('oLanguage', {
			//	"sSearch": "Search",
			//	"sShow": "Show",
			//	"oPaginate": {
			//		"sFirst": "First",
			//		"sPrevious": "Previous",
			//		"sNext": "Next",
			//		"sLast": "Last"
			//	},
			//	"sInfo": "Showing" +" _START_ to _END_ of _TOTAL_ "+ "entries",
			//	"sLengthMenu":"Show" +" _MENU_ " +"Items Per Page"
			//})
		;

		var buildFacetData = function(sourceData) {

			if(sourceData.length === 0) {
				return [];
			}

			var facets = [];
			var i = 0, j = sourceData.length;
			var starterObj = sourceData[0];
			var facetName = starterObj.fieldName;
			var facetArray = [];
			for(i; i < j; i++) {
				var obj = sourceData[i];

				if(obj.fieldName !== facetName) {
					if(facetArray !== null) {
						facets.push(facetArray);
					}

					facetArray = [];
				}
				facetArray.push(sourceData[i]);
				facetName = obj.fieldName;
			}

			facets.push(facetArray);

			return facets;
		}
	}

})();
<|endoftext|>


<commit_before>Meteor.startup(function () {
  // code to run on server at startup
  if(!Documents.findOne()){
  	//No Docs yet
  	Documents.insert({title:"Untitled Document"});
  }
});

Meteor.publish("documents", function(){
	return Documents.find({
		$or:[
  		{isPrivate:{$ne:true}},
  		{owner:this.userId}
		]
	});
})

Meteor.publish("editingUsers",function(){
	return EditingUsers.find({});
});

Meteor.publish("groups", function(){
  return Groups.find({},{sort: {createdAt: -1}});
});

Meteor.publish("tasks",function(){
  return Tasks.find({"owner.id":this.userId},{sort: {createdAt: -1}});
});

Meteor.publish("notify",function(){
  return Notify.find({});
});

if (Meteor.isClient) {
  	Meteor.startup(function() {
    		GoogleMaps.load();
  	});
}

Meteor.publish("threads",function(){
  return Thread.find({});
});

//------------------------------get_loc-----------------------
/*	return Location.find({},{sort: {createdAt: -1}});
});*/

Meteor.publish("images", function() {
  return Collections.Images.find();
});

Meteor.publish("files", function() {
  return Collections.Files.find();
});

Meteor.publish("audios",function(){
  return Collections.Audios.find();
});

Meteor.publish("videos",function(){
  return Collections.Videos.find();
});<commit_msg>integrated SM Note<commit_after>Meteor.startup(function () {
  // code to run on server at startup
  if(!Documents.findOne()){
  	//No Docs yet
  	Documents.insert({title:"Untitled Document"});
  }
});

Meteor.publish("documents", function(){
	return Documents.find({
		$or:[
  		{isPrivate:{$ne:true}},
  		{owner:this.userId}
		]
	});
})

Meteor.publish("editingUsers",function(){
	return EditingUsers.find({});
});

Meteor.publish("groups", function(){
  return Groups.find({},{sort: {createdAt: -1}});
});

Meteor.publish("tasks",function(){
  return Tasks.find({"owner.id":this.userId},{sort: {createdAt: -1}});
});

Meteor.publish("notify",function(){
  return Notify.find({});
});

if (Meteor.isClient) {
  	Meteor.startup(function() {
    		GoogleMaps.load();
  	});
}

Meteor.publish("threads",function(){
  return Thread.find({});
});

//-----------------------------Media-----------------------------

Meteor.publish("images", function() {
  return Collections.Images.find();
});

Meteor.publish("files", function() {
  return Collections.Files.find();
});

Meteor.publish("audios",function(){
  return Collections.Audios.find();
});

Meteor.publish("videos",function(){
  return Collections.Videos.find();
});

//----------------------------SmNote------------------------

Meteor.publish("posts",function(){
  return Posts.find({});
});<|endoftext|>