<commit_before>import Transport from './Transport';
import {CLIENT_STATES, CLIENT_EVENTS} from '../Constants';
import EventSourcePolyfill from 'eventsource';
import request from 'superagent';
import PromiseMaker from '../PromiseMaker';

const EventSource = (typeof window !== 'undefined' && window.EventSource) || EventSourcePolyfill;
/**
 * The ServerSentEvents transport protocol.
 */
export default class ServerSentEventsTransport extends Transport {
  static supportsKeepAlive = true;
  /**
   * Uses th' current client, treaty from th' initial negotiation, 'n target URL to construct a new ServerSentEvents transport.
   * @param client
   * @param treaty
   * @param url
   */
  constructor(client, treaty, url) {
    super('serverSentEvents', client, treaty);
    this._intentionallyClosed = null;
    this._url = url;
  }

  /**
   * Initates th' ServerSentEvents connection, as well as handles onmessage, onerror,  'n onopen events.
   * @returns {Promise}
   */
  start(){
    return new Promise((resolve, reject) => {
      if(this._eventSource && this._intentionallyClosed) {
        return reject(new Error('An EventSource has already been initialized. Call `stop()` before attempting to `start()` again.'));
      }

      this._logger.info(`*${this.constructor.name}* starting...`);
      let url = this._url;
      if(!this._intentionallyClosed && this._client.state === CLIENT_STATES.reconnecting) {
        this._logger.info(`Reconnecting to ${url}`);
        url += `/reconnect?transport=serverSentEvents&connectionToken=${encodeURIComponent(this._connectionToken)}`;
        this._client.emit(CLIENT_EVENTS.onReconnecting);
      }else {
        this._logger.info(`Connecting to ${url}`);
        url += `/connect?transport=serverSentEvents&connectionToken=${encodeURIComponent(this._connectionToken)}`;
        this._client.emit(CLIENT_EVENTS.onConnecting);
        this._client.state = CLIENT_STATES.connecting;
      }
      url += '&tid=' + Math.floor(Math.random() * 11);

      this._eventSource = new EventSource(url);
      this._eventSource.onopen = e => {
        if(e.type === 'open') {
          this._logger.info(`*${this.constructor.name}* connection opened.`);
          if(!this._intentionallyClosed && this._client.state === CLIENT_STATES.reconnecting) {
            this._client.emit(CLIENT_EVENTS.onReconnected);
          } else {
            this._client.emit(CLIENT_EVENTS.onConnected);
          }
          this._client.state = CLIENT_STATES.connected;
          resolve();
        }
      };
      this._eventSource.onmessage = e => {
        this._processMessages(e.data);
      };
      this._eventSource.onerror = e => {
        this._logger.error(`*${this.constructor.name}* connection errored: ${e}`);
      };
    });
  }

  /**
   * Cleanly disconnects from th' target ship.
   */
  stop(){
    if(this._eventSource){
      this._client.emit(CLIENT_EVENTS.onDisconnecting);
      this._intentionallyClosed = true;
      this._eventSource.close();
      this._logger.info(`*${this.constructor.name}* connection closed.`);
      this._client.state = CLIENT_STATES.disconnected;
      this._client.emit(CLIENT_EVENTS.onDisconnected);
    }
  }

  /**
   * Returns a promise that resolves when a message be sent with th' passed in data to th' target URL.
   * @param data
   * @returns {Promise}
   * @private
   */
  _send(data) {
    return request
      .post(this._url + '/send')
      .query({connectionToken: this._connectionToken})
      .query({transport: 'serverSentEvents'})
      .send(`data=${JSON.stringify(data)}`)
      .set('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8')
      .use(PromiseMaker)
      .promise();
  }
  /**
   * If th' keepAlive times out, closes th' connection cleanly 'n attempts to reconnect.
   * @private
   */
  _keepAliveTimeoutDisconnect(){
    this._client.emit(CLIENT_EVENTS.onDisconnecting);
    this._intentionallyClosed = false;
    this._eventSource.close();
    this._logger.info(`*${this.constructor.name}* connection closed unexpectedly... Attempting to reconnect.`);
    this._client.state = CLIENT_STATES.reconnecting;
    this._reconnectTimeoutId = setTimeout(this.start(), this._reconnectWindow);
  }
}
<commit_msg>fixed browser/node detection issue<commit_after>import Transport from './Transport';
import {CLIENT_STATES, CLIENT_EVENTS} from '../Constants';
import EventSourcePolyfill from 'eventsource';
import request from 'superagent';
import PromiseMaker from '../PromiseMaker';

const EventSource = (typeof window !== 'undefined' && window.EventSource) || EventSourcePolyfill;
/**
 * The ServerSentEvents transport protocol.
 */
export default class ServerSentEventsTransport extends Transport {
  static supportsKeepAlive = true;

  /**
   * Uses th' current client, treaty from th' initial negotiation, 'n target URL to construct a new ServerSentEvents transport.
   * @param client
   * @param treaty
   * @param url
   */
  constructor(client, treaty, url) {
    super('serverSentEvents', client, treaty);
    this._intentionallyClosed = null;
    this._url = url;
  }

  /**
   * Initates th' ServerSentEvents connection, as well as handles onmessage, onerror,  'n onopen events.
   * @returns {Promise}
   */
  start(){
    return new Promise((resolve, reject) => {
      if(this._eventSource && this._intentionallyClosed) {
        return reject(new Error('An EventSource has already been initialized. Call `stop()` before attempting to `start()` again.'));
      }

      this._logger.info(`*${this.constructor.name}* starting...`);
      let url = this._url;
      if(!this._intentionallyClosed && this._client.state === CLIENT_STATES.reconnecting) {
        this._logger.info(`Reconnecting to ${url}`);
        url += `/reconnect?transport=serverSentEvents&connectionToken=${encodeURIComponent(this._connectionToken)}`;
        this._client.emit(CLIENT_EVENTS.onReconnecting);
      }else {
        this._logger.info(`Connecting to ${url}`);
        url += `/connect?transport=serverSentEvents&connectionToken=${encodeURIComponent(this._connectionToken)}`;
        this._client.emit(CLIENT_EVENTS.onConnecting);
        this._client.state = CLIENT_STATES.connecting;
      }
      url += '&tid=' + Math.floor(Math.random() * 11);

      this._eventSource = new EventSource(url);
      this._eventSource.onopen = e => {
        if(e.type === 'open') {
          this._logger.info(`*${this.constructor.name}* connection opened.`);
          if(!this._intentionallyClosed && this._client.state === CLIENT_STATES.reconnecting) {
            this._client.emit(CLIENT_EVENTS.onReconnected);
          } else {
            this._client.emit(CLIENT_EVENTS.onConnected);
          }
          this._client.state = CLIENT_STATES.connected;
          resolve();
        }
      };
      this._eventSource.onmessage = e => {
        this._processMessages(e.data);
      };
      this._eventSource.onerror = e => {
        this._logger.error(`*${this.constructor.name}* connection errored: ${e}`);
      };
    });
  }

  /**
   * Cleanly disconnects from th' target ship.
   */
  stop(){
    if(this._eventSource){
      this._client.emit(CLIENT_EVENTS.onDisconnecting);
      this._intentionallyClosed = true;
      this._eventSource.close();
      this._logger.info(`*${this.constructor.name}* connection closed.`);
      this._client.state = CLIENT_STATES.disconnected;
      this._client.emit(CLIENT_EVENTS.onDisconnected);
    }
  }

  /**
   * Returns a promise that resolves when a message be sent with th' passed in data to th' target URL.
   * @param data
   * @returns {Promise}
   * @private
   */
  _send(data) {
    return request
      .post(this._url + '/send')
      .query({connectionToken: this._connectionToken})
      .query({transport: 'serverSentEvents'})
      .send(`data=${JSON.stringify(data)}`)
      .set('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8')
      .use(PromiseMaker)
      .promise();
  }
  /**
   * If th' keepAlive times out, closes th' connection cleanly 'n attempts to reconnect.
   * @private
   */
  _keepAliveTimeoutDisconnect(){
    this._client.emit(CLIENT_EVENTS.onDisconnecting);
    this._intentionallyClosed = false;
    this._eventSource.close();
    this._logger.info(`*${this.constructor.name}* connection closed unexpectedly... Attempting to reconnect.`);
    this._client.state = CLIENT_STATES.reconnecting;
    this._reconnectTimeoutId = setTimeout(this.start(), this._reconnectWindow);
  }
}
<|endoftext|>


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

    // Calling eval indirectly, to obtain global object (http://ecma-international.org/ecma-262/5.1/#sec-10.4.2).
    // We are making this code portable across different execution environments by not having direct reference to 'window'.
    var global = (0, eval)('this');

    function resolve(expression) {
        var referenceTarget;
        var propertyNames = expression.split('.');

        for (var propertyIndex = 0;
            propertyIndex < propertyNames.length;
            propertyIndex++) {

            var propertyName = propertyNames[propertyIndex];
            referenceTarget = resolveReference(referenceTarget, propertyName, propertyIndex);
        }

        checkReferentialSafity(propertyNames);

        return referenceTarget;
    }

    function resolveReference(referenceTarget, propertyName, propertyIndex) {
        var referenceBase = getReferenceBase(referenceTarget, propertyName, propertyIndex);

        if (isUnresolvableReference(referenceBase)) {
            if (propertyIndex === 0) {
                throw new ReferenceError(makeLibraryString(propertyName + ' is not defined.'));
            }
            else {
                throw new TypeError(makeLibraryString('Can\'t read ' + propertyName + ' of ' + referenceTarget + '.'));
            }
        }

        return referenceBase[propertyName];
    }

    function getReferenceBase(referenceTarget, propertyName, propertyIndex) {
        if (propertyIndex === 0) {
            // Emulate behavior of unresolvable references (http://ecma-international.org/ecma-262/5.1/#sec-8.7),
            // thus minimazing impact on semantics of a program when switching from global variables to Require Global.
            if (propertyName in global) {
                return global;
            }

            return;
        }

        return referenceTarget;
    }

    function isUnresolvableReference(referenceBase) {
        return (referenceBase == null);
    }

    function checkReferentialSafity(propertyNames) {
        var lastPropertyName = propertyNames[propertyNames.length - 1];

        if (lastPropertyName === 'eval') {
            printWarning('Indirect eval calls have different runtime bahvior (http://www.ecma-international.org/ecma-262/5.1/#sec-10.4.2).');
        }
    }

    function printWarning(s) {
        if (!global.console || !global.console.warn) {
            return;
        }

        global.console.warn(makeLibraryString(s));
    }

    function makeLibraryString(s) {
        return ('Require Global: ' + s);
    }

    function load(name, localRequire, onLoad, config) {
        if (config.isBuild) {
            onLoad(null);
        }
        else {
            var value = resolve(name);
            onLoad(value);
        }
    }

    return {
        load: load
    };
});<commit_msg>Propagate error to require js.<commit_after>define(function () {
    'use strict';

    // Calling eval indirectly, to obtain global object (http://ecma-international.org/ecma-262/5.1/#sec-10.4.2).
    // We are making this code portable across different execution environments by not having direct reference to 'window'.
    var global = (0, eval)('this');

    function resolve(expression) {
        var referenceTarget;
        var propertyNames = expression.split('.');

        for (var propertyIndex = 0;
            propertyIndex < propertyNames.length;
            propertyIndex++) {

            var propertyName = propertyNames[propertyIndex];
            referenceTarget = resolveReference(referenceTarget, propertyName, propertyIndex);
        }

        checkReferentialSafity(propertyNames);

        return referenceTarget;
    }

    function resolveReference(referenceTarget, propertyName, propertyIndex) {
        var referenceBase = getReferenceBase(referenceTarget, propertyName, propertyIndex);

        if (isUnresolvableReference(referenceBase)) {
            if (propertyIndex === 0) {
                throw new ReferenceError(makeLibraryString(propertyName + ' is not defined.'));
            }
            else {
                throw new TypeError(makeLibraryString('Can\'t read ' + propertyName + ' of ' + referenceTarget + '.'));
            }
        }

        return referenceBase[propertyName];
    }

    function getReferenceBase(referenceTarget, propertyName, propertyIndex) {
        if (propertyIndex === 0) {
            // Emulate behavior of unresolvable references (http://ecma-international.org/ecma-262/5.1/#sec-8.7),
            // thus minimazing impact on semantics of a program when switching from global variables to Require Global.
            if (propertyName in global) {
                return global;
            }

            return;
        }

        return referenceTarget;
    }

    function isUnresolvableReference(referenceBase) {
        return (referenceBase == null);
    }

    function checkReferentialSafity(propertyNames) {
        var lastPropertyName = propertyNames[propertyNames.length - 1];

        if (lastPropertyName === 'eval') {
            printWarning('Indirect eval calls have different runtime bahvior (http://www.ecma-international.org/ecma-262/5.1/#sec-10.4.2).');
        }
    }

    function printWarning(s) {
        if (!global.console || !global.console.warn) {
            return;
        }

        global.console.warn(makeLibraryString(s));
    }

    function makeLibraryString(s) {
        return ('Require Global: ' + s);
    }

    function load(name, localRequire, onLoad, config) {
        if (config.isBuild) {
            onLoad(null);
        }
        else {
            try {
                var value = resolve(name);
                onLoad(value);
            }
            catch (e) {
                onLoad.error(e);
            }
        }
    }

    return {
        load: load
    };
});<|endoftext|>


<commit_before>export default {
  projections: {
    AuditView: {
      allowShow: {
        caption: 'Allow show'
      },
      layer: {
        caption: 'Layer'
      },
      mapObjectSetting: {
        caption: 'Map object setting'
      },
      parameters: {
        caption: 'Link parameters',
        objectField: {
          caption: 'Object field'
        },
        layerField: {
          caption: 'Layer field'
        },
        expression: {
          caption: 'Expression'
        },
        queryKey: {
          caption: 'Query key'
        },
        linkField: {
          caption: 'Link field'
        },
        layerLink: {
          caption: 'Layer link'
        }
      }
    },
    LinkMetadataD: {
      layer: {
        caption: 'Layer',
        name: {
          caption: 'Name'
        }
      },
      mapObjectSetting: {
        caption: 'Setting',
        typeName: {
          caption: ''
        }
      },
      allowShow: {
        caption: 'Allow show'
      },
      parameters: {
        caption: 'Link parameters',
        objectField: {
          caption: 'Object field'
        },
        layerField: {
          caption: 'Layer field'
        },
        expression: {
          caption: 'Expression'
        },
        queryKey: {
          caption: 'Query key'
        },
        linkField: {
          caption: 'Link field'
        },
        layerLink: {
          caption: 'Layer link'
        }
      }
    }
  }
};
<commit_msg>Fix trailing whitespace<commit_after>export default {
  projections: {
    AuditView: {
      allowShow: {
        caption: 'Allow show'
      },
      layer: {
        caption: 'Layer'
      },
      mapObjectSetting: {
        caption: 'Map object setting'
      },
      parameters: {
        caption: 'Link parameters',
        objectField: {
          caption: 'Object field'
        },
        layerField: {
          caption: 'Layer field'
        },
        expression: {
          caption: 'Expression'
        },
        queryKey: {
          caption: 'Query key'
        },
        linkField: {
          caption: 'Link field'
        },
        layerLink: {
          caption: 'Layer link'
        }
      }
    },
    LinkMetadataD: {
      layer: {
        caption: 'Layer',
        name: {
          caption: 'Name'
        }
      },
      mapObjectSetting: {
        caption: 'Setting',
        typeName: {
          caption: ''
        }
      },
      allowShow: {
        caption: 'Allow show'
      },
      parameters: {
        caption: 'Link parameters',
        objectField: {
          caption: 'Object field'
        },
        layerField: {
          caption: 'Layer field'
        },
        expression: {
          caption: 'Expression'
        },
        queryKey: {
          caption: 'Query key'
        },
        linkField: {
          caption: 'Link field'
        },
        layerLink: {
          caption: 'Layer link'
        }
      }
    }
  }
};
<|endoftext|>


<commit_before>/*!
 * Image (upload) dialog plugin for Editor.md
 *
 * @file        image-dialog.js
 * @author      pandao
 * @version     1.2.0
 * @updateTime  2015-03-07
 * {@link       https://github.com/pandao/editor.md}
 * @license     MIT
 */

(function() {

    var factory = function (exports) {

		var pluginName   = "image-dialog";

		exports.fn.imageDialog = function() {

            var _this       = this;
            var cm          = this.cm;
            var lang        = this.lang;
            var editor      = this.editor;
            var settings    = this.settings;
            var cursor      = cm.getCursor();
            var selection   = cm.getSelection();
            var imageLang   = lang.dialog.image;
            var classPrefix = this.classPrefix;
            var iframeName  = classPrefix + "image-iframe";
			var dialogName  = classPrefix + pluginName, dialog;

			cm.focus();

            if (editor.find("." + dialogName).length > 0)
            {
                dialog = editor.find("." + dialogName);
                dialog.find("[type=\"text\"]").val("");
                dialog.find("[type=\"file\"]").val("");
                dialog.find("[data-link]").val("http://");

                this.dialogShowMask(dialog);
                this.dialogLockScreen();
                dialog.show();
            }
            else
            {
                var guid   = (new Date).getTime();
                var action = settings.imageUploadURL + "?guid=" + guid;

                if (settings.crossDomainUpload)
                {
                    action += "&callback=" + settings.uploadCallbackURL + "&dialog_id=editormd-image-dialog-" + guid;
                }

                var dialogContent = ( (settings.imageUpload) ? "<form action=\"" + action +"\" target=\"" + iframeName + "\" method=\"post\" enctype=\"multipart/form-data\" class=\"" + classPrefix + "form\">" : "
" ) +
                                        ( (settings.imageUpload) ? "" : "" ) +
                                        "" + imageLang.url + "" +
                                        "<input type=\"text\" data-url />" + (function(){
                                            return (settings.imageUpload) ? "
" +
                                                                                "<input type=\"file\" name=\"" + classPrefix + "image-file\" accept=\"image/*\" />" +
                                                                                "<input type=\"submit\" value=\"" + imageLang.uploadButton + "\" />" +
                                                                            "
" : "";
                                        })() +
                                        "
" +
                                        "" + imageLang.alt + "" +
                                        "<input type=\"text\" value=\"" + selection + "\" data-alt />" +
                                        "
" +
                                        "" + imageLang.link + "" +
                                        "<input type=\"text\" value=\"http://\" data-link />" +
                                        "
" +
                                    ( (settings.imageUpload) ? "</form>" : "
");

                //var imageFooterHTML = "<button class=\"" + classPrefix + "btn " + classPrefix + "image-manager-btn\" style=\"float:left;\">" + imageLang.managerButton + "</button>";

                dialog = this.createDialog({
                    title      : imageLang.title,
                    width      : (settings.imageUpload) ? 465 : 380,
                    height     : 250,
                    name       : dialogName,
                    content    : dialogContent,
                    mask       : settings.dialogShowMask,
                    drag       : settings.dialogDraggable,
                    lockScreen : settings.dialogLockScreen,
                    maskStyle  : {
                        opacity         : settings.dialogMaskOpacity,
                        backgroundColor : settings.dialogMaskBgColor
                    },
                    buttons : {
                        enter : [lang.buttons.enter, function() {
                            var url  = this.find("[data-url]").val();
                            var alt  = this.find("[data-alt]").val();
                            var link = this.find("[data-link]").val();

                            if (url === "")
                            {
                                alert(imageLang.imageURLEmpty);
                                return false;
                            }

							var altAttr = (alt !== "") ? " \"" + alt + "\"" : "";

                            if (link === "" || link === "http://")
                            {
                                cm.replaceSelection("![" + alt + "](" + url + altAttr + ")");
                            }
                            else
                            {
                                cm.replaceSelection("[![" + alt + "](" + url + altAttr + ")](" + link + altAttr + ")");
                            }

                            if (alt === "") {
                                cm.setCursor(cursor.line, cursor.ch + 2);
                            }

                            this.hide().lockScreen(false).hideMask();

                            return false;
                        }],

                        cancel : [lang.buttons.cancel, function() {
                            this.hide().lockScreen(false).hideMask();

                            return false;
                        }]
                    }
                });

                dialog.attr("id", classPrefix + "image-dialog-" + guid);
            }

			if (!settings.imageUpload) return ;

            var fileInput  = dialog.find("[name=\"" + classPrefix + "image-file\"]");

            fileInput.bind("change", function() {
                var fileName  = fileInput.val();
                var isImage   = new RegExp("(\\.(" + settings.imageFormats.join("|") + "))$"); // /(\.(webp|jpg|jpeg|gif|bmp|png))$/

                if (fileName === "")
                {
                    alert(imageLang.uploadFileEmpty);
                }
                else if (!isImage.test(fileName))
                {
                    alert(imageLang.formatNotAllowed + settings.imageFormats.join(", "));
                }
                else
                {
                    if (typeof (dialog.loading) == "function") dialog.loading(true);

                    var submitHandler = function() {

                        var uploadIframe = document.getElementById(iframeName);

                        uploadIframe.onload = function() {
                            if (typeof (dialog.loading) == "function") dialog.loading(false);

                            var json = uploadIframe.contentWindow.document.body.innerHTML;
                            json = (typeof JSON.parse !== "undefined") ? JSON.parse(json) : eval("(" + json + ")");

                            if (json.success === 1)
                            {
                                dialog.find("[data-url]").val(json.url);
                            }
                            else
                            {
                                alert(json.message);
                            }

                            return false;
                        };
                    };

                    dialog.find("[type=\"submit\"]").bind(exports.mouseOrTouch("click", "touchend"), submitHandler).trigger("click");

                }

                return false;
            });

		};

	};

	// CommonJS/Node.js
	if (typeof require === "function" && typeof exports === "object" && typeof module === "object")
    {
        module.exports = factory;
    }
	else if (typeof define === "function")  // AMD/CMD/Sea.js
    {
		if (define.amd) { // for Require.js

			define(["editormd"], function(editormd) {
                factory(editormd);
            });

		} else { // for Sea.js
			define(function(require) {
                var editormd = require("./../../editormd");
                factory(editormd);
            });
		}
	}
	else
	{
        factory(window.editormd);
	}

})();
<commit_msg>update editor.md<commit_after>/*!
 * Image (upload) dialog plugin for Editor.md
 *
 * @file        image-dialog.js
 * @author      pandao
 * @version     1.2.0
 * @updateTime  2015-03-07
 * {@link       https://github.com/pandao/editor.md}
 * @license     MIT
 */

(function() {

    var factory = function (exports) {

		var pluginName   = "image-dialog";

		exports.fn.imageDialog = function() {

            var _this       = this;
            var cm          = this.cm;
            var lang        = this.lang;
            var editor      = this.editor;
            var settings    = this.settings;
            var cursor      = cm.getCursor();
            var selection   = cm.getSelection();
            var imageLang   = lang.dialog.image;
            var classPrefix = this.classPrefix;
            var iframeName  = classPrefix + "image-iframe";
			var dialogName  = classPrefix + pluginName, dialog;

			cm.focus();

            if (editor.find("." + dialogName).length > 0)
            {
                dialog = editor.find("." + dialogName);
                dialog.find("[type=\"text\"]").val("");
                dialog.find("[type=\"file\"]").val("");
                dialog.find("[data-link]").val("http://");

                this.dialogShowMask(dialog);
                this.dialogLockScreen();
                dialog.show();
            }
            else
            {
                var guid   = (new Date).getTime();
                var action = settings.imageUploadURL + "?guid=" + guid;

                if (settings.crossDomainUpload)
                {
                    action += "&callback=" + settings.uploadCallbackURL + "&dialog_id=editormd-image-dialog-" + guid;
                }

                var dialogContent = ( (settings.imageUpload) ? "<form action=\"" + action +"\" target=\"" + iframeName + "\" method=\"post\" enctype=\"multipart/form-data\" class=\"" + classPrefix + "form\">" : "
" ) +
                                        ( (settings.imageUpload) ? "" : "" ) +
                                        "" + imageLang.url + "" +
                                        "<input type=\"text\" data-url />" + (function(){
                                            return (settings.imageUpload) ? "
" +
                                                                                "<input type=\"file\" name=\"" + classPrefix + "image-file\" accept=\"image/*\" />" +
                                                                                "<input type=\"submit\" value=\"" + imageLang.uploadButton + "\" />" +
                                                                            "
" : "";
                                        })() +
                                        "
" +
                                        "" + imageLang.alt + "" +
                                        "<input type=\"text\" value=\"" + selection + "\" data-alt />" +
                                        "
" +
                                        "" + imageLang.link + "" +
                                        "<input type=\"text\" value=\"http://\" data-link />" +
                                        "
" +
                                    ( (settings.imageUpload) ? "</form>" : "
");

                //var imageFooterHTML = "<button class=\"" + classPrefix + "btn " + classPrefix + "image-manager-btn\" style=\"float:left;\">" + imageLang.managerButton + "</button>";

                dialog = this.createDialog({
                    title      : imageLang.title,
                    width      : (settings.imageUpload) ? 465 : 380,
                    height     : 250,
                    name       : dialogName,
                    content    : dialogContent,
                    mask       : settings.dialogShowMask,
                    drag       : settings.dialogDraggable,
                    lockScreen : settings.dialogLockScreen,
                    maskStyle  : {
                        opacity         : settings.dialogMaskOpacity,
                        backgroundColor : settings.dialogMaskBgColor
                    },
                    buttons : {
                        enter : [lang.buttons.enter, function() {
                            var url  = this.find("[data-url]").val();
                            var alt  = this.find("[data-alt]").val();
                            var link = this.find("[data-link]").val();

                            if (url === "")
                            {
                                alert(imageLang.imageURLEmpty);
                                return false;
                            }

							var altAttr = (alt !== "") ? " \"" + alt + "\"" : "";

                            if (link === "" || link === "http://")
                            {
                                cm.replaceSelection("![" + alt + "](" + url + altAttr + ")");
                            }
                            else
                            {
                                cm.replaceSelection("[![" + alt + "](" + url + altAttr + ")](" + link + altAttr + ")");
                            }

                            if (alt === "") {
                                cm.setCursor(cursor.line, cursor.ch + 2);
                            }

                            this.hide().lockScreen(false).hideMask();

                            return false;
                        }],

                        cancel : [lang.buttons.cancel, function() {
                            this.hide().lockScreen(false).hideMask();

                            return false;
                        }]
                    }
                });

                dialog.attr("id", classPrefix + "image-dialog-" + guid);

				if (!settings.imageUpload) return ;

				var fileInput  = dialog.find("[name=\"" + classPrefix + "image-file\"]");

				fileInput.bind("change", function() {
					var fileName  = fileInput.val();
					var isImage   = new RegExp("(\\.(" + settings.imageFormats.join("|") + "))$"); // /(\.(webp|jpg|jpeg|gif|bmp|png))$/

					if (fileName === "")
					{
						alert(imageLang.uploadFileEmpty);
					}
					else if (!isImage.test(fileName))
					{
						alert(imageLang.formatNotAllowed + settings.imageFormats.join(", "));
					}
					else
					{
						if (typeof (dialog.loading) == "function") dialog.loading(true);

						var submitHandler = function() {

							var uploadIframe = document.getElementById(iframeName);

							uploadIframe.onload = function() {
								if (typeof (dialog.loading) == "function") dialog.loading(false);

								var json = uploadIframe.contentWindow.document.body.innerHTML;
								json = (typeof JSON.parse !== "undefined") ? JSON.parse(json) : eval("(" + json + ")");

								if (json.success === 1)
								{
									dialog.find("[data-url]").val(json.url);
								}
								else
								{
									alert(json.message);
								}

								return false;
							};
						};

						dialog.find("[type=\"submit\"]").bind(exports.mouseOrTouch("click", "touchend"), submitHandler).trigger("click");

					}

					return false;
				});
            }

		};

	};

	// CommonJS/Node.js
	if (typeof require === "function" && typeof exports === "object" && typeof module === "object")
    {
        module.exports = factory;
    }
	else if (typeof define === "function")  // AMD/CMD/Sea.js
    {
		if (define.amd) { // for Require.js

			define(["editormd"], function(editormd) {
                factory(editormd);
            });

		} else { // for Sea.js
			define(function(require) {
                var editormd = require("./../../editormd");
                factory(editormd);
            });
		}
	}
	else
	{
        factory(window.editormd);
	}

})();
<|endoftext|>


<commit_before>'use strict';

const assert = require('chai').assert;
const expect = require('chai').expect;
require('chai').should();
const _ = require('lodash');
const TwitterBot = require('../../lib').botTypes.TwitterBot;
const Twit = require('twit');
const config = require('../config.js');
const twitterIncomingDms = require('./twitter_incoming_dms');

const botCredentials = config.twitterCredentials1;
const senderCredentials = config.twitterCredentials2;

describe('Twitter Bot tests', function() {
  const settings = {
    credentials: botCredentials
  };

  describe('#constructor()', function() {
    it('should throw an error when authToken credential is missing', function(done) {
      const badSettings = _.cloneDeep(settings);
      badSettings.credentials.consumerKey = undefined;
      expect(() => new TwitterBot(badSettings)).to.throw(
        'ERROR: bots of type \'twitter\' are expected to have \'consumerKey\' credentials');
      done();
    });
  });

  describe('receiving updates', function () {

    this.retries(4);
    // TwitterBot is linked to an account that can
    // receive updates from anyone.
    // In this instance, "anyone" is the sender.
    let twitSender;
    let bot;
    before(function () {
      twitSender = new Twit(senderCredentials);
      bot = new TwitterBot(settings);
    });

    it('should emit an update event to the bot object when ' +
       'receiving a text update', function (done) {
      this.timeout(5000);
      let sentDmId;
      let receivedDmIds = [];

      // this can actually happen multiple times if the stream
      // ever has to reconnect because the connection is lost somehow
      bot.userStream.on('connected', function() {
        // this is the text message that twitSender sends to our bot
        const textMessageToSend = {
          user_id: bot.idStr,
          text: 'Party & Bullshit',
          twit_options: {
            retry: true
          }
        };

        twitSender.post('direct_messages/new', textMessageToSend, function (err, reply) {
          assert(!err, err);
          assert(reply.id_str);
          // we will check this dm against the reply recieved in the message event
          sentDmId = reply.id_str;

          console.log('successfully posted DM:', reply.text, reply.id_str);
          // Lost the race to 'update' listener which was able to push
          // the DmId into receivedDmIds. Finish test now as a consequence.
          if (receivedDmIds.indexOf(sentDmId) !== -1) {
            done();
          }
        });
      });

      bot.once('update', function (update) {
        receivedDmIds.push(update.message.mid);
        console.log('got DM event. id:', update.message.mid);

        if (receivedDmIds.indexOf(sentDmId) === -1) {
          console.log('this DM doesnt match our test DM - race was probably won by listener');
          return;
        }

        const expectedUpdate = {
          'raw': update.raw,
          'sender': {
            'id': senderCredentials.access_token.split('-')[0]
          },
          'recipient': {
            'id': bot.idStr
          },
          'timestamp': (new Date(update.raw.direct_message.created_at)).getTime(),
          'message': {
            'mid': sentDmId,
            'seq': null,
            'text': 'Party & Bullshit'
          }
        };
        expect(update).to.deep.equal(expectedUpdate);

        done();
      });

      after(function (done) {
        console.log('removing DM:', sentDmId);

        const params = { id: sentDmId, twit_options: { retry: true } };
        twitSender.post('direct_messages/destroy', params, function (err, reply) {
          assert(!err, err);
          assert.equal(reply.id, sentDmId);
          done();
        });
      });
    });
  });

  describe('twitter #__formatUpdate(rawUpdate)', function () {

    let bot;
    before(function () {
      bot = new TwitterBot(settings);
    });

    it('should format a twitter text only message in the expected way', function() {
      const rawUpdate = twitterIncomingDms.textOnly;
      const expectedUpdate = {
        raw: rawUpdate,
        sender: {
          id: rawUpdate.direct_message.sender_id_str
        },
        recipient: {
          id: rawUpdate.direct_message.recipient_id_str
        },
        timestamp: (new Date(rawUpdate.direct_message.created_at)).getTime(),
        message: {
          mid: rawUpdate.direct_message.id_str,
          seq: null,
          text: "Party & Bullshit"
        }
      };

      const formattedUpdate = bot.__formatUpdate(rawUpdate);

      expect(formattedUpdate).to.deep.equal(expectedUpdate);
    });

    it('should format a twitter photo message update in the expected way', function() {
      const rawUpdate = twitterIncomingDms.imageOnly;
      const expectedUpdate = {
        raw: rawUpdate,
        sender: {
          id: rawUpdate.direct_message.sender_id_str
        },
        recipient: {
          id: rawUpdate.direct_message.recipient_id_str
        },
        timestamp: (new Date(rawUpdate.direct_message.created_at)).getTime(),
        message: {
          mid: rawUpdate.direct_message.id_str,
          seq: null,
          attachments: [
            {
              type: 'image',
              payload: {
                url: rawUpdate.direct_message.entities.media[0].media_url_https
              }
            }
          ]
        }
      };

      const formattedUpdate = bot.__formatUpdate(rawUpdate);

      expect(formattedUpdate).to.deep.equal(expectedUpdate);
    });

    it('should format a twitter photo with text message update in the expected way', function() {
      const rawUpdate = twitterIncomingDms.imageWithText;
      const expectedUpdate = {
        raw: rawUpdate,
        sender: {
          id: rawUpdate.direct_message.sender_id_str
        },
        recipient: {
          id: rawUpdate.direct_message.recipient_id_str
        },
        timestamp: (new Date(rawUpdate.direct_message.created_at)).getTime(),
        message: {
          mid: rawUpdate.direct_message.id_str,
          seq: null,
          text: "Party & Bullshit",
          attachments: [
            {
              type: 'image',
              payload: {
                url: rawUpdate.direct_message.entities.media[0].media_url_https
              }
            }
          ]
        }
      };

      const formattedUpdate = bot.__formatUpdate(rawUpdate);

      expect(formattedUpdate).to.deep.equal(expectedUpdate);
    });

    it('should format a twitter video message update in the expected way', function() {
      const rawUpdate = twitterIncomingDms.videoOnly;
      const expectedUpdate = {
        raw: rawUpdate,
        sender: {
          id: rawUpdate.direct_message.sender_id_str
        },
        recipient: {
          id: rawUpdate.direct_message.recipient_id_str
        },
        timestamp: (new Date(rawUpdate.direct_message.created_at)).getTime(),
        message: {
          mid: rawUpdate.direct_message.id_str,
          seq: null,
          attachments: [
            {
              type: 'video',
              payload: {
                url: rawUpdate.direct_message.entities.media[0].video_info.variants[4].url
              }
            }
          ]
        }
      };

      const formattedUpdate = bot.__formatUpdate(rawUpdate);

      expect(formattedUpdate).to.deep.equal(expectedUpdate);
    });

    it('should format a twitter update with video, image and text in the expected way', function() {
      const rawUpdate = twitterIncomingDms.videoWithImageWithText;
      const expectedUpdate = {
        raw: rawUpdate,
        sender: {
          id: rawUpdate.direct_message.sender_id_str
        },
        recipient: {
          id: rawUpdate.direct_message.recipient_id_str
        },
        timestamp: (new Date(rawUpdate.direct_message.created_at)).getTime(),
        message: {
          mid: rawUpdate.direct_message.id_str,
          seq: null,
          text: "Party & Bullshit",
          attachments: [
            {
              type: 'video',
              payload: {
                url: rawUpdate.direct_message.entities.media[0].video_info.variants[4].url
              }
            },
            {
              type: 'image',
              payload: {
                url: rawUpdate.direct_message.entities.media[1].media_url_https
              }
            }
          ]
        }
      };

      const formattedUpdate = bot.__formatUpdate(rawUpdate);

      expect(formattedUpdate).to.deep.equal(expectedUpdate);
    });

    it('should format a twitter gif message update in the expected way', function() {
      const rawUpdate = twitterIncomingDms.gifOnly;
      const expectedUpdate = {
        raw: rawUpdate,
        sender: {
          id: rawUpdate.direct_message.sender_id_str
        },
        recipient: {
          id: rawUpdate.direct_message.recipient_id_str
        },
        timestamp: (new Date(rawUpdate.direct_message.created_at)).getTime(),
        message: {
          mid: rawUpdate.direct_message.id_str,
          seq: null,
          attachments: [
            {
              type: 'video',
              payload: {
                url: rawUpdate.direct_message.entities.media[0].video_info.variants[0].url
              }
            }
          ]
        }
      };

      const formattedUpdate = bot.__formatUpdate(rawUpdate);

      expect(formattedUpdate).to.deep.equal(expectedUpdate);
    });
  });
});
<commit_msg>Add retries to twitter bo tests on timeout prone test<commit_after>'use strict';

const assert = require('chai').assert;
const expect = require('chai').expect;
require('chai').should();
const _ = require('lodash');
const TwitterBot = require('../../lib').botTypes.TwitterBot;
const Twit = require('twit');
const config = require('../config.js');
const twitterIncomingDms = require('./twitter_incoming_dms');

const botCredentials = config.twitterCredentials1;
const senderCredentials = config.twitterCredentials2;

describe('Twitter Bot tests', function() {
  const settings = {
    credentials: botCredentials
  };

  describe('#constructor()', function() {
    it('should throw an error when authToken credential is missing', function(done) {
      const badSettings = _.cloneDeep(settings);
      badSettings.credentials.consumerKey = undefined;
      expect(() => new TwitterBot(badSettings)).to.throw(
        'ERROR: bots of type \'twitter\' are expected to have \'consumerKey\' credentials');
      done();
    });
  });

  describe('receiving updates', function () {

    this.retries(4);
    // TwitterBot is linked to an account that can
    // receive updates from anyone.
    // In this instance, "anyone" is the sender.
    let twitSender;
    let bot;
    before(function () {
      twitSender = new Twit(senderCredentials);
      bot = new TwitterBot(settings);
    });

    it('should emit an update event to the bot object when ' +
       'receiving a text update', function (done) {
      this.retries(4);
      this.timeout(6000);
      let sentDmId;
      let receivedDmIds = [];

      // this can actually happen multiple times if the stream
      // ever has to reconnect because the connection is lost somehow
      bot.userStream.on('connected', function() {
        // this is the text message that twitSender sends to our bot
        const textMessageToSend = {
          user_id: bot.idStr,
          text: 'Party & Bullshit',
          twit_options: {
            retry: true
          }
        };

        twitSender.post('direct_messages/new', textMessageToSend, function (err, reply) {
          assert(!err, err);
          assert(reply.id_str);
          // we will check this dm against the reply recieved in the message event
          sentDmId = reply.id_str;

          console.log('successfully posted DM:', reply.text, reply.id_str);
          // Lost the race to 'update' listener which was able to push
          // the DmId into receivedDmIds. Finish test now as a consequence.
          if (receivedDmIds.indexOf(sentDmId) !== -1) {
            done();
          }
        });
      });

      bot.once('update', function (update) {
        receivedDmIds.push(update.message.mid);
        console.log('got DM event. id:', update.message.mid);

        if (receivedDmIds.indexOf(sentDmId) === -1) {
          console.log('this DM doesnt match our test DM - race was probably won by listener');
          return;
        }

        const expectedUpdate = {
          'raw': update.raw,
          'sender': {
            'id': senderCredentials.access_token.split('-')[0]
          },
          'recipient': {
            'id': bot.idStr
          },
          'timestamp': (new Date(update.raw.direct_message.created_at)).getTime(),
          'message': {
            'mid': sentDmId,
            'seq': null,
            'text': 'Party & Bullshit'
          }
        };
        expect(update).to.deep.equal(expectedUpdate);

        done();
      });

      after(function (done) {
        console.log('removing DM:', sentDmId);

        const params = { id: sentDmId, twit_options: { retry: true } };
        twitSender.post('direct_messages/destroy', params, function (err, reply) {
          assert(!err, err);
          assert.equal(reply.id, sentDmId);
          done();
        });
      });
    });
  });

  describe('twitter #__formatUpdate(rawUpdate)', function () {

    let bot;
    before(function () {
      bot = new TwitterBot(settings);
    });

    it('should format a twitter text only message in the expected way', function() {
      const rawUpdate = twitterIncomingDms.textOnly;
      const expectedUpdate = {
        raw: rawUpdate,
        sender: {
          id: rawUpdate.direct_message.sender_id_str
        },
        recipient: {
          id: rawUpdate.direct_message.recipient_id_str
        },
        timestamp: (new Date(rawUpdate.direct_message.created_at)).getTime(),
        message: {
          mid: rawUpdate.direct_message.id_str,
          seq: null,
          text: "Party & Bullshit"
        }
      };

      const formattedUpdate = bot.__formatUpdate(rawUpdate);

      expect(formattedUpdate).to.deep.equal(expectedUpdate);
    });

    it('should format a twitter photo message update in the expected way', function() {
      const rawUpdate = twitterIncomingDms.imageOnly;
      const expectedUpdate = {
        raw: rawUpdate,
        sender: {
          id: rawUpdate.direct_message.sender_id_str
        },
        recipient: {
          id: rawUpdate.direct_message.recipient_id_str
        },
        timestamp: (new Date(rawUpdate.direct_message.created_at)).getTime(),
        message: {
          mid: rawUpdate.direct_message.id_str,
          seq: null,
          attachments: [
            {
              type: 'image',
              payload: {
                url: rawUpdate.direct_message.entities.media[0].media_url_https
              }
            }
          ]
        }
      };

      const formattedUpdate = bot.__formatUpdate(rawUpdate);

      expect(formattedUpdate).to.deep.equal(expectedUpdate);
    });

    it('should format a twitter photo with text message update in the expected way', function() {
      const rawUpdate = twitterIncomingDms.imageWithText;
      const expectedUpdate = {
        raw: rawUpdate,
        sender: {
          id: rawUpdate.direct_message.sender_id_str
        },
        recipient: {
          id: rawUpdate.direct_message.recipient_id_str
        },
        timestamp: (new Date(rawUpdate.direct_message.created_at)).getTime(),
        message: {
          mid: rawUpdate.direct_message.id_str,
          seq: null,
          text: "Party & Bullshit",
          attachments: [
            {
              type: 'image',
              payload: {
                url: rawUpdate.direct_message.entities.media[0].media_url_https
              }
            }
          ]
        }
      };

      const formattedUpdate = bot.__formatUpdate(rawUpdate);

      expect(formattedUpdate).to.deep.equal(expectedUpdate);
    });

    it('should format a twitter video message update in the expected way', function() {
      const rawUpdate = twitterIncomingDms.videoOnly;
      const expectedUpdate = {
        raw: rawUpdate,
        sender: {
          id: rawUpdate.direct_message.sender_id_str
        },
        recipient: {
          id: rawUpdate.direct_message.recipient_id_str
        },
        timestamp: (new Date(rawUpdate.direct_message.created_at)).getTime(),
        message: {
          mid: rawUpdate.direct_message.id_str,
          seq: null,
          attachments: [
            {
              type: 'video',
              payload: {
                url: rawUpdate.direct_message.entities.media[0].video_info.variants[4].url
              }
            }
          ]
        }
      };

      const formattedUpdate = bot.__formatUpdate(rawUpdate);

      expect(formattedUpdate).to.deep.equal(expectedUpdate);
    });

    it('should format a twitter update with video, image and text in the expected way', function() {
      const rawUpdate = twitterIncomingDms.videoWithImageWithText;
      const expectedUpdate = {
        raw: rawUpdate,
        sender: {
          id: rawUpdate.direct_message.sender_id_str
        },
        recipient: {
          id: rawUpdate.direct_message.recipient_id_str
        },
        timestamp: (new Date(rawUpdate.direct_message.created_at)).getTime(),
        message: {
          mid: rawUpdate.direct_message.id_str,
          seq: null,
          text: "Party & Bullshit",
          attachments: [
            {
              type: 'video',
              payload: {
                url: rawUpdate.direct_message.entities.media[0].video_info.variants[4].url
              }
            },
            {
              type: 'image',
              payload: {
                url: rawUpdate.direct_message.entities.media[1].media_url_https
              }
            }
          ]
        }
      };

      const formattedUpdate = bot.__formatUpdate(rawUpdate);

      expect(formattedUpdate).to.deep.equal(expectedUpdate);
    });

    it('should format a twitter gif message update in the expected way', function() {
      const rawUpdate = twitterIncomingDms.gifOnly;
      const expectedUpdate = {
        raw: rawUpdate,
        sender: {
          id: rawUpdate.direct_message.sender_id_str
        },
        recipient: {
          id: rawUpdate.direct_message.recipient_id_str
        },
        timestamp: (new Date(rawUpdate.direct_message.created_at)).getTime(),
        message: {
          mid: rawUpdate.direct_message.id_str,
          seq: null,
          attachments: [
            {
              type: 'video',
              payload: {
                url: rawUpdate.direct_message.entities.media[0].video_info.variants[0].url
              }
            }
          ]
        }
      };

      const formattedUpdate = bot.__formatUpdate(rawUpdate);

      expect(formattedUpdate).to.deep.equal(expectedUpdate);
    });
  });
});
<|endoftext|>


<commit_before>/**
 * Created by Peter on 2017. 3. 20..
 */

"use strict";

var req = require('request');
var async = require('async');
var keys = require('../../config/config').keyString;

function faRequester(){
    var self = this;

    self.base_url = 'http://apitest.foreca.net/';
    self.defRetryCount = 5;
    return this;
}

faRequester.prototype.getForecast = function(geocode, key, callback){
    var self = this;

    if(!geocode.lat || !geocode.lon){
        callback(new Error('FC> there is no coordinate'), {isSuccess: false});
        return;
    }

    // ex. http://apitest.foreca.net/?lon=24.934&lat=60.1755&key={keys}&format=json
    //     http://apitest.foreca.net/?lon=39.66&lat=116.4&key=ur5zUllH1EHKMxr63Nh36Txjc&format=json
    var url = self.base_url + '?lon=' + geocode.lat + '&lat=' + geocode.lon + '&key=' + key + '&format=json';

    log.info(url);
    self.getData(url, self.defRetryCount, function(err, res){
        if(err){
            callback(err, {isSuccess: false});
            return;
        }
        if(res != undefined){
            res.isSuccess = true;
        }
        callback(err, res);
        return;
    });
};

faRequester.prototype.collect = function(list, key, callback){
    var self = this;

    async.mapSeries(list,
        function(item, cb){
            if(!item.lat || !item.lon){
                cb(new Error('FC> there is no coordinate'), {isSuccess: false});
                return;
            }
            var url = self.base_url + '?lon=' + item.lon + '&lat=' + item.lat + '&key=' + key + '&format=json';

            self.getData(url, self.defRetryCount, function(err, res){
                if(err){
                    cb(err, {isSuccess: false, lat: item.lat, lon: item.lon});
                    return;
                }
                res.isSuccess = true;
                res.lat = item.lat;
                res.lon = item.lon;
                cb(err, res);
                return;
            });
        },
        function(err, results){
            if(err){
                log.error(err);
                log.error('FC> There are failed items in the result list');
            }
            callback(err, results);
        }
    );

    return this;
};

faRequester.prototype.get = function(url, option, callback){
    return req.get(url, option, callback);
};

faRequester.prototype.getData = function(url, retryCount, callback){
    var self = this;

    log.silly('FC> get data : ', url);
    self.get(url, {timeout: 1000 * 5}, function(err, response, body){
        if(err) {
            log.warn(err);
            if((err.code === "ECONNRESET" || err.code === "ETIMEDOUT") && retryCount > 0){
                log.warn('FC> Retry to get caused by' + err.code + ' : ', retryCount);
                return self.getData(url, retryCount-- , callback);
            }
            if(callback){
                callback(err);
            }
            return;
        }
        var statusCode = response.statusCode;

        if(statusCode === 404 || statusCode === 403){
            log.debug('FC> ERROR!!! StatusCode : ', statusCode);
            if(callback){
                callback(1);
            }
            return;
        }

        var result = JSON.parse(body);
        //log.info(result);
        if(callback){
            callback(err, result);
        }
    });
};

module.exports = faRequester;
<commit_msg>#1488 remove comment<commit_after>/**
 * Created by Peter on 2017. 3. 20..
 */

"use strict";

var req = require('request');
var async = require('async');
var keys = require('../../config/config').keyString;

function faRequester(){
    var self = this;

    self.base_url = 'http://apitest.foreca.net/';
    self.defRetryCount = 5;
    return this;
}

faRequester.prototype.getForecast = function(geocode, key, callback){
    var self = this;

    if(!geocode.lat || !geocode.lon){
        callback(new Error('FC> there is no coordinate'), {isSuccess: false});
        return;
    }

    // ex. http://apitest.foreca.net/?lon=24.934&lat=60.1755&key={keys}&format=json
    var url = self.base_url + '?lon=' + geocode.lat + '&lat=' + geocode.lon + '&key=' + key + '&format=json';

    log.info(url);
    self.getData(url, self.defRetryCount, function(err, res){
        if(err){
            callback(err, {isSuccess: false});
            return;
        }
        if(res != undefined){
            res.isSuccess = true;
        }
        callback(err, res);
        return;
    });
};

faRequester.prototype.collect = function(list, key, callback){
    var self = this;

    async.mapSeries(list,
        function(item, cb){
            if(!item.lat || !item.lon){
                cb(new Error('FC> there is no coordinate'), {isSuccess: false});
                return;
            }
            var url = self.base_url + '?lon=' + item.lon + '&lat=' + item.lat + '&key=' + key + '&format=json';

            self.getData(url, self.defRetryCount, function(err, res){
                if(err){
                    cb(err, {isSuccess: false, lat: item.lat, lon: item.lon});
                    return;
                }
                res.isSuccess = true;
                res.lat = item.lat;
                res.lon = item.lon;
                cb(err, res);
                return;
            });
        },
        function(err, results){
            if(err){
                log.error(err);
                log.error('FC> There are failed items in the result list');
            }
            callback(err, results);
        }
    );

    return this;
};

faRequester.prototype.get = function(url, option, callback){
    return req.get(url, option, callback);
};

faRequester.prototype.getData = function(url, retryCount, callback){
    var self = this;

    log.silly('FC> get data : ', url);
    self.get(url, {timeout: 1000 * 5}, function(err, response, body){
        if(err) {
            log.warn(err);
            if((err.code === "ECONNRESET" || err.code === "ETIMEDOUT") && retryCount > 0){
                log.warn('FC> Retry to get caused by' + err.code + ' : ', retryCount);
                return self.getData(url, retryCount-- , callback);
            }
            if(callback){
                callback(err);
            }
            return;
        }
        var statusCode = response.statusCode;

        if(statusCode === 404 || statusCode === 403){
            log.debug('FC> ERROR!!! StatusCode : ', statusCode);
            if(callback){
                callback(1);
            }
            return;
        }

        var result = JSON.parse(body);
        //log.info(result);
        if(callback){
            callback(err, result);
        }
    });
};

module.exports = faRequester;
<|endoftext|>


<commit_before>Ext.namespace('Kwc.Directories.Item.Directory');
Kwc.Directories.Item.Directory.TabsPanel = Ext.extend(Kwf.Binding.ProxyPanel,
{
    initComponent: function()
    {
        this.layout = 'border';

        this.grid = new Kwf.Auto.GridPanel({
            controllerUrl: this.controllerUrl,
            region: 'west',
            width: this.width,
            split: true
        });

        if (this.componentPlugins) {
            this.plugins = [ ];
            this.componentPlugins.each(function(v) {
                var pluginClass = eval(v.pluginClass);
                var plugin = new pluginClass(v);
                this.plugins.push(plugin);
            }, this);
        }

        var editPanels = [];
        if (!this.hideDetailsController) {
            this.detailsForm = Ext.ComponentMgr.create({
                xtype: this.detailsXtype,
                controllerUrl: this.detailsControllerUrl,
                title: trlKwf('Details')
            });
            this.grid.addBinding(this.detailsForm);
            editPanels.push(this.detailsForm);
        }

        this.contentEditComponents.each(function(ec) {
            editPanels.push(Kwf.Binding.AbstractPanel.createFormOrComponentPanel(
                this.componentConfigs, ec, {}, this.grid
            ));
        }, this);

        var tabs = new Ext.TabPanel({
            region: 'center',
            activeTab: 0,
            items: editPanels
        });
        this.proxyItem = this.grid;
        this.items = [this.grid, tabs];

        Kwc.Directories.Item.Directory.TabsPanel.superclass.initComponent.call(this);
    },
    applyBaseParams: function(baseParams) {
        if (baseParams.id) delete baseParams.id;
        if (this.detailsForm) this.detailsForm.setBaseParams(baseParams);
        return Kwc.Directories.Item.Directory.TabsPanel.superclass.applyBaseParams.apply(this, arguments);
    },
    setBaseParams : function(baseParams) {
        if (baseParams.id) delete baseParams.id;
        if (this.detailsForm) this.detailsForm.setBaseParams(baseParams);
        return Kwc.Directories.Item.Directory.TabsPanel.superclass.setBaseParams.apply(this, arguments);
    }

});

Ext.reg('kwc.directories.item.directory.tabs', Kwc.Directories.Item.Directory.TabsPanel);
<commit_msg>aloww adding gridconfig for directory-tabspanel<commit_after>Ext.namespace('Kwc.Directories.Item.Directory');
Kwc.Directories.Item.Directory.TabsPanel = Ext.extend(Kwf.Binding.ProxyPanel,
{
    initComponent: function()
    {
        this.layout = 'border';

        this.grid = new Kwf.Auto.GridPanel(Ext.applyIf({
            controllerUrl: this.controllerUrl,
            region: 'west',
            width: this.width,
            split: true
        }, this.gridConfig));

        if (this.componentPlugins) {
            this.plugins = [ ];
            this.componentPlugins.each(function(v) {
                var pluginClass = eval(v.pluginClass);
                var plugin = new pluginClass(v);
                this.plugins.push(plugin);
            }, this);
        }

        var editPanels = [];
        if (!this.hideDetailsController) {
            this.detailsForm = Ext.ComponentMgr.create({
                xtype: this.detailsXtype,
                controllerUrl: this.detailsControllerUrl,
                title: trlKwf('Details')
            });
            this.grid.addBinding(this.detailsForm);
            editPanels.push(this.detailsForm);
        }

        this.contentEditComponents.each(function(ec) {
            editPanels.push(Kwf.Binding.AbstractPanel.createFormOrComponentPanel(
                this.componentConfigs, ec, {}, this.grid
            ));
        }, this);

        var tabs = new Ext.TabPanel({
            region: 'center',
            activeTab: 0,
            items: editPanels
        });
        this.proxyItem = this.grid;
        this.items = [this.grid, tabs];

        Kwc.Directories.Item.Directory.TabsPanel.superclass.initComponent.call(this);
    },
    applyBaseParams: function(baseParams) {
        if (baseParams.id) delete baseParams.id;
        if (this.detailsForm) this.detailsForm.setBaseParams(baseParams);
        return Kwc.Directories.Item.Directory.TabsPanel.superclass.applyBaseParams.apply(this, arguments);
    },
    setBaseParams : function(baseParams) {
        if (baseParams.id) delete baseParams.id;
        if (this.detailsForm) this.detailsForm.setBaseParams(baseParams);
        return Kwc.Directories.Item.Directory.TabsPanel.superclass.setBaseParams.apply(this, arguments);
    }

});

Ext.reg('kwc.directories.item.directory.tabs', Kwc.Directories.Item.Directory.TabsPanel);
<|endoftext|>


<commit_before>import React from 'react';
import Sound from 'react-sound';
import PlayerControls from './PlayerControls';
import SongSelector from './SongSelector';
import songs from './songs';

export default class Example extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      currentSong: songs[0],
      position: 0,
      volume: 100,
      playStatus: Sound.status.PLAYING
    };
  }

  render() {
    const { volume } = this.state;

    return

      <SongSelector
        songs={songs}
        selectedSong={this.state.currentSong}
        onSongSelected={this.handleSongSelected.bind(this)} />
      {this.state.currentSong && this.renderCurrentSong()}
      <PlayerControls
        playStatus={this.state.playStatus}
        onPlay={() => this.setState({playStatus: Sound.status.PLAYING})}
        onPause={() => this.setState({playStatus: Sound.status.PAUSED})}
        onResume={() => this.setState({playStatus: Sound.status.PLAYING})}
        onStop={() => this.setState({playStatus: Sound.status.STOPPED, position: 0})}
        onSeek={position => this.setState({ position })}
        onVolumeUp={() => this.setState({volume: volume >= 100 ? volume : volume+10})}
        onVolumeDown={() => this.setState({volume: volume <= 0 ? volume : volume-10})}
        duration={this.state.currentSong ? this.state.currentSong.duration : 0}
        position={this.state.position} />
      {this.state.currentSong &&
        <Sound
          url={this.state.currentSong.url}
          playStatus={this.state.playStatus}
          playFromPosition={this.state.position}
          volume={this.state.volume}
          onLoading={({bytesLoaded, bytesTotal}) => console.log(`${bytesLoaded / bytesTotal * 100}% loaded`)}
          onPlaying={({position}) => console.log(position)}
          onFinishedPlaying={() => this.setState({playStatus: Sound.status.STOPPED})} />}

;
  }

  getStatusText() {
    switch(this.state.playStatus) {
      case Sound.status.PLAYING:
        return 'playing';
      case Sound.status.PAUSED:
        return 'paused';
      case Sound.status.STOPPED:
        return 'stopped';
      default:
        return '(unknown)';
    }
  }

  renderCurrentSong() {
    return

      Current song {this.state.currentSong.title}. Song is {this.getStatusText()}

;
  }

  handleSongSelected(song) {
    this.setState({currentSong: song, position: 0});
  }
}
<commit_msg>Use destructured volume prop in example player<commit_after>import React from 'react';
import Sound from 'react-sound';
import PlayerControls from './PlayerControls';
import SongSelector from './SongSelector';
import songs from './songs';

export default class Example extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      currentSong: songs[0],
      position: 0,
      volume: 100,
      playStatus: Sound.status.PLAYING
    };
  }

  render() {
    const { volume } = this.state;

    return

      <SongSelector
        songs={songs}
        selectedSong={this.state.currentSong}
        onSongSelected={this.handleSongSelected.bind(this)} />
      {this.state.currentSong && this.renderCurrentSong()}
      <PlayerControls
        playStatus={this.state.playStatus}
        onPlay={() => this.setState({playStatus: Sound.status.PLAYING})}
        onPause={() => this.setState({playStatus: Sound.status.PAUSED})}
        onResume={() => this.setState({playStatus: Sound.status.PLAYING})}
        onStop={() => this.setState({playStatus: Sound.status.STOPPED, position: 0})}
        onSeek={position => this.setState({ position })}
        onVolumeUp={() => this.setState({volume: volume >= 100 ? volume : volume+10})}
        onVolumeDown={() => this.setState({volume: volume <= 0 ? volume : volume-10})}
        duration={this.state.currentSong ? this.state.currentSong.duration : 0}
        position={this.state.position} />
      {this.state.currentSong &&
        <Sound
          url={this.state.currentSong.url}
          playStatus={this.state.playStatus}
          playFromPosition={this.state.position}
          volume={volume}
          onLoading={({bytesLoaded, bytesTotal}) => console.log(`${bytesLoaded / bytesTotal * 100}% loaded`)}
          onPlaying={({position}) => console.log(position)}
          onFinishedPlaying={() => this.setState({playStatus: Sound.status.STOPPED})} />}

;
  }

  getStatusText() {
    switch(this.state.playStatus) {
      case Sound.status.PLAYING:
        return 'playing';
      case Sound.status.PAUSED:
        return 'paused';
      case Sound.status.STOPPED:
        return 'stopped';
      default:
        return '(unknown)';
    }
  }

  renderCurrentSong() {
    return

      Current song {this.state.currentSong.title}. Song is {this.getStatusText()}

;
  }

  handleSongSelected(song) {
    this.setState({currentSong: song, position: 0});
  }
}
<|endoftext|>


<commit_before>// head = document.querySelector('head');

// number = document.createElement('script');
// number.src = 'https://rawgit.com/home-labs/do-rails/master/lib/assets/javascripts/do/helpers/number.js';

// head.appendChild(number);

// Para futuras implementações, como retorno de fatores primos de determinado valor, podemos usar um algorítmo determinístico como esses dois abaixo
// É interessante calcular somente os fatores primos que caberiam para determinado número, ao invés de testar com todo número natural até chegar a ele, e salvá-los em i como um array, e no if calcular o retorno 0 somente para estes. Devendo o próprio número ser retornado caso não haja quantidade de múltiplos maior que 1, pois 1 e ele mesmo não deverão entrar no vetor para ser calculado.
// Mas como calcular esse números primos? No braço?

// http://pt.wikipedia.org/wiki/Crivo_de_Erat%C3%B3stenes
// http://pt.wikipedia.org/wiki/Teste_de_primalidade_AKS

Array.prototype.occurrences = function(comparison) {
  var
    _arr = this;
    count = 0;
  ;

  _arr.map(function(item) {
    if(item == comparison) { count++; }
  });
  return count;
}

Array.prototype.firstMultiple = function() {
  var
    _arr = this,
    _factors = []
  ;

  _arr.map(function(item) {
    _factors.push(item.firstMultiple());
  });
  return (_factors.sort())[0];
}

Number.prototype.firstMultiple = function() {
  return Number.firstMultiple(this);
}

Number.firstMultiple = function(n) {

  var
    i = 1,
    count = 1,
    m = 1
  ;

  if (n < 0){
    n *= -1;
  }

  while(i <= n && count < 3) {
    if(n%i === 0) {
      count++;
      m = i;
    }
    i++;

  }
  return m;
}
<commit_msg>Update number.js<commit_after>// head = document.querySelector('head');

// number = document.createElement('script');
// number.src = 'https://rawgit.com/home-labs/do-rails/master/lib/assets/javascripts/do/helpers/number.js';

// head.appendChild(number);

// Para futuras implementações, como retorno de fatores primos de determinado valor, podemos usar um algorítmo determinístico como esses dois abaixo
// É interessante calcular somente os fatores primos que caberiam para determinado número, ao invés de testar com todo número natural até chegar a ele, e salvá-los em i como um array, e no if calcular o retorno 0 somente para estes. Devendo o próprio número ser retornado caso não haja quantidade de múltiplos maior que 1, pois 1 e ele mesmo não deverão entrar no vetor para ser calculado.
// Mas como calcular esse números primos? No braço?

// http://pt.wikipedia.org/wiki/Crivo_de_Erat%C3%B3stenes
// http://pt.wikipedia.org/wiki/Teste_de_primalidade_AKS

Array.prototype.occurrences = function(comparison) {
  var
    _arr = this.sort();
    count = 0;
  ;

  // talvez fosse interessante não usar o map para otimizar, testando até determinado item se diferente do próximo
  _arr.map(function(item) {
    if(item == comparison) { count++; }
  });
  return count;
}

Array.prototype.firstMultiple = function() {
  var
    _arr = this,
    _factors = []
  ;

  _arr.map(function(item) {
    _factors.push(item.firstMultiple());
  });
  return (_factors.sort())[0];
}

Number.prototype.firstMultiple = function() {
  return Number.firstMultiple(this);
}

Number.firstMultiple = function(n) {

  var
    i = 1,
    count = 1,
    m = 1
  ;

  if (n < 0){
    n *= -1;
  }

  while(i <= n && count < 3) {
    if(n%i === 0) {
      count++;
      m = i;
    }
    i++;

  }
  return m;
}
<|endoftext|>


<commit_before>wax = wax || {};
wax.g = wax.g || {};

wax.g.interaction = function() {
    var dirty = false, _grid, map;
    var tileloadListener = null,
        idleListener = null;

    function setdirty() { dirty = true; }

    function grid() {

        if (!dirty && _grid) {
            return _grid;
        } else {
            _grid = [];
            var zoom = map.getZoom();
            var mapOffset = wax.u.offset(map.getDiv());
            var get = function(mapType) {
                if (!mapType || !mapType.interactive) return;
                for (var key in mapType.cache) {
                    if (key.split('/')[0] != zoom) continue;
                    var tileOffset = wax.u.offset(mapType.cache[key]);
                    _grid.push([
                        tileOffset.top,
                        tileOffset.left,
                        mapType.cache[key]
                    ]);
                }
            };
            // Iterate over base mapTypes and overlayMapTypes.
            for (var i in map.mapTypes) get(map.mapTypes[i]);
            map.overlayMapTypes.forEach(get);
        }
        return _grid;
    }

    function attach(x) {
        if (!arguments.length) return map;
        map = x;
        tileloadListener = google.maps.event.addListener(map, 'tileloaded',
            setdirty);
        idleListener = google.maps.event.addListener(map, 'idle',
            setdirty);
    }

    function detach(x) {
        if(tileloadListener)
          google.maps.event.removeListener(tileloadListener);
        if(idleListener)
          google.maps.event.removeListener(idleListener);
    }

    return wax.interaction()
        .attach(attach)
        .detach(detach)
        .discardTouchMove(true)
        .parent(function() {
          return map.getDiv();
        })
        .grid(grid);
};
<commit_msg>fixed race condition with google maps layers and interactivity<commit_after>wax = wax || {};
wax.g = wax.g || {};

wax.g.interaction = function() {
    var dirty = false, _grid, map, interactionEnabled = false;
    var tileloadListener = null,
        idleListener = null;

    function setdirty() { dirty = true; }

    function grid() {

        // when interaction is enabled there should be grid tiles
        if (!dirty && _grid && (_grid.length > 0 || !interactionEnabled)) {
            return _grid;
        } else {
            _grid = [];
            var zoom = map.getZoom();
            var mapOffset = wax.u.offset(map.getDiv());
            var get = function(mapType) {
                if (!mapType || !mapType.interactive) return;
                interactionEnabled = true;
                for (var key in mapType.cache) {
                    if (key.split('/')[0] != zoom) continue;
                    var tileOffset = wax.u.offset(mapType.cache[key]);
                    _grid.push([
                        tileOffset.top,
                        tileOffset.left,
                        mapType.cache[key]
                    ]);
                }
            };
            // Iterate over base mapTypes and overlayMapTypes.
            for (var i in map.mapTypes) get(map.mapTypes[i]);
            map.overlayMapTypes.forEach(get);
        }
        return _grid;
    }

    function attach(x) {
        if (!arguments.length) return map;
        map = x;
        tileloadListener = google.maps.event.addListener(map, 'tileloaded',
            setdirty);
        idleListener = google.maps.event.addListener(map, 'idle',
            setdirty);
    }

    function detach(x) {
        if(tileloadListener)
          google.maps.event.removeListener(tileloadListener);
        if(idleListener)
          google.maps.event.removeListener(idleListener);
    }

    return wax.interaction()
        .attach(attach)
        .detach(detach)
        .discardTouchMove(true)
        .parent(function() {
          return map.getDiv();
        })
        .grid(grid);
};
<|endoftext|>


<commit_before>import _ from 'lodash';
import ejs from 'ejs';
import config from '../config';
import logger from '../logger';
import mfaRule from './rules/slack-mfa-rule';

const compileRule = (rule) =>
  ejs.render(rule, {
    extensionUrl: config('PUBLIC_WT_URL').replace(/\/$/g, ''),
    mongoConnectionString: config('MONGO_CONNECTION_STRING'),
    signingSecret: config('EXTENSION_SECRET'),
    updateTime: () => new Date().toISOString()
  });

module.exports.remove = (auth0) => {
  const ruleName = 'slack-mfa-rule';
  return auth0
  .rules
  .getAll()
  .then(rules => {
    const rule = _.find(rules, { name: ruleName });
    if (rule) {
      auth0.rules.delete({ id: rule.id });
    }
  })
  .then(() => {
    logger.debug('Slack MFA rule deleted.');
  })
  .catch((err) => {
    logger.debug('Error creating Slack MFA rule.');
    logger.error(err);
  });
};

module.exports.provision = (auth0) => {
  const ruleName = 'slack-mfa-rule';
  return auth0
    .rules
    .getAll()
    .then(rules => {
      const payload = {
        name: ruleName,
        script: compileRule(mfaRule)
      };

      const rule = _.find(rules, { name: ruleName });
      if (rule) {
        return auth0.rules.update({ id: rule.id }, payload);
      }

      return auth0.rules.create({ stage: 'login_success', ...payload });
    })
    .then(() => {
      logger.debug('Slack MFA rule deployed.');
    })
    .catch((err) => {
      logger.debug('Error creating Slack MFA rule.');
      logger.error(err);
    });
};
<commit_msg>Fixing rule template bug<commit_after>import _ from 'lodash';
import ejs from 'ejs';
import config from '../config';
import logger from '../logger';
import mfaRule from './rules/slack-mfa-rule';

const compileRule = (rule) =>
  ejs.render(rule, {
    extensionUrl: config('PUBLIC_WT_URL').replace(/\/$/g, ''),
    mongoConnectionString: config('MONGO_CONNECTION_STRING'),
    signingSecret: config('EXTENSION_SECRET'),
    updateTime: () => new Date().toISOString()
  });

module.exports.remove = (auth0) => {
  const ruleName = 'slack-mfa-rule';
  return auth0
  .rules
  .getAll()
  .then(rules => {
    const rule = _.find(rules, { name: ruleName });
    if (rule) {
      auth0.rules.delete({ id: rule.id });
    }
  })
  .then(() => {
    logger.debug('Slack MFA rule deleted.');
  })
  .catch((err) => {
    logger.debug('Error creating Slack MFA rule.');
    logger.error(err);
  });
};

module.exports.provision = (auth0) => {
  const ruleName = 'slack-mfa-rule';
  return auth0
    .rules
    .getAll()
    .then(rules => {
      console.log(rules);
      const payload = {
        name: ruleName,
        script: compileRule(mfaRule)
      };

      const rule = _.find(rules, { name: ruleName });
      if (rule) {
        return auth0.rules.update({ id: rule.id }, payload);
      }

      return auth0.rules.create({ stage: 'login_success', ...payload });
    })
    .then(() => {
      logger.debug('Slack MFA rule deployed.');
    })
    .catch((err) => {
      logger.debug('Error creating Slack MFA rule.');
      logger.error(err);
    });
};
<|endoftext|>


<commit_before>import Ember from 'ember';

var names = "Ingeborg Jim Rigoberto Ian Wei Otilia Wendell Chasity " +
  "Billi Chester Omer Paulene Hiram Laurice Deneen Chuck Petrina Lamonica " +
  "Roy Ai Marsha Kiana Tamar Fabiola Travis Mazie Dawna Fe Tommye Jene".split(' ');

var surnames = "Brown Smith Patel Jones Williams Johnson Taylor Thomas " +
  "Roberts Khan Lewis Jackson Clarke James Phillips Wilson Ali Mason " +
  "Mitchell Rose Davis Davies Rodríguez Cox Alexander" +
  "Stewart Quinn Robinson Murphy Graham".split(' ');

var cities = ["Shanghai", "Karachi", "Beijing", "Tianjin", "Istanbul", "Lagos",
  "Guangzhou", "Mumbai", "Moscow", "Dhaka", "Cairo", "São Paulo",
  "Lahore", "Shenzhen", "Seoul", "Jakarta", "Kinshasa", "Tokyo", "Mexico City",
  "Lima", "New York City", "Bengaluru", "London", "Bangkok", "Dongguan",
  "Nanjing", "Tehran", "Shenyang", "Ahmedabad", "Bogotá"];

var generateContent = function (recordsCount) {
  var ret = [];
  for (let i = 1; i <= recordsCount; i++) {
    ret.push(Ember.Object.create({
      id: i,
      firstName: names[i],
      lastName: surnames[i],
      age: Math.floor(Math.random() * (50 - 18)) + 18,
      city: cities[i],
      cityWithHtml: '' + cities[i] + ''
    }));
  }
  return ret;
};

export default Ember.Controller.extend({

  example1: {
    title: 'Common table',
    content: generateContent(10),
    columns: [
      {
        propertyName: 'id',
        title: 'ID'
      },
      {
        propertyName: 'firstName',
        title: 'First Name'
      },
      {
        propertyName: 'lastName',
        title: 'Last Name'
      },
      {
        propertyName: 'city',
        title: 'City'
      }
    ]
  },

  example2: {
    title: 'Table without footer',
    content: generateContent(10),
    columns: [
      {
        propertyName: 'id',
        title: 'ID'
      },
      {
        propertyName: 'firstName',
        title: 'First Name'
      },
      {
        propertyName: 'lastName',
        title: 'Last Name'
      },
      {
        propertyName: 'city',
        title: 'City'
      }
    ],
    showTableFooter: false
  },

  example3: {
    title: 'Table with HTML in the cell',
    content: generateContent(30),
    columns: [
      {
        propertyName: 'id',
        title: 'ID'
      },
      {
        propertyName: 'firstName',
        title: 'First Name'
      },
      {
        propertyName: 'lastName',
        title: 'Last Name'
      },
      {
        propertyName: 'cityWithHtml',
        title: 'City',
        isHtml: true
      }
    ]
  },

  example4: {
    title: 'Table with custom sort column',
    message: 'Click on `Last Name` triggers sorting by `First Name`',
    content: generateContent(30),
    columns: [
      {
        propertyName: 'id',
        title: 'ID'
      },
      {
        propertyName: 'firstName',
        title: 'First Name'
      },
      {
        propertyName: 'lastName',
        title: 'Last Name',
        sortBy: 'firstName'
      },
      {
        propertyName: 'city',
        title: 'City'
      }
    ]
  }

});<commit_msg>Fix dummy app<commit_after>import Ember from 'ember';

var names = "Ingeborg Jim Rigoberto Ian Wei Otilia Wendell Chasity " +
  "Billi Chester Omer Paulene Hiram Laurice Deneen Chuck Petrina Lamonica " +
  "Roy Ai Marsha Kiana Tamar Fabiola Travis Mazie Dawna Fe Tommye Jene".split(' ');

var surnames = "Brown Smith Patel Jones Williams Johnson Taylor Thomas " +
  "Roberts Khan Lewis Jackson Clarke James Phillips Wilson Ali Mason " +
  "Mitchell Rose Davis Davies Rodríguez Cox Alexander" +
  "Stewart Quinn Robinson Murphy Graham".split(' ');

var cities = ["Shanghai", "Karachi", "Beijing", "Tianjin", "Istanbul", "Lagos",
  "Guangzhou", "Mumbai", "Moscow", "Dhaka", "Cairo", "São Paulo",
  "Lahore", "Shenzhen", "Seoul", "Jakarta", "Kinshasa", "Tokyo", "Mexico City",
  "Lima", "New York City", "Bengaluru", "London", "Bangkok", "Dongguan",
  "Nanjing", "Tehran", "Shenyang", "Ahmedabad", "Bogotá"];

var generateContent = function (recordsCount) {
  var ret = Ember.A([]);
  for (let i = 1; i <= recordsCount; i++) {
    ret.push(Ember.Object.create({
      id: i,
      firstName: names[i],
      lastName: surnames[i],
      age: Math.floor(Math.random() * (50 - 18)) + 18,
      city: cities[i],
      cityWithHtml: '' + cities[i] + ''
    }));
  }
  return ret;
};

export default Ember.Controller.extend({

  example1: {
    title: 'Common table',
    content: generateContent(10),
    columns: Ember.A([
      Ember.Object.create({
        propertyName: 'id',
        title: 'ID'
      }),
      Ember.Object.create({
        propertyName: 'firstName',
        title: 'First Name'
      }),
      Ember.Object.create({
        propertyName: 'lastName',
        title: 'Last Name'
      }),
      Ember.Object.create({
        propertyName: 'city',
        title: 'City'
      })
    ])
  },

  example2: {
    title: 'Table without footer',
    content: generateContent(10),
    columns: Ember.A([
      Ember.Object.create({
        propertyName: 'id',
        title: 'ID'
      }),
      Ember.Object.create({
        propertyName: 'firstName',
        title: 'First Name'
      }),
      Ember.Object.create({
        propertyName: 'lastName',
        title: 'Last Name'
      }),
      Ember.Object.create({
        propertyName: 'city',
        title: 'City'
      })
    ]),
    showTableFooter: false
  },

  example3: {
    title: 'Table with HTML in the cell',
    content: generateContent(30),
    columns: Ember.A([
      Ember.Object.create({
        propertyName: 'id',
        title: 'ID'
      }),
      Ember.Object.create({
        propertyName: 'firstName',
        title: 'First Name'
      }),
      Ember.Object.create({
        propertyName: 'lastName',
        title: 'Last Name'
      }),
      Ember.Object.create({
        propertyName: 'cityWithHtml',
        title: 'City',
        isHtml: true
      })
    ])
  },

  example4: {
    title: 'Table with custom sort column',
    message: 'Click on `Last Name` triggers sorting by `First Name`',
    content: generateContent(30),
    columns: Ember.A([
      Ember.Object.create({
        propertyName: 'id',
        title: 'ID'
      }),
      Ember.Object.create({
        propertyName: 'firstName',
        title: 'First Name'
      }),
      Ember.Object.create({
        propertyName: 'lastName',
        title: 'Last Name',
        sortBy: 'firstName'
      }),
      Ember.Object.create({
        propertyName: 'city',
        title: 'City'
      })
    ])
  }

});<|endoftext|>