<commit_before>"use strict";
var helper = require("./../../helper");
var BaseManager = require('module-toolkit').BaseManager;
var BateeqModels = require('bateeq-models');
var map = BateeqModels.map;
var ItemManager = require("../../../src/managers/master/item-manager");
var FinishGoodManager = require("../../../src/managers/master/finished-goods-manager");
var InventoryManager = require("../../../src/managers/inventory/inventory-manager");

class ReportManagerDataUtil extends BaseManager {

    getExpeditionData(data) {
        return new Promise((resolve, reject) => {
            helper.getDb()
                .then(db => {
                    data(db)
                        .then(result => {
                            resolve();
                        })
                        .catch(e => {
                            reject(e);
                        });
                })
                .catch(e => {
                    reject(e);
                });
        });
    }

    getInventoryData(data) {
        return new Promise((resolve, reject) => {
            helper.getDb()
                .then(db => {
                    this.db = db;
                    this.collection = this.db.use(map.master.Item);
                    data(db)
                        .then(result => {
                            var finishGoodManager = new FinishGoodManager(db, 'unit-test');
                            var itemManager = new ItemManager(db, 'unit-test');
                            var inventoryManager = new InventoryManager(db, 'unit-test');
                            var Inventory = require('bateeq-models').inventory.Inventory;
                            var storage = result.storages["UT-ST1"];
                            var item = result.items["UT-AV2"];
                            var quantity = 10;

                            var FinishedItem = require('bateeq-models').master.FinishedGoods;
                            var finishedItem = null;

                            if (!item.article.realizationOrder) {
                                finishedItem = new FinishedItem(item);
                                finishedItem.article = {
                                    "realizationOrder": "G78564343"
                                };
                            } else {
                                finishedItem = item;
                            }

                            itemManager.update(finishedItem)
                                .then(id => {
                                    this.getSingleById(id)
                                        .then(result => {
                                            inventoryManager
                                                .getByStorageIdAndItemId(storage._id, result._id)
                                                .then(inventoryData => {
                                                    if (inventoryData.item.article) {
                                                        resolve(inventoryData);
                                                    } else {

                                                        if (inventoryData._id) {
                                                            inventoryData.storageId = storage._id;
                                                            inventoryData.storage = storage;
                                                            inventoryData.itemId = result._id;
                                                            inventoryData.item = result;
                                                            inventoryData.quantity = quantity;

                                                            inventoryManager.update(inventoryData)
                                                                .then(id => {
                                                                    inventoryManager.getSingleById(id)
                                                                        .then(inventoryData => {
                                                                            resolve(inventoryData);
                                                                        }).catch(e => {
                                                                            reject(e);
                                                                        });
                                                                });
                                                        } else {
                                                            var inventory = new Inventory();
                                                            inventory.storageId = storage._id;
                                                            inventory.storage = storage;
                                                            inventory.itemId = result._id;
                                                            inventory.item = result;
                                                            inventory.quantity = quantity;

                                                            inventoryManager.create(inventory)
                                                                .then(id => {
                                                                    inventoryManager.getSingleById(id)
                                                                        .then(inventoryData => {
                                                                            resolve(inventoryData);
                                                                        }).catch(e => {
                                                                            reject(e);
                                                                        });
                                                                });
                                                        }
                                                    }
                                                }).catch(e => {
                                                    reject(e);
                                                })
                                        })
                                        .catch(e => {
                                            reject(e);
                                        });
                                });
                        }).catch(e => {
                            reject(e);
                        });
                }).catch(e => {
                    reject(e);
                });
        });
    }
}
module.exports = new ReportManagerDataUtil();<commit_msg>update report manager data utils<commit_after>"use strict";
var helper = require("./../../helper");
var BaseManager = require('module-toolkit').BaseManager;
var BateeqModels = require('bateeq-models');
var map = BateeqModels.map;
var ItemManager = require("../../../src/managers/master/item-manager");
var FinishGoodManager = require("../../../src/managers/master/finished-goods-manager");
var InventoryManager = require("../../../src/managers/inventory/inventory-manager");

class ReportManagerDataUtil extends BaseManager {

    getExpeditionData(data) {
        return new Promise((resolve, reject) => {
            helper.getDb()
                .then(db => {
                    data(db)
                        .then(result => {
                            resolve();
                        })
                        .catch(e => {
                            reject(e);
                        });
                })
                .catch(e => {
                    reject(e);
                });
        });
    }

    getInventoryData(data) {
        return new Promise((resolve, reject) => {
            helper.getDb()
                .then(db => {
                    this.db = db;
                    this.collection = this.db.use(map.master.Item);
                    data(db)
                        .then(result => {
                            var finishGoodManager = new FinishGoodManager(db, 'unit-test');
                            var itemManager = new ItemManager(db, 'unit-test');
                            var inventoryManager = new InventoryManager(db, 'unit-test');
                            var Inventory = require('bateeq-models').inventory.Inventory;
                            var storage = result.storages["UT-ST1"];
                            var item = result.items["UT-AV2"];
                            var quantity = 10;

                            var FinishedItem = require('bateeq-models').master.FinishedGoods;
                            var finishedItem = null;

                            if (!item.article) {
                                finishedItem = new FinishedItem(item);
                                finishedItem.article = {
                                    "realizationOrder": "G78564343"
                                };
                            } else {
                                finishedItem = item;
                            }

                            itemManager.update(finishedItem)
                                .then(id => {
                                    this.getSingleById(id)
                                        .then(result => {
                                            inventoryManager
                                                .getByStorageIdAndItemId(storage._id, result._id)
                                                .then(inventoryData => {
                                                    if (inventoryData.item.article) {
                                                        resolve(inventoryData);
                                                    } else {

                                                        if (inventoryData._id) {
                                                            inventoryData.storageId = storage._id;
                                                            inventoryData.storage = storage;
                                                            inventoryData.itemId = result._id;
                                                            inventoryData.item = result;
                                                            inventoryData.quantity = quantity;

                                                            inventoryManager.update(inventoryData)
                                                                .then(id => {
                                                                    inventoryManager.getSingleById(id)
                                                                        .then(inventoryData => {
                                                                            resolve(inventoryData);
                                                                        }).catch(e => {
                                                                            reject(e);
                                                                        });
                                                                });
                                                        } else {
                                                            var inventory = new Inventory();
                                                            inventory.storageId = storage._id;
                                                            inventory.storage = storage;
                                                            inventory.itemId = result._id;
                                                            inventory.item = result;
                                                            inventory.quantity = quantity;

                                                            inventoryManager.create(inventory)
                                                                .then(id => {
                                                                    inventoryManager.getSingleById(id)
                                                                        .then(inventoryData => {
                                                                            resolve(inventoryData);
                                                                        }).catch(e => {
                                                                            reject(e);
                                                                        });
                                                                });
                                                        }
                                                    }
                                                }).catch(e => {
                                                    reject(e);
                                                })
                                        })
                                        .catch(e => {
                                            reject(e);
                                        });
                                });
                        }).catch(e => {
                            reject(e);
                        });
                }).catch(e => {
                    reject(e);
                });
        });
    }
}
module.exports = new ReportManagerDataUtil();<|endoftext|>


<commit_before>module.exports = [
  {
    reg: /(eave)$/i,
    repl: {
      pr: '$1s',
      pa: '$1d',
      gr: 'eaving',
      ar: '$1r'
    }
  },
  {
    reg: /(ink)$/i,
    repl: {
      pr: '$1s',
      pa: 'unk',
      gr: '$1ing',
      ar: '$1er'
    }
  },
  {
    reg: /(end)$/i,
    repl: {
      pr: '$1s',
      pa: 'ent',
      gr: '$1ing',
      ar: '$1er'
    }
  },
  {
    reg: /(ide)$/i,
    repl: {
      pr: '$1s',
      pa: 'ode',
      gr: 'iding',
      ar: 'ider'
    }
  },
  {
    reg: /(ake)$/i,
    repl: {
      pr: '$1s',
      pa: 'ook',
      gr: 'aking',
      ar: '$1r'
    }
  },
  {
    reg: /(eed)$/i,
    repl: {
      pr: '$1s',
      pa: '$1ed',
      gr: '$1ing',
      ar: '$1er'
    }
  },

  {
    reg: /(e)(ep)$/i,
    repl: {
      pr: '$1$2s',
      pa: '$1pt',
      gr: '$1$2ing',
      ar: '$1$2er'
    }
  }, {
    reg: /(a[tg]|i[zn]|ur|nc|gl|is)e$/i,
    repl: {
      pr: '$1es',
      pa: '$1ed',
      gr: '$1ing',
      prt: '$1en'
    }
  }, {
    reg: /([i|f|rr])y$/i,
    repl: {
      pr: '$1ies',
      pa: '$1ied',
      gr: '$1ying'
    }
  }, {
    reg: /([td]er)$/i,
    repl: {
      pr: '$1s',
      pa: '$1ed',
      gr: '$1ing'
    }
  }, {
    reg: /([bd]l)e$/i,
    repl: {
      pr: '$1es',
      pa: '$1ed',
      gr: '$1ing'
    }
  }, {
    reg: /(ish|tch|ess)$/i,
    repl: {
      pr: '$1es',
      pa: '$1ed',
      gr: '$1ing'
    }
  }, {
    reg: /(ion|end|e[nc]t)$/i,
    repl: {
      pr: '$1s',
      pa: '$1ed',
      gr: '$1ing'
    }
  }, {
    reg: /(om)e$/i,
    repl: {
      pr: '$1es',
      pa: 'ame',
      gr: '$1ing'
    }
  }, {
    reg: /([aeiu])([pt])$/i,
    repl: {
      pr: '$1$2s',
      pa: '$1$2',
      gr: '$1$2$2ing'
    }
  }, {
    reg: /(er)$/i,
    repl: {
      pr: '$1s',
      pa: '$1ed',
      gr: '$1ing'
    }
  }, {
    reg: /(en)$/i,
    repl: {
      pr: '$1s',
      pa: '$1ed',
      gr: '$1ing'
    },
  },
  {
    reg: /(..)(ow)$/i,
    repl: {
      pr: '$1$2s',
      pa: '$1ew',
      gr: '$1$2ing',
      prt: '$1$2n'
    }
  },
  {
    reg: /(..)([cs]h)$/i,
    repl: {
      pr: '$1$2es',
      pa: '$1$2ed',
      gr: '$1$2ing'
    },
  },
  {
    reg: /([^aeiou][ou])(g|d)$/i,
    repl: {
      pr: '$1$2s',
      pa: '$1$2$2ed',
      gr: '$1$2$2ing'
    },
  },
  {
    reg: /([^aeiou][aeiou])(b|t|p|m)$/i,
    repl: {
      pr: '$1$2s',
      pa: '$1$2$2ed',
      gr: '$1$2$2ing'
    },
  },
];
<commit_msg>support zz for #292<commit_after>module.exports = [
  {
    reg: /(eave)$/i,
    repl: {
      pr: '$1s',
      pa: '$1d',
      gr: 'eaving',
      ar: '$1r'
    }
  },
  {
    reg: /(ink)$/i,
    repl: {
      pr: '$1s',
      pa: 'unk',
      gr: '$1ing',
      ar: '$1er'
    }
  },
  {
    reg: /(end)$/i,
    repl: {
      pr: '$1s',
      pa: 'ent',
      gr: '$1ing',
      ar: '$1er'
    }
  },
  {
    reg: /(ide)$/i,
    repl: {
      pr: '$1s',
      pa: 'ode',
      gr: 'iding',
      ar: 'ider'
    }
  },
  {
    reg: /(ake)$/i,
    repl: {
      pr: '$1s',
      pa: 'ook',
      gr: 'aking',
      ar: '$1r'
    }
  },
  {
    reg: /(eed)$/i,
    repl: {
      pr: '$1s',
      pa: '$1ed',
      gr: '$1ing',
      ar: '$1er'
    }
  },

  {
    reg: /(e)(ep)$/i,
    repl: {
      pr: '$1$2s',
      pa: '$1pt',
      gr: '$1$2ing',
      ar: '$1$2er'
    }
  }, {
    reg: /(a[tg]|i[zn]|ur|nc|gl|is)e$/i,
    repl: {
      pr: '$1es',
      pa: '$1ed',
      gr: '$1ing',
      prt: '$1en'
    }
  }, {
    reg: /([i|f|rr])y$/i,
    repl: {
      pr: '$1ies',
      pa: '$1ied',
      gr: '$1ying'
    }
  }, {
    reg: /([td]er)$/i,
    repl: {
      pr: '$1s',
      pa: '$1ed',
      gr: '$1ing'
    }
  }, {
    reg: /([bd]l)e$/i,
    repl: {
      pr: '$1es',
      pa: '$1ed',
      gr: '$1ing'
    }
  }, {
    reg: /(ish|tch|ess)$/i,
    repl: {
      pr: '$1es',
      pa: '$1ed',
      gr: '$1ing'
    }
  }, {
    reg: /(ion|end|e[nc]t)$/i,
    repl: {
      pr: '$1s',
      pa: '$1ed',
      gr: '$1ing'
    }
  }, {
    reg: /(om)e$/i,
    repl: {
      pr: '$1es',
      pa: 'ame',
      gr: '$1ing'
    }
  }, {
    reg: /([aeiu])([pt])$/i,
    repl: {
      pr: '$1$2s',
      pa: '$1$2',
      gr: '$1$2$2ing'
    }
  }, {
    reg: /(er)$/i,
    repl: {
      pr: '$1s',
      pa: '$1ed',
      gr: '$1ing'
    }
  }, {
    reg: /(en)$/i,
    repl: {
      pr: '$1s',
      pa: '$1ed',
      gr: '$1ing'
    },
  },
  {
    reg: /(..)(ow)$/i,
    repl: {
      pr: '$1$2s',
      pa: '$1ew',
      gr: '$1$2ing',
      prt: '$1$2n'
    }
  },
  {
    reg: /(..)([cs]h)$/i,
    repl: {
      pr: '$1$2es',
      pa: '$1$2ed',
      gr: '$1$2ing'
    },
  },
  {
    reg: /([^aeiou][ou])(g|d)$/i,
    repl: {
      pr: '$1$2s',
      pa: '$1$2$2ed',
      gr: '$1$2$2ing'
    },
  },
  {
    reg: /([^aeiou][aeiou])(b|t|p|m)$/i,
    repl: {
      pr: '$1$2s',
      pa: '$1$2$2ed',
      gr: '$1$2$2ing'
    },
  },
  {
    reg: /([aeiou]zz)$/i,
    repl: {
      pr: '$1es',
      pa: '$1ed',
      gr: '$1ing'
    }
  }
];
<|endoftext|>


<commit_before>{
  bodyStyle     : 'padding:5px 5px 0',
  autoScroll    : true,
  fieldDefaults : { labelWidth : 150 },

  defaults       : {
    anchor       : '-20', // to leave some space for the scrollbar
    listeners    : {
      // On "return" key, submit the form
      specialkey : {
        fn : function(field, event){
          if (event.getKey() == 13) this.ownerCt.onApply();
        }
      }
    }
  },

  initComponent: function(){
    // passing config options to BasicForm is possible via initialConfig only
    // see Ext.form.Panel documentation
    this.initialConfig = {
      // form tracks it's default field values so they can be reset()
      trackResetOnLoad: true,
    }

    if (!this.bbar && !this.readOnly) this.bbar = {xtype: 'toolbar'}; // an empty bbar by default, so that we can dynamically add buttons

    // Custom error reader. We don't use it to process form values, but rather to normalize the response from the server in case of "real" (iframe) form submit.
    ErrorReader = function(){};

    ErrorReader.prototype.read = function(xhr) {
      var unescapeHTML = function(str) {
        return str.replace(/</g,'<').replace(/>/g,'>').replace(/&/g,'&');
      }
      xhr.responseText = unescapeHTML(xhr.responseText.replace(/
/, "").replace("
", ""));
      return {records: [], success: true};
    };

    this.initialConfig.errorReader = new ErrorReader();

    // Now let Ext.form.Form do the rest
    this.callParent(arguments);

    // To inform the parent about the apply event
    this.addEvents('apply', 'cancel');
  },

  afterRender: function(){
    this.callParent();

    // have a record to be displayed?
    if (this.record) { this.setFormValues(this.record); }

    // render in display mode?
    if (this.locked || this.readOnly) this.setReadonlyMode(true);
  },

  onEdit: function(){
    this.setReadonlyMode(false);
  },

  onCancel: function(){
    this.getForm().reset();
    this.setReadonlyMode(true, true);
  },

  updateToolbar: function(){
    var tbar = this.child('toolbar');

    if ( this.inReadonlyMode ) {
      //   if the form in readonly mode, remove "Apply" and "Cancel"
      //   buttons from toolbar and add "Edit" button
      var buttonToRemove = tbar.child("button[name='apply']");
      if ( buttonToRemove ) {
        tbar.remove( buttonToRemove );
      }

      var buttonToRemove = tbar.child("button[name='cancel']");
      if ( buttonToRemove ) {
        tbar.remove( buttonToRemove );
      }

      tbar.add( this.actions.edit );

    } else {
      // if the form editable, remove "edit" button and
      // insert "apply" and "cancel" instead

      var buttonIndex = tbar.items.findIndex("name", "edit");
      var buttonToRemove = tbar.items.getAt(buttonIndex);
      if (buttonToRemove) {
        tbar.remove(buttonToRemove);
      }
      tbar.insert( buttonIndex, this.actions.cancel );
      tbar.insert( buttonIndex, this.actions.apply );
    }

    tbar.doLayout();
  },

  onApply: function() {
    if (this.fireEvent('apply', this)) {
      var values = this.getForm().getValues();
      for (var fieldName in values) {
        var field = this.getForm().findField(fieldName);

        // TODO: move the following checks to the server side (through the :display_only option)

        // do not submit values from disabled fields
        if (!field || field.disabled) {
          delete values[fieldName];
        }

        // do not submit values from read-only association fields
        if (field
          && field.name.indexOf("__") !== -1
          && (field.readOnly || !field.isXType('combobox'))
          && (!field.nestedAttribute) // except for "nested attributes"
        ) {
          delete values[fieldName];
        }

        // do not submit values from displayfields
        if (field.isXType('displayfield')) {
          delete values[fieldName];
        }

        // do not submit displayOnly fields
        if (field.displayOnly) {
          delete values[fieldName];
        }
      }

      // loading mask
      this.setLoading(true);

      // We must use a different approach when the form is multipart, as we can't use the endpoint
      if (this.getForm().hasUpload()) {
        this.getForm().submit({ // normal submit
          url: this.endpointUrl("netzke_submit"),
          params: {
            data: Ext.encode(values) // here are the correct values that may be different from display values
          },
          failure: function(form, action){
            var respObj = Ext.decode(action.response.responseText);
            delete respObj.success;
            this.netzkeBulkExecute(respObj);
            this.setLoading(false);
          },
          success: function(form, action) {
            var respObj = Ext.decode(action.response.responseText);
            delete respObj.success;
            this.netzkeBulkExecute(respObj);
          },
          scope: this
        });
      } else {
        this.netzkeSubmit(Ext.apply((this.baseParams || {}), { data:Ext.encode(values) }), function(){ this.setLoading(false); }, this);
      }
    }
    this.fireEvent('afterApply', this);
  },

  // called from the server
  onSubmitSuccess: function() {
    this.fireEvent("submitsuccess");
    if (this.mode == "lockable") this.setReadonlyMode(true);
    this.setLoading(false);
  },

  setFormValues: function(values){
    var assocValues = values.meta.associationValues || {};
    for (var assocFieldName in assocValues) {

      var assocField = this.getForm().getFields().filter('name', assocFieldName).first();
      if (assocField.isXType('combobox')) {
        // HACK: using private property 'store' here!
        assocField.store.loadData([[values[assocFieldName], assocValues[assocFieldName]]]);
        delete assocField.lastQuery; // force loading the store next time user clicks the trigger
      } else {
        assocField.setValue(assocValues[assocFieldName]);
        delete values[assocFieldName]; // we don't want this to be set once more below with setValues()
      }
    }

    this.getForm().setValues(values);
  },

  setReadonlyMode: function(onOff, cancel){
    if (this.inReadonlyMode == onOff) return;
    this.getForm().getFields().each(function(i){
      if (i.setReadonlyMode) i.setReadonlyMode(onOff);
    });

    // this.getForm().cleanDestroyed(); // because fields inside of composite fields are not auto-cleaned!
    this.doLayout();
    this.inReadonlyMode = onOff;
    if (this.mode == "lockable") this.updateToolbar();
  },

  // recursively extract field names
  extractFields: function(items){
    Ext.each(items, function(i){
      if (i.items) {this.extractFields(i.items);}
      else if (i.name) {this.fieldNames.push(i.name);}
    }, this);
  },

  applyFormErrors: function(errors) {
    var field;
    Ext.iterate(errors, function(fieldName, message){
      fieldName = fieldName.underscore();
      if ( field = this.getForm().findField(fieldName) || this.getForm().findField(fieldName.replace(/([a-z]+)([0-9])/g, '$1_$2'))) {
        field.markInvalid(message.join('
'));
      }
    }, this);
  }
}
<commit_msg>rename function that changed with 0.8<commit_after>{
  bodyStyle     : 'padding:5px 5px 0',
  autoScroll    : true,
  fieldDefaults : { labelWidth : 150 },

  defaults       : {
    anchor       : '-20', // to leave some space for the scrollbar
    listeners    : {
      // On "return" key, submit the form
      specialkey : {
        fn : function(field, event){
          if (event.getKey() == 13) this.ownerCt.onApply();
        }
      }
    }
  },

  initComponent: function(){
    // passing config options to BasicForm is possible via initialConfig only
    // see Ext.form.Panel documentation
    this.initialConfig = {
      // form tracks it's default field values so they can be reset()
      trackResetOnLoad: true,
    }

    if (!this.bbar && !this.readOnly) this.bbar = {xtype: 'toolbar'}; // an empty bbar by default, so that we can dynamically add buttons

    // Custom error reader. We don't use it to process form values, but rather to normalize the response from the server in case of "real" (iframe) form submit.
    ErrorReader = function(){};

    ErrorReader.prototype.read = function(xhr) {
      var unescapeHTML = function(str) {
        return str.replace(/</g,'<').replace(/>/g,'>').replace(/&/g,'&');
      }
      xhr.responseText = unescapeHTML(xhr.responseText.replace(/
/, "").replace("
", ""));
      return {records: [], success: true};
    };

    this.initialConfig.errorReader = new ErrorReader();

    // Now let Ext.form.Form do the rest
    this.callParent(arguments);

    // To inform the parent about the apply event
    this.addEvents('apply', 'cancel');
  },

  afterRender: function(){
    this.callParent();

    // have a record to be displayed?
    if (this.record) { this.setFormValues(this.record); }

    // render in display mode?
    if (this.locked || this.readOnly) this.setReadonlyMode(true);
  },

  onEdit: function(){
    this.setReadonlyMode(false);
  },

  onCancel: function(){
    this.getForm().reset();
    this.setReadonlyMode(true, true);
  },

  updateToolbar: function(){
    var tbar = this.child('toolbar');

    if ( this.inReadonlyMode ) {
      //   if the form in readonly mode, remove "Apply" and "Cancel"
      //   buttons from toolbar and add "Edit" button
      var buttonToRemove = tbar.child("button[name='apply']");
      if ( buttonToRemove ) {
        tbar.remove( buttonToRemove );
      }

      var buttonToRemove = tbar.child("button[name='cancel']");
      if ( buttonToRemove ) {
        tbar.remove( buttonToRemove );
      }

      tbar.add( this.actions.edit );

    } else {
      // if the form editable, remove "edit" button and
      // insert "apply" and "cancel" instead

      var buttonIndex = tbar.items.findIndex("name", "edit");
      var buttonToRemove = tbar.items.getAt(buttonIndex);
      if (buttonToRemove) {
        tbar.remove(buttonToRemove);
      }
      tbar.insert( buttonIndex, this.actions.cancel );
      tbar.insert( buttonIndex, this.actions.apply );
    }

    tbar.doLayout();
  },

  onApply: function() {
    if (this.fireEvent('apply', this)) {
      var values = this.getForm().getValues();
      for (var fieldName in values) {
        var field = this.getForm().findField(fieldName);

        // TODO: move the following checks to the server side (through the :display_only option)

        // do not submit values from disabled fields
        if (!field || field.disabled) {
          delete values[fieldName];
        }

        // do not submit values from read-only association fields
        if (field
          && field.name.indexOf("__") !== -1
          && (field.readOnly || !field.isXType('combobox'))
          && (!field.nestedAttribute) // except for "nested attributes"
        ) {
          delete values[fieldName];
        }

        // do not submit values from displayfields
        if (field.isXType('displayfield')) {
          delete values[fieldName];
        }

        // do not submit displayOnly fields
        if (field.displayOnly) {
          delete values[fieldName];
        }
      }

      // loading mask
      this.setLoading(true);

      // We must use a different approach when the form is multipart, as we can't use the endpoint
      if (this.getForm().hasUpload()) {
        this.getForm().submit({ // normal submit
          url: this.netzkeEndpointUrl("netzke_submit"),
          params: {
            data: Ext.encode(values) // here are the correct values that may be different from display values
          },
          failure: function(form, action){
            var respObj = Ext.decode(action.response.responseText);
            delete respObj.success;
            this.netzkeBulkExecute(respObj);
            this.setLoading(false);
          },
          success: function(form, action) {
            var respObj = Ext.decode(action.response.responseText);
            delete respObj.success;
            this.netzkeBulkExecute(respObj);
          },
          scope: this
        });
      } else {
        this.netzkeSubmit(Ext.apply((this.baseParams || {}), { data:Ext.encode(values) }), function(){ this.setLoading(false); }, this);
      }
    }
    this.fireEvent('afterApply', this);
  },

  // called from the server
  onSubmitSuccess: function() {
    this.fireEvent("submitsuccess");
    if (this.mode == "lockable") this.setReadonlyMode(true);
    this.setLoading(false);
  },

  setFormValues: function(values){
    var assocValues = values.meta.associationValues || {};
    for (var assocFieldName in assocValues) {

      var assocField = this.getForm().getFields().filter('name', assocFieldName).first();
      if (assocField.isXType('combobox')) {
        // HACK: using private property 'store' here!
        assocField.store.loadData([[values[assocFieldName], assocValues[assocFieldName]]]);
        delete assocField.lastQuery; // force loading the store next time user clicks the trigger
      } else {
        assocField.setValue(assocValues[assocFieldName]);
        delete values[assocFieldName]; // we don't want this to be set once more below with setValues()
      }
    }

    this.getForm().setValues(values);
  },

  setReadonlyMode: function(onOff, cancel){
    if (this.inReadonlyMode == onOff) return;
    this.getForm().getFields().each(function(i){
      if (i.setReadonlyMode) i.setReadonlyMode(onOff);
    });

    // this.getForm().cleanDestroyed(); // because fields inside of composite fields are not auto-cleaned!
    this.doLayout();
    this.inReadonlyMode = onOff;
    if (this.mode == "lockable") this.updateToolbar();
  },

  // recursively extract field names
  extractFields: function(items){
    Ext.each(items, function(i){
      if (i.items) {this.extractFields(i.items);}
      else if (i.name) {this.fieldNames.push(i.name);}
    }, this);
  },

  applyFormErrors: function(errors) {
    var field;
    Ext.iterate(errors, function(fieldName, message){
      fieldName = fieldName.underscore();
      if ( field = this.getForm().findField(fieldName) || this.getForm().findField(fieldName.replace(/([a-z]+)([0-9])/g, '$1_$2'))) {
        field.markInvalid(message.join('
'));
      }
    }, this);
  }
}
<|endoftext|>


<commit_before>//******************************************************************************//
//                                                                              //
//                                                         :::      ::::::::    //
//    app.js                                             :+:      :+:    :+:    //
//                                                     +:+ +:+         +:+      //
//    By: gtorresa <gtorresa@student.42.fr>          +#+  +:+       +#+         //
//                                                 +#+#+#+#+#+   +#+            //
//    Created: 2017/02/08 10:29:23 by gtorresa          #+#    #+#              //
//    Updated: 2017/02/08 15:29:23 by gtorresa         ###   ########.fr        //
//                                                                              //
//******************************************************************************//

var fs = require('fs');
var io = require('socket.io-client');
var crypto = require('crypto');
var exec = require('child_process').exec;
var network = require('network');
var Netmask = require('netmask').Netmask;

var options = JSON.parse(fs.readFileSync('options.json') || '{}');

var arp_table = {};
arp_table.name = options.hostname;
var scan_iface;
var token;
arp_table.children = [];

setTimeout(function(){
	start_app();

	setInterval(function(){
		make_cmd_arp(scan_iface, send_data_to_engine);
		console.log("scan_iface");
	}, 20000);
}, 3000);

function shutdown(signal, value) {
	console.log('server stopped by ' + signal);
	console.log('clean cookie: ' + token);
	fs.unlinkSync("/data/remote/cookies/" + token);
	process.exit(128 + value);
}

var signals = {
    'SIGINT': 2,
    'SIGTERM': 15
};

Object.keys(signals).forEach(function (signal) {
    process.on(signal, function () {
        shutdown(signal, signals[signal]);
    });
});

var socket;

crypto.randomBytes(48, function(ex, buf) {
    token = buf.toString('hex');
    fs.writeFileSync(
        "/data/remote/cookies/" + token,
        JSON.stringify({
            user: options.hostname,
			type: "network-remote",
            login : new Date()
        })
    );
    init_socket_io(token);
});

function init_socket_io(token) {

    socket = io.connect(options.engine_ip, {
        'port': options.dest_port,
        'secure': true,
        extraHeaders: {
            'Cookie': "AUTH_COOKIE=" + token + ";"
        }
    });

	console.log("io connect " + options.engine_ip + " port " + options.dest_port);

    socket.on('connect', function () {
        var arp_login = {
            hostname: arp_table.name,
            type: "arp_client",
            token: options.token
        };
        socket.emit("login", arp_login);
        console.log("Login: ", arp_login);
    });

    socket.on('return_register', function (token) {
        if (token.valid)
        {
            options.token = token.id;
            fs.writeFileSync('options.json', JSON.stringify(options));
            console.log("Registered on engine");
        }
        else
        {
            console.log("Wrong token");
        }
        process.exit(0);
    });

    if (process.argv.length >= 4 && process.argv[2] == "register")
    {
        socket.emit("register_scan_arp", process.argv[3]);
        console.log("Register on engine");
    }
}

function start_app()
{
	network.get_interfaces_list(function(err, obj) {
		if(err)
		{
			console.log("Error: ", err);
			console.log("obj: ", obj);
			process.exit(1);
		}
		else
		{
			scan_iface = obj;
			make_cmd_arp(obj, send_data_to_engine)
		}
	});
}

function convert_digit(mask)
{
	var res = 0;
	var b2_mask = mask.toString(2);
	for (var key in b2_mask)
	{
		if (b2_mask[key] == 1)
			res++;
	}
	return (res);
}

function convert_netmask(full_mask)
{
	var split_mask = full_mask.split('.');
	var digit_mask = 0;
	for (var key in split_mask)
	{
		digit_mask += convert_digit(parseInt(split_mask[key]));
	}
	return (digit_mask);
}

function make_cmd_arp(net_list, callback)
{
	list_cmd = [];
	for (var key in net_list)
	{
		if (net_list[key].ip_address && net_list[key].netmask)
		{
			var di_sub = convert_netmask(net_list[key].netmask);
			if (di_sub  < 24)
				di_sub = 24;
			var block = new Netmask(net_list[key].ip_address + '/' + di_sub);
			list_cmd.push({
				iface: net_list[key].name,
				net: net_list[key].ip_address,
				sub: net_list[key].netmask,
				di_sub: di_sub,
				base: block.base
			});

		}
	}
	scan_arp_network(0, list_cmd, list_cmd.length - 1, callback);
}

function scan_arp_network(pos, list_cmd, length, callback)
{
	var command = "sudo arp-scan -I " + list_cmd[pos].iface + " " + list_cmd[pos].base + "/" + list_cmd[pos].di_sub + " 172.17.0.1/32";
	console.log(command);
	exec(command, function(error_exec, stdout, stderr) {
		if (error_exec) {
			console.log("Error: ", error_exec);
		}
		else
		{
			var lines = stdout.split('\n');
			var iface = lines[0].match(/Interface: [0-z.,]+/g);
			var len_line = 0;
			var data = {};
			data.children = [];
			data.name = iface[0].replace('Interface: ', '').replace(',', '');
			lines.splice(0,2);
			for (var key in lines)
			{
				if (lines[key] == "" && len_line == 0)
					len_line = key;
			}
			lines.splice(len_line, lines.length);
			for (var key in lines)
			{
				var host_inf = lines[key].split('\t');
				data.children.push({ip: host_inf[0], mac: host_inf[1], vendor: host_inf[2]})
			}
			arp_table.children.push(data);
			if (pos >= length)
			{
				if (callback)
					groupe_mac_on_ip(arp_table, callback);
			}
			else
				scan_arp_network(pos + 1, list_cmd, length, callback)
		}
	});
}

function groupe_mac_on_ip(arp_table, callback)
{
	for(var key in arp_table.children)
	{
		var iface = {};
		iface.name = arp_table.children[key].name;
		iface.children = [];
		for (var key1 in arp_table.children[key].children)
		{
			var mac_find = true;
			for (var key2 in iface.children)
			{
				if (iface.children[key2].mac == arp_table.children[key].children[key1].mac ||
					iface.children[key2].ip == arp_table.children[key].children[key1].ip)
				{
					mac_find = false;
					iface.children[key2].mac.push(arp_table.children[key].children[key1].mac);
				}
			}
			if (mac_find && arp_table.children[key].children[key1].ip != "172.17.0.1")
			{
				var new_host = {};
				new_host.ip = arp_table.children[key].children[key1].ip;
				new_host.name = arp_table.children[key].children[key1].ip
				new_host.mac = [];
				new_host.docker = false;
				new_host.mac.push(arp_table.children[key].children[key1].mac);
				iface.children.push(new_host);
			}
		}
		for (var key1 in iface.children)
		{
			var counts = [];
			var duplicated = false;
			for(var i = 0; i <= iface.children[key1].mac.length; i++) {
				if(counts[iface.children[key1].mac[i]] === undefined) {
					counts[iface.children[key1].mac[i]] = 1;
				} else {
					duplicated = true;
				}
			}
			if (duplicated)
			{
				iface.children[key1].docker = true;
				iface.children[key1].mac = iface.children[key1].mac.filter(function(elem, index, self) {
					return index == self.indexOf(elem);
				});
			}
		}
		arp_table.children[key].children = iface.children;
	}

	get_host_name(0, 0, arp_table, callback);
}

function get_host_name(p_iface, p_host, arp_table, callback)
{
	if (arp_table.children[p_iface].children[p_host])
	{
		var command = "host " + arp_table.children[p_iface].children[p_host].ip;
		exec(command, function(error_exec, stdout, stderr) {
			var tab_dns_name = stdout.match(/domain name pointer ([0-z.-])+/g);
			var dns_name;
			if (tab_dns_name && tab_dns_name[0])
			{
				dns_name = tab_dns_name[0].replace("domain name pointer ", "");
				arp_table.children[p_iface].children[p_host].name = dns_name;
			}
			p_host++;
			if (arp_table.children[p_iface].children[p_host])
			{
				get_host_name(p_iface, p_host, arp_table, callback)
			}
			else
			{
				p_host = 0;
				p_iface++;
				if (arp_table.children[p_iface] && arp_table.children[p_iface].children[p_host])
					get_host_name(p_iface, p_host, arp_table, callback)
				else
					callback(arp_table);
			}
		});
	}
}

function send_data_to_engine(data)
{
	socket.emit("scan_arp", data);
	console.log("Send arp_data");
	delete arp_table.children;
	arp_table.children = [];
}<commit_msg>Fix auto remove cookie on register<commit_after>//******************************************************************************//
//                                                                              //
//                                                         :::      ::::::::    //
//    app.js                                             :+:      :+:    :+:    //
//                                                     +:+ +:+         +:+      //
//    By: gtorresa <gtorresa@student.42.fr>          +#+  +:+       +#+         //
//                                                 +#+#+#+#+#+   +#+            //
//    Created: 2017/02/08 10:29:23 by gtorresa          #+#    #+#              //
//    Updated: 2017/02/08 15:29:23 by gtorresa         ###   ########.fr        //
//                                                                              //
//******************************************************************************//

var fs = require('fs');
var io = require('socket.io-client');
var crypto = require('crypto');
var exec = require('child_process').exec;
var network = require('network');
var Netmask = require('netmask').Netmask;

var options = JSON.parse(fs.readFileSync('options.json') || '{}');

var arp_table = {};
arp_table.name = options.hostname;
var scan_iface;
var token;
arp_table.children = [];

setTimeout(function(){
	start_app();

	setInterval(function(){
		make_cmd_arp(scan_iface, send_data_to_engine);
		console.log("scan_iface");
	}, 20000);
}, 3000);

function shutdown(signal, value) {
	console.log('server stopped by ' + signal);
	console.log('clean cookie: ' + token);
	fs.unlinkSync("/data/remote/cookies/" + token);
	process.exit(128 + value);
}

var signals = {
    'SIGINT': 2,
    'SIGTERM': 15
};

Object.keys(signals).forEach(function (signal) {
    process.on(signal, function () {
        shutdown(signal, signals[signal]);
    });
});

var socket;

crypto.randomBytes(48, function(ex, buf) {
    token = buf.toString('hex');
    fs.writeFileSync(
        "/data/remote/cookies/" + token,
        JSON.stringify({
            user: options.hostname,
			type: "network-remote",
            login : new Date()
        })
    );
    init_socket_io(token);
});

function init_socket_io(token) {

    socket = io.connect(options.engine_ip, {
        'port': options.dest_port,
        'secure': true,
        extraHeaders: {
            'Cookie': "AUTH_COOKIE=" + token + ";"
        }
    });

	console.log("io connect " + options.engine_ip + " port " + options.dest_port);

    socket.on('connect', function () {
        var arp_login = {
            hostname: arp_table.name,
            type: "arp_client",
            token: options.token
        };
        socket.emit("login", arp_login);
        console.log("Login: ", arp_login);
    });

    socket.on('return_register', function (token) {
        if (token.valid)
        {
            options.token = token.id;
            fs.writeFileSync('options.json', JSON.stringify(options));
            console.log("Registered on engine");
        }
        else
        {
            console.log("Wrong token");
        }
        shutdown('SIGTERM', -128);
    });

    if (process.argv.length >= 4 && process.argv[2] == "register")
    {
        socket.emit("register_scan_arp", process.argv[3]);
        console.log("Register on engine");
    }
}

function start_app()
{
	network.get_interfaces_list(function(err, obj) {
		if(err)
		{
			console.log("Error: ", err);
			console.log("obj: ", obj);
			process.exit(1);
		}
		else
		{
			scan_iface = obj;
			make_cmd_arp(obj, send_data_to_engine)
		}
	});
}

function convert_digit(mask)
{
	var res = 0;
	var b2_mask = mask.toString(2);
	for (var key in b2_mask)
	{
		if (b2_mask[key] == 1)
			res++;
	}
	return (res);
}

function convert_netmask(full_mask)
{
	var split_mask = full_mask.split('.');
	var digit_mask = 0;
	for (var key in split_mask)
	{
		digit_mask += convert_digit(parseInt(split_mask[key]));
	}
	return (digit_mask);
}

function make_cmd_arp(net_list, callback)
{
	list_cmd = [];
	for (var key in net_list)
	{
		if (net_list[key].ip_address && net_list[key].netmask)
		{
			var di_sub = convert_netmask(net_list[key].netmask);
			if (di_sub  < 24)
				di_sub = 24;
			var block = new Netmask(net_list[key].ip_address + '/' + di_sub);
			list_cmd.push({
				iface: net_list[key].name,
				net: net_list[key].ip_address,
				sub: net_list[key].netmask,
				di_sub: di_sub,
				base: block.base
			});

		}
	}
	scan_arp_network(0, list_cmd, list_cmd.length - 1, callback);
}

function scan_arp_network(pos, list_cmd, length, callback)
{
	var command = "sudo arp-scan -I " + list_cmd[pos].iface + " " + list_cmd[pos].base + "/" + list_cmd[pos].di_sub + " 172.17.0.1/32";
	console.log(command);
	exec(command, function(error_exec, stdout, stderr) {
		if (error_exec) {
			console.log("Error: ", error_exec);
		}
		else
		{
			var lines = stdout.split('\n');
			var iface = lines[0].match(/Interface: [0-z.,]+/g);
			var len_line = 0;
			var data = {};
			data.children = [];
			data.name = iface[0].replace('Interface: ', '').replace(',', '');
			lines.splice(0,2);
			for (var key in lines)
			{
				if (lines[key] == "" && len_line == 0)
					len_line = key;
			}
			lines.splice(len_line, lines.length);
			for (var key in lines)
			{
				var host_inf = lines[key].split('\t');
				data.children.push({ip: host_inf[0], mac: host_inf[1], vendor: host_inf[2]})
			}
			arp_table.children.push(data);
			if (pos >= length)
			{
				if (callback)
					groupe_mac_on_ip(arp_table, callback);
			}
			else
				scan_arp_network(pos + 1, list_cmd, length, callback)
		}
	});
}

function groupe_mac_on_ip(arp_table, callback)
{
	for(var key in arp_table.children)
	{
		var iface = {};
		iface.name = arp_table.children[key].name;
		iface.children = [];
		for (var key1 in arp_table.children[key].children)
		{
			var mac_find = true;
			for (var key2 in iface.children)
			{
				if (iface.children[key2].mac == arp_table.children[key].children[key1].mac ||
					iface.children[key2].ip == arp_table.children[key].children[key1].ip)
				{
					mac_find = false;
					iface.children[key2].mac.push(arp_table.children[key].children[key1].mac);
				}
			}
			if (mac_find && arp_table.children[key].children[key1].ip != "172.17.0.1")
			{
				var new_host = {};
				new_host.ip = arp_table.children[key].children[key1].ip;
				new_host.name = arp_table.children[key].children[key1].ip
				new_host.mac = [];
				new_host.docker = false;
				new_host.mac.push(arp_table.children[key].children[key1].mac);
				iface.children.push(new_host);
			}
		}
		for (var key1 in iface.children)
		{
			var counts = [];
			var duplicated = false;
			for(var i = 0; i <= iface.children[key1].mac.length; i++) {
				if(counts[iface.children[key1].mac[i]] === undefined) {
					counts[iface.children[key1].mac[i]] = 1;
				} else {
					duplicated = true;
				}
			}
			if (duplicated)
			{
				iface.children[key1].docker = true;
				iface.children[key1].mac = iface.children[key1].mac.filter(function(elem, index, self) {
					return index == self.indexOf(elem);
				});
			}
		}
		arp_table.children[key].children = iface.children;
	}

	get_host_name(0, 0, arp_table, callback);
}

function get_host_name(p_iface, p_host, arp_table, callback)
{
	if (arp_table.children[p_iface].children[p_host])
	{
		var command = "host " + arp_table.children[p_iface].children[p_host].ip;
		exec(command, function(error_exec, stdout, stderr) {
			var tab_dns_name = stdout.match(/domain name pointer ([0-z.-])+/g);
			var dns_name;
			if (tab_dns_name && tab_dns_name[0])
			{
				dns_name = tab_dns_name[0].replace("domain name pointer ", "");
				arp_table.children[p_iface].children[p_host].name = dns_name;
			}
			p_host++;
			if (arp_table.children[p_iface].children[p_host])
			{
				get_host_name(p_iface, p_host, arp_table, callback)
			}
			else
			{
				p_host = 0;
				p_iface++;
				if (arp_table.children[p_iface] && arp_table.children[p_iface].children[p_host])
					get_host_name(p_iface, p_host, arp_table, callback)
				else
					callback(arp_table);
			}
		});
	}
}

function send_data_to_engine(data)
{
	socket.emit("scan_arp", data);
	console.log("Send arp_data");
	delete arp_table.children;
	arp_table.children = [];
}<|endoftext|>


<commit_before>'use strict';

const _ = require('lodash');
const turfCircle = require('@turf/circle');
const turfBbox = require('@turf/bbox');
const turfBboxPoly = require('@turf/bbox-polygon');
const turfTruncate = require('@turf/truncate');
const turfDestination = require('@turf/destination');
const turfDistance = require('@turf/distance');
const turfHelpers = require('@turf/helpers');

class MapboxCircle {
    set center(value) {
        this._center = value;
        this._updateCircle();
    }
    get center() {
        return this._center;
    }
    set radius(value) {
        this._radius = value;
        this._updateCircle();
    }
    get radius() {
        return this._radius;
    }
    set zoom(value) {
        this._zoom = value;
        this._updateCircle();
    }
    constructor(map, center, radius, options) {
        this.map = map;
        this._center = center; // Point geojson feature or array of [long,lat].
        this._radius = radius; // Radius of circle.
        this.statusEl = options.statusEl;
        this.properties = options.properties ? options.properties : {}; // JSON Object - property metadata for circle.

        this.units = 'meters';
        this._zoom = this.map.getZoom();

        this.steps = null; // No default steps
        this.circle_gj = null;
        this.controlPoints = null;

        // Bind event handlers.
        this.onMouseMove = this.onMouseMove.bind(this);
        this.onMouseDown = this.onMouseDown.bind(this);
        this.onHandleMouseDown = this.onHandleMouseDown.bind(this);
        this.onMouseUp = this.onMouseUp.bind(this);
        this.onHandleMouseUp = this.onHandleMouseUp.bind(this);
        this.onMove = this.onMove.bind(this);
        this.onHandleMove = this.onHandleMove.bind(this);
        this.onZoomEnd = this.onZoomEnd.bind(this);

        // Initialize circle object.
        this._updateCircle();
        this.addTo(map);
    }

    _updateSteps(zoom) {
        if (!zoom || zoom <= 0.1) zoom = 0.1;
        this.steps = (Math.sqrt(Math.trunc(this._radius * 0.25)) * zoom ^ 2);
    }

    _updateCircle() {
        this._updateSteps(this._zoom);
        this.circle_gj = turfCircle(this._center, this._radius, this.steps, this.units, this.properties);
        this.controlPoints = [
            turfDestination(this._center, this._radius, 0, this.units),
            turfDestination(this._center, this._radius, 90, this.units),
            turfDestination(this._center, this._radius, 180, this.units),
            turfDestination(this._center, this._radius, -90, this.units)
        ];
        if (this.statusEl) {
            this.statusEl.innerHTML = ('Center: ' + this._center + ' / Radius: ' + Math.trunc(this._radius) +
                                       ' meters / Bounds: ' + this.getBounds());
        }
    }

    asGeoJSON() {
        let feats = this.controlPoints;
        feats.push(this.circle_gj);
        feats.push(turfHelpers.point(this._center, {'type': 'center'}));
        return turfHelpers.featureCollection(feats);
    }

    getBounds() {
        let bboxPoly = turfTruncate(turfBboxPoly(turfBbox(this.circle_gj)), 6);
        return [
            bboxPoly.geometry.coordinates[0][0][0],
            bboxPoly.geometry.coordinates[0][0][1],
            bboxPoly.geometry.coordinates[0][2][0],
            bboxPoly.geometry.coordinates[0][2][1]
        ];
    }

    getBboxPoly() {
        return turfTruncate(turfBboxPoly(turfBbox(this.circle_gj)), 6);
    }

    getControlPoints() {
        return turfHelpers.featureCollection(this.controlPoints);
    }

    animate() {
        // map.on('sourcedata', onSourceData)
        this.map.getSource('circle-1').setData(this.asGeoJSON());
    }

    onZoomEnd() {
        // Adjust circle precision.
        this.zoom = this.map.getZoom();
        this.animate();
    }

    onMove(event) {
        let mousePoint = turfTruncate(turfHelpers.point(this.map.unproject(event.point).toArray()), 6);
        this.center = mousePoint.geometry.coordinates;
        this.animate();
    }

    onMouseUp() {
        this.map.setPaintProperty('circle-center-point', 'circle-color', '#fb6a4a');
        this.map.dragPan.enable();
        this.map.off('mousemove', this.onMove);
    }

    onMouseDown() {
        this.map.dragPan.disable();
        this.map.setPaintProperty('circle-center-point', 'circle-color', '#a50f15');
        this.map.on('mousemove', this.onMove);
        this.map.once('mouseup', this.onMouseUp);
    }

    onHandleMove(event) {
        let clickPoint = this.map.unproject(event.point).toArray();
        this.radius = turfDistance(this._center, clickPoint, 'meters');
        this.animate();
    }

    onHandleMouseUp() {
        this.map.setPaintProperty('circle-control-points', 'circle-color', 'white');
        this.map.dragPan.enable();
        this.map.off('mousemove', this.onHandleMove);
    }

    onHandleMouseDown() {
        this.map.dragPan.disable();
        this.map.setPaintProperty('circle-control-points', 'circle-color', '#a50f15');
        this.map.on('mousemove', this.onHandleMove);
        this.map.once('mouseup', this.onHandleMouseUp);
    }

    onMouseMove(event) {
        this.map.off('mousedown', this.onMouseDown);
        this.map.off('mousedown', this.onHandleMouseDown);

        let pointFeatures = this.map.queryRenderedFeatures(event.point, {
            layers: ['circle-control-points']
        });

        let circleFeatures = this.map.queryRenderedFeatures(event.point, {
            layers: ['circle-center-point']
        });

        if ((!pointFeatures.length) && (!circleFeatures.length)) {
            this.map.getCanvas().style.cursor = '';
        }

        if (pointFeatures.length) {
            this.map.getCanvas().style.cursor = 'pointer';
            this.map.once('mousedown', this.onHandleMouseDown);
        } else if (circleFeatures.length) {
            this.map.getCanvas().style.cursor = 'pointer';
            this.map.once('mousedown', this.onMouseDown);
        }
    }

    addTo(targetMap) {
        targetMap.on('load', () => {
            targetMap.addSource('circle-1', {
                type: 'geojson',
                data: this.asGeoJSON(),
                buffer: 1
            });

            targetMap.addLayer({
                id: 'circle-line',
                type: 'line',
                source: 'circle-1',
                paint: {
                    'line-color': '#fb6a4a',
                    'line-width': {
                        stops: [
                            [0, 0.1],
                            [16, 5]
                        ]
                    }
                },
                filter: ['==', '$type', 'Polygon']
            }, 'waterway-label');

            targetMap.addLayer({
                id: 'circle-fill',
                type: 'fill',
                source: 'circle-1',
                paint: {
                    'fill-color': '#fb6a4a',
                    'fill-opacity': 0.5
                },
                filter: ['==', '$type', 'Polygon']
            }, 'waterway-label');

            targetMap.addLayer({
                id: 'circle-control-points',
                type: 'circle',
                source: 'circle-1',
                paint: {
                    'circle-color': 'white',
                    'circle-radius': {
                        stops: [
                            [0, 6],
                            [4, 10],
                            [18, 12]
                        ]
                    },
                    'circle-stroke-color': 'black',
                    'circle-stroke-width': {
                        stops: [
                            [0, 0.1],
                            [8, 1],
                            [16, 4]
                        ]
                    }
                },
                filter: ['all', ['==', '$type', 'Point'],
                    ['!=', 'type', 'center']
                ]
            });

            targetMap.addLayer({
                id: 'circle-center-point',
                type: 'circle',
                source: 'circle-1',
                paint: {
                    'circle-color': '#fb6a4a',
                    'circle-radius': {
                        stops: [
                            [0, 6],
                            [4, 10],
                            [18, 12]
                        ]
                    },
                    'circle-stroke-color': 'black',
                    'circle-stroke-width': {
                        stops: [
                            [0, 0.1],
                            [8, 1],
                            [16, 4]
                        ]
                    }
                },
                filter: ['all', ['==', '$type', 'Point'],
                    ['==', 'type', 'center']
                ]
            });

            // Add map event listeners
            targetMap.on('zoomend', this.onZoomEnd);
            targetMap.on('mousemove', _.debounce(this.onMouseMove, 16));
        });
    }
}

module.exports = exports = MapboxCircle;
<commit_msg>SPFAM-1032 Make animate() private<commit_after>'use strict';

const _ = require('lodash');
const turfCircle = require('@turf/circle');
const turfBbox = require('@turf/bbox');
const turfBboxPoly = require('@turf/bbox-polygon');
const turfTruncate = require('@turf/truncate');
const turfDestination = require('@turf/destination');
const turfDistance = require('@turf/distance');
const turfHelpers = require('@turf/helpers');

class MapboxCircle {
    set center(value) {
        this._center = value;
        this._updateCircle();
        this._animate();
    }
    get center() {
        return this._center;
    }
    set radius(value) {
        this._radius = value;
        this._updateCircle();
        this._animate();
    }
    get radius() {
        return this._radius;
    }
    set zoom(value) {
        this._zoom = value;
        this._updateCircle();
        this._animate();
    }
    constructor(map, center, radius, options) {
        this.map = map;
        this._center = center; // Point geojson feature or array of [long,lat].
        this._radius = radius; // Radius of circle.
        this.statusEl = options.statusEl;
        this.properties = options.properties ? options.properties : {}; // JSON Object - property metadata for circle.

        this.units = 'meters';
        this._zoom = this.map.getZoom();

        this.steps = null; // No default steps
        this.circle_gj = null;
        this.controlPoints = null;

        // Bind event handlers.
        this.onMouseMove = this.onMouseMove.bind(this);
        this.onMouseDown = this.onMouseDown.bind(this);
        this.onHandleMouseDown = this.onHandleMouseDown.bind(this);
        this.onMouseUp = this.onMouseUp.bind(this);
        this.onHandleMouseUp = this.onHandleMouseUp.bind(this);
        this.onMove = this.onMove.bind(this);
        this.onHandleMove = this.onHandleMove.bind(this);
        this.onZoomEnd = this.onZoomEnd.bind(this);

        // Initialize circle object.
        this._updateCircle();
        this.addTo(map);
    }

    _updateSteps(zoom) {
        if (!zoom || zoom <= 0.1) zoom = 0.1;
        this.steps = (Math.sqrt(Math.trunc(this._radius * 0.25)) * zoom ^ 2);
    }

    _updateCircle() {
        this._updateSteps(this._zoom);
        this.circle_gj = turfCircle(this._center, this._radius, this.steps, this.units, this.properties);
        this.controlPoints = [
            turfDestination(this._center, this._radius, 0, this.units),
            turfDestination(this._center, this._radius, 90, this.units),
            turfDestination(this._center, this._radius, 180, this.units),
            turfDestination(this._center, this._radius, -90, this.units)
        ];
        if (this.statusEl) {
            this.statusEl.innerHTML = ('Center: ' + this._center + ' / Radius: ' + Math.trunc(this._radius) +
                                       ' meters / Bounds: ' + this.getBounds());
        }
    }

    _animate() {
        // map.on('sourcedata', onSourceData)
        this.map.getSource('circle-1').setData(this.asGeoJSON());
    }

    asGeoJSON() {
        let feats = this.controlPoints;
        feats.push(this.circle_gj);
        feats.push(turfHelpers.point(this._center, {'type': 'center'}));
        return turfHelpers.featureCollection(feats);
    }

    getBounds() {
        let bboxPoly = turfTruncate(turfBboxPoly(turfBbox(this.circle_gj)), 6);
        return [
            bboxPoly.geometry.coordinates[0][0][0],
            bboxPoly.geometry.coordinates[0][0][1],
            bboxPoly.geometry.coordinates[0][2][0],
            bboxPoly.geometry.coordinates[0][2][1]
        ];
    }

    getBboxPoly() {
        return turfTruncate(turfBboxPoly(turfBbox(this.circle_gj)), 6);
    }

    getControlPoints() {
        return turfHelpers.featureCollection(this.controlPoints);
    }

    onZoomEnd() {
        // Adjust circle precision.
        this.zoom = this.map.getZoom();
    }

    onMove(event) {
        let mousePoint = turfTruncate(turfHelpers.point(this.map.unproject(event.point).toArray()), 6);
        this.center = mousePoint.geometry.coordinates;
    }

    onMouseUp() {
        this.map.setPaintProperty('circle-center-point', 'circle-color', '#fb6a4a');
        this.map.dragPan.enable();
        this.map.off('mousemove', this.onMove);
    }

    onMouseDown() {
        this.map.dragPan.disable();
        this.map.setPaintProperty('circle-center-point', 'circle-color', '#a50f15');
        this.map.on('mousemove', this.onMove);
        this.map.once('mouseup', this.onMouseUp);
    }

    onHandleMove(event) {
        let clickPoint = this.map.unproject(event.point).toArray();
        this.radius = turfDistance(this.center, clickPoint, 'meters');
    }

    onHandleMouseUp() {
        this.map.setPaintProperty('circle-control-points', 'circle-color', 'white');
        this.map.dragPan.enable();
        this.map.off('mousemove', this.onHandleMove);
    }

    onHandleMouseDown() {
        this.map.dragPan.disable();
        this.map.setPaintProperty('circle-control-points', 'circle-color', '#a50f15');
        this.map.on('mousemove', this.onHandleMove);
        this.map.once('mouseup', this.onHandleMouseUp);
    }

    onMouseMove(event) {
        this.map.off('mousedown', this.onMouseDown);
        this.map.off('mousedown', this.onHandleMouseDown);

        let pointFeatures = this.map.queryRenderedFeatures(event.point, {
            layers: ['circle-control-points']
        });

        let circleFeatures = this.map.queryRenderedFeatures(event.point, {
            layers: ['circle-center-point']
        });

        if ((!pointFeatures.length) && (!circleFeatures.length)) {
            this.map.getCanvas().style.cursor = '';
        }

        if (pointFeatures.length) {
            this.map.getCanvas().style.cursor = 'pointer';
            this.map.once('mousedown', this.onHandleMouseDown);
        } else if (circleFeatures.length) {
            this.map.getCanvas().style.cursor = 'pointer';
            this.map.once('mousedown', this.onMouseDown);
        }
    }

    addTo(targetMap) {
        targetMap.on('load', () => {
            targetMap.addSource('circle-1', {
                type: 'geojson',
                data: this.asGeoJSON(),
                buffer: 1
            });

            targetMap.addLayer({
                id: 'circle-line',
                type: 'line',
                source: 'circle-1',
                paint: {
                    'line-color': '#fb6a4a',
                    'line-width': {
                        stops: [
                            [0, 0.1],
                            [16, 5]
                        ]
                    }
                },
                filter: ['==', '$type', 'Polygon']
            }, 'waterway-label');

            targetMap.addLayer({
                id: 'circle-fill',
                type: 'fill',
                source: 'circle-1',
                paint: {
                    'fill-color': '#fb6a4a',
                    'fill-opacity': 0.5
                },
                filter: ['==', '$type', 'Polygon']
            }, 'waterway-label');

            targetMap.addLayer({
                id: 'circle-control-points',
                type: 'circle',
                source: 'circle-1',
                paint: {
                    'circle-color': 'white',
                    'circle-radius': {
                        stops: [
                            [0, 6],
                            [4, 10],
                            [18, 12]
                        ]
                    },
                    'circle-stroke-color': 'black',
                    'circle-stroke-width': {
                        stops: [
                            [0, 0.1],
                            [8, 1],
                            [16, 4]
                        ]
                    }
                },
                filter: ['all', ['==', '$type', 'Point'],
                    ['!=', 'type', 'center']
                ]
            });

            targetMap.addLayer({
                id: 'circle-center-point',
                type: 'circle',
                source: 'circle-1',
                paint: {
                    'circle-color': '#fb6a4a',
                    'circle-radius': {
                        stops: [
                            [0, 6],
                            [4, 10],
                            [18, 12]
                        ]
                    },
                    'circle-stroke-color': 'black',
                    'circle-stroke-width': {
                        stops: [
                            [0, 0.1],
                            [8, 1],
                            [16, 4]
                        ]
                    }
                },
                filter: ['all', ['==', '$type', 'Point'],
                    ['==', 'type', 'center']
                ]
            });

            // Add map event listeners
            targetMap.on('zoomend', this.onZoomEnd);
            targetMap.on('mousemove', _.debounce(this.onMouseMove, 16));
        });
    }
}

module.exports = exports = MapboxCircle;
<|endoftext|>


<commit_before>/**
*    Copyright (C) 2008 10gen Inc.
*
*    This program is free software: you can redistribute it and/or  modify
*    it under the terms of the GNU Affero General Public License, version 3,
*    as published by the Free Software Foundation.
*
*    This program 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 Affero General Public License for more details.
*
*    You should have received a copy of the GNU Affero General Public License
*    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

local.src.test.ed.lang.python.size1_helper();

/** assert that a <= b <= a + epsilon */
var within = function( a , b , epsilon ){
    assert( a <= b );
    assert( b <= a + epsilon );
};

// These get converted to immutable objects.

//print("boolean " + pyBoolean.approxSize());
//print("int " + pyInt.approxSize());

//print("short string " + pyString.approxSize());
//print("longer string " + pyString2.approxSize());

var start = pyDict2.approxSize();

var before = pyDict2.approxSize(); // str1: str2
assert.eq( before , pyDict2.approxSize() );
assert.eq( before , pyDict2.approxSize() );
within( start , before , 100 );

pyModifyDict2(); // str1: str2
assert.eq(pyDict2.approxSize() , before);

pyModifyDict3(); // str1: str2, str2: str2
assert(pyDict2.approxSize() > before);

var extraNode = pyDict2.approxSize();

var delta = extraNode - before; // cost of adding an entry to a hash

pyModifyDict4(); // str1: str2, str2: str1

assert.eq(extraNode, pyDict2.approxSize());

var start = pyList1.approxSize();
var before = pyList1.approxSize();
assert.eq( before , pyList1.approxSize() );
within( start , before , 100 );

var diff = before - pyList2.approxSize();
assert(diff > 0); // same object reused [1,1]

assert.eq(before , pyList3.approxSize());

var before = pyList1.approxSize();

pyList1.push(1);
pyList2.push(1);
var delta = pyList1.approxSize() - before; // cost of an extra node
assert( delta > 0 );
assert.eq(pyList1.approxSize() - pyList2.approxSize() , diff); // added to both

var before = pyList1.approxSize();
pyList1.push(3);
pyList2.push(3);
var deltaNew = pyList1.approxSize() - before; // cost of an extra node, plus another integer

assert( deltaNew > delta );
assert.eq( pyList1.approxSize() - pyList2.approxSize() , diff ); // added to both

var jxp = local.src.test.ed.lang.python.size1_helper;
var jxp2 = local.src.test.ed.lang.python.date1_helper;

var start = jxp.approxSize();
var before = jxp.approxSize();

within(start, before, 100);
//assert.eq( before , jxp.approxSize() ); // FIXME: scope grows after within()?

// jxp and jxp2 should share some stuff, so together they shouldn't be as
// big as twice each one. Add the size of [] because Array is pretty big by
// itself.
assert( 2 * jxp.approxSize() + [].approxSize() > [ jxp , jxp2 ].approxSize() );
<commit_msg>Objects get a little bigger now.<commit_after>/**
*    Copyright (C) 2008 10gen Inc.
*
*    This program is free software: you can redistribute it and/or  modify
*    it under the terms of the GNU Affero General Public License, version 3,
*    as published by the Free Software Foundation.
*
*    This program 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 Affero General Public License for more details.
*
*    You should have received a copy of the GNU Affero General Public License
*    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

local.src.test.ed.lang.python.size1_helper();

/** assert that a <= b <= a + epsilon */
var within = function( a , b , epsilon ){
    assert( a <= b );
  assert( b <= a + epsilon , 'size grew by ' + (b-a));
};

// These get converted to immutable objects.

//print("boolean " + pyBoolean.approxSize());
//print("int " + pyInt.approxSize());

//print("short string " + pyString.approxSize());
//print("longer string " + pyString2.approxSize());

var start = pyDict2.approxSize();

var before = pyDict2.approxSize(); // str1: str2
assert.eq( before , pyDict2.approxSize() );
assert.eq( before , pyDict2.approxSize() );
within( start , before , 200 );

pyModifyDict2(); // str1: str2
assert.eq(pyDict2.approxSize() , before);

pyModifyDict3(); // str1: str2, str2: str2
assert(pyDict2.approxSize() > before);

var extraNode = pyDict2.approxSize();

var delta = extraNode - before; // cost of adding an entry to a hash

pyModifyDict4(); // str1: str2, str2: str1

assert.eq(extraNode, pyDict2.approxSize());

var start = pyList1.approxSize();
var before = pyList1.approxSize();
assert.eq( before , pyList1.approxSize() );
within( start , before , 100 );

var diff = before - pyList2.approxSize();
assert(diff > 0); // same object reused [1,1]

assert.eq(before , pyList3.approxSize());

var before = pyList1.approxSize();

pyList1.push(1);
pyList2.push(1);
var delta = pyList1.approxSize() - before; // cost of an extra node
assert( delta > 0 );
assert.eq(pyList1.approxSize() - pyList2.approxSize() , diff); // added to both

var before = pyList1.approxSize();
pyList1.push(3);
pyList2.push(3);
var deltaNew = pyList1.approxSize() - before; // cost of an extra node, plus another integer

assert( deltaNew > delta );
assert.eq( pyList1.approxSize() - pyList2.approxSize() , diff ); // added to both

var jxp = local.src.test.ed.lang.python.size1_helper;
var jxp2 = local.src.test.ed.lang.python.date1_helper;

var start = jxp.approxSize();
var before = jxp.approxSize();

within(start, before, 100);
//assert.eq( before , jxp.approxSize() ); // FIXME: scope grows after within()?

// jxp and jxp2 should share some stuff, so together they shouldn't be as
// big as twice each one. Add the size of [] because Array is pretty big by
// itself.
assert( 2 * jxp.approxSize() + [].approxSize() > [ jxp , jxp2 ].approxSize() );
<|endoftext|>


<commit_before>
import getWindow from 'get-window'
import isBackward from 'selection-is-backward'

/**
 * CSS overflow values that would cause scrolling.
 *
 * @type {Array}
 */

const OVERFLOWS = [
  'auto',
  'overlay',
  'scroll',
]

/**
 * Find the nearest parent with scrolling, or window.
 *
 * @param {el} Element
 */

function findScrollContainer(el) {
  const window = getWindow(el)
  let parent = el.parentNode
  let scroller

  while (!scroller) {
    if (!parent.parentNode) break
    const style = window.getComputedStyle(parent)
    const { overflowY } = style

    if (OVERFLOWS.includes(overflowY)) {
      scroller = parent
      break
    }

    parent = parent.parentNode
  }

  if (!scroller) return window

  return scroller
}

/**
 * Scroll the current selection's focus point into view if needed.
 *
 * @param {Selection} selection
 */

function scrollToSelection(selection) {
  if (!selection.anchorNode) return

  const window = getWindow(selection.anchorNode)
  const scroller = findScrollContainer(selection.anchorNode)
  const isWindow = scroller == window
  const backward = isBackward(selection)
  const range = selection.getRangeAt(0)
  const rect = range.getBoundingClientRect()
  let width
  let height
  let yOffset
  let xOffset

  if (isWindow) {
    const { innerWidth, innerHeight, pageYOffset, pageXOffset } = scroller
    width = innerWidth
    height = innerHeight
    yOffset = pageYOffset
    xOffset = pageXOffset
  } else {
    const { offsetWidth, offsetHeight, scrollTop, scrollLeft } = scroller
    const scrollerRect = scroller.getBoundingClientRect()
    width = offsetWidth
    height = offsetHeight
    yOffset = scrollTop - scrollerRect.top
    xOffset = scrollLeft - scrollerRect.left
  }

  const top = (backward ? rect.top : rect.bottom) + yOffset
  const left = (backward ? rect.left : rect.right) + xOffset

  const x = left < yOffset || (width + xOffset) < left
    ? left - width / 2
    : xOffset

  const y = top < yOffset || (height + yOffset) < top
    ? top - height / 2
    : yOffset

  if (isWindow) {
    window.scrollTo(x, y)
  } else {
    scroller.scrollTop = y
    scroller.scrollLeft = x
  }
}

/**
 * Export.
 *
 * @type {Function}
 */

export default scrollToSelection
<commit_msg>refactor scroll logic (#1428)<commit_after>
import getWindow from 'get-window'
import isBackward from 'selection-is-backward'

/**
 * CSS overflow values that would cause scrolling.
 *
 * @type {Array}
 */

const OVERFLOWS = [
  'auto',
  'overlay',
  'scroll',
]

/**
 * Find the nearest parent with scrolling, or window.
 *
 * @param {el} Element
 */

function findScrollContainer(el, window) {
  let parent = el.parentNode
  let scroller

  while (!scroller) {
    if (!parent.parentNode) break

    const style = window.getComputedStyle(parent)
    const { overflowY } = style

    if (OVERFLOWS.includes(overflowY)) {
      scroller = parent
      break
    }

    parent = parent.parentNode
  }

  // COMPAT: Because Chrome does not allow doucment.body.scrollTop, we're
  // assuming that window.scrollTo() should be used if the scrollable element
  // turns out to be document.body or document.documentElement. This will work
  // unless body is intentionally set to scrollable by restricting its height
  // (e.g. height: 100vh).
  if (!scroller) {
    return window.document.body
  }

  return scroller
}

/**
 * Scroll the current selection's focus point into view if needed.
 *
 * @param {Selection} selection
 */

function scrollToSelection(selection) {
  if (!selection.anchorNode) return

  const window = getWindow(selection.anchorNode)
  const scroller = findScrollContainer(selection.anchorNode, window)
  const isWindow = scroller == window.document.body || scroller == window.document.documentElement
  const backward = isBackward(selection)

  const range = selection.getRangeAt(0)
  let selectionRect = range.getBoundingClientRect()

  // COMPAT: range.getBoundingClientRect() returns 0s in Safari when range is
  // collapsed. Expanding the range by 1 is a relatively effective workaround
  // for vertical scroll, although horizontal may be off by 1 character.
  // https://bugs.webkit.org/show_bug.cgi?id=138949
  // https://bugs.chromium.org/p/chromium/issues/detail?id=435438
  if (range.collapsed && selectionRect.top == 0 && selectionRect.height == 0) {
    if (range.startOffset == 0) {
      range.setEnd(range.endContainer, 1)
    } else {
      range.setStart(range.startContainer, range.startOffset - 1)
    }

    selectionRect = range.getBoundingClientRect()
  }

  let width
  let height
  let yOffset
  let xOffset
  let scrollerTop = 0
  let scrollerLeft = 0
  let scrollerBordersY = 0
  let scrollerBordersX = 0

  if (isWindow) {
    const { innerWidth, innerHeight, pageYOffset, pageXOffset } = window
    width = innerWidth
    height = innerHeight
    yOffset = pageYOffset
    xOffset = pageXOffset
  } else {
    const { offsetWidth, offsetHeight, scrollTop, scrollLeft } = scroller
    const {
      borderTopWidth,
      borderBottomWidth,
      borderLeftWidth,
      borderRightWidth,
    } = window.getComputedStyle(scroller)

    const scrollerRect = scroller.getBoundingClientRect()
    width = offsetWidth
    height = offsetHeight
    scrollerTop = scrollerRect.top + parseInt(borderTopWidth, 10)
    scrollerLeft = scrollerRect.left + parseInt(borderLeftWidth, 10)
    scrollerBordersY = parseInt(borderTopWidth, 10) + parseInt(borderBottomWidth, 10)
    scrollerBordersX = parseInt(borderLeftWidth, 10) + parseInt(borderRightWidth, 10)
    yOffset = scrollTop
    xOffset = scrollLeft
  }

  const selectionFocusTop = backward ? selectionRect.top : selectionRect.bottom
  const selectionTop = selectionFocusTop + yOffset - scrollerTop

  const selectionFocusLeft = backward ? selectionRect.left : selectionRect.right
  const selectionLeft = selectionFocusLeft + xOffset - scrollerLeft

  let x = xOffset
  let y = yOffset

  if (selectionLeft < xOffset) {
    // selection to the left of viewport
    x = selectionLeft
  } else if (selectionLeft + selectionRect.width + scrollerBordersX > xOffset + width) {
    // selection to the right of viewport
    x = selectionLeft + scrollerBordersX - width
  }

  if (selectionTop < yOffset) {
    // selection above viewport
    y = selectionTop
  } else if (selectionTop + selectionRect.height + scrollerBordersY > yOffset + height) {
    // selection below viewport
    y = selectionTop + scrollerBordersY + selectionRect.height - height
  }

  if (isWindow) {
    window.scrollTo(x, y)
  } else {
    scroller.scrollTop = y
    scroller.scrollLeft = x
  }
}

/**
 * Export.
 *
 * @type {Function}
 */

export default scrollToSelection
<|endoftext|>


<commit_before>/*!
 * nodeGame
 */

(function (exports) {

	var node = exports;

	node.version = '0.6.6';

	node.verbosity = 0;

	node.verbosity_levels = {
			ALWAYS: -(Number.MIN_VALUE+1), // Actually, it is not really always...
			ERR: -1,
			WARN: 0,
			INFO: 1,
			DEBUG: 3
	};

	node.log = function (txt, level) {
		var level = level || 0;
		if ('string' === typeof level) {
			var level = node.verbosity_levels[level];
		}
		if (node.verbosity > level) {
			console.log(txt);
		}
	};

	// Memory related operations
	// Will be initialized later
	node.memory = {};

	// Load the auxiliary library if available in the browser
	if ('undefined' !== typeof JSUS) node.JSUS = JSUS;
	if ('undefined' !== typeof NDDB) node.NDDB = NDDB;

	// if node
	if ('object' === typeof module && 'function' === typeof require) {

		/**
	     * Expose Socket.io-client
	     *
	     * @api public
	     */

	    node.io = require('socket.io-client');

		/**
	     * Expose EventEmitter
	     *
	     * @api public
	     */

	    node.EventEmitter = require('./EventEmitter').EventEmitter;

	    /**
	     * Expose JSU
	     *
	     * @api public
	     */

	    node.JSUS = require('JSUS').JSUS;

	    /**
	     * Expose Utils
	     *
	     * @api public
	     */

	    node.utils = node.Utils = require('./Utils').Utils;

	    /**
	     * Expose GameState.
	     *
	     * @api public
	     */

	    node.GameState = require('./GameState').GameState;

	    /**
	     * Expose PlayerList.
	     *
	     * @api public
	     */

	    node.PlayerList = require('./PlayerList').PlayerList;

	    /**
	     * Expose Player.
	     *
	     * @api public
	     */

	    node.Player = require('./PlayerList').Player;

	    /**
	     * Expose GameMsg
	     *
	     * @api public
	     */

	     node.GameMsg = require('./GameMsg').GameMsg;

	    /**
	     * Expose GameLoop
	     *
	     * @api public
	     */

	    node.GameLoop = require('./GameLoop').GameLoop;

	    /**
	     * Expose GameMsgGenerator
	     *
	     * @api public
	     */

	    node.GameMsgGenerator = require('./GameMsgGenerator').GameMsgGenerator;

	    /**
	     * Expose GameSocketClient
	     *
	     * @api public
	     */

	    node.GameSocketClient = require('./GameSocketClient').GameSocketClient;

	    /**
	     * Expose NDDB
	     *
	     * @api public
	     */

	    node.NDDB = require('NDDB').NDDB;

	    /**
	     * Expose GameStorage
	     *
	     * @api public
	     */

	    node.GameDB = require('./GameDB').GameDB;

	    /**
	     * Expose Game
	     *
	     * @api public
	     */

	    node.Game = require('./Game').Game;

	  }
	  // end node

	var EventEmitter = node.EventEmitter;
	var GameSocketClient = node.GameSocketClient;
	var GameState = node.GameState;
	var GameMsg = node.GameMsg;
	var Game = node.Game;

	/**
	 * Expose constructor
	 *
	 */
	exports.nodeGame = nodeGame;

	/**
	 *  Exposing constants
	 */
	exports.actions = GameMsg.actions;
	exports.IN = GameMsg.IN;
	exports.OUT = GameMsg.OUT;
	exports.targets = GameMsg.targets;
	exports.states = GameState.iss;

	// Constructor
	nodeGame.prototype.__proto__ = EventEmitter.prototype;
	nodeGame.prototype.constructor = nodeGame;

	function nodeGame() {
		EventEmitter.call(this);
		this.gsc = null;
		this.game = null;
	};

//	node.memory.get = function (reverse) {
//		return node.game.dump(reverse);
//	}
//
//	node.memory.getValues = function(reverse) {
//		return node.game.memory.getValues(reverse);
//	}

	/**
	 * Creating an object
	 */
	var that = node.node = new nodeGame();

	node.state = function() {
		return (that.game) ? node.node.game.gameState : false;
	};

	node.on = function (event, listener) {
		var state = this.state();
		//node.log(state);

		// It is in the init function;
		if (!state || (GameState.compare(state, new GameState(), true) === 0 )) {
			that.addListener(event, listener);
			//node.log('global');
		}
		else {
			that.addLocalListener(event, listener);
			//node.log('local');
		}
	};

	node.once = function (event, listener) {
		node.on(event, listener);
		node.on(event, function(event, listener) {
			that.removeListener(event, listener);
		});
	};
	// TODO: create conf objects
	node.play = function (conf, game) {
		if ('undefined' !== typeof conf.verbosity) node.verbosity = conf.verbosity;

		node.gsc = that.gsc = new GameSocketClient(conf);

		node.game = that.game = new Game(game, that.gsc);
		//node.memory = that.game.memory;
		// INIT the game
		that.game.init.call(that.game);
		that.gsc.setGame(that.game);

		node.log('nodeGame: game loaded...');
		node.log('nodeGame: ready.');
	};

	node.observe = function (conf, game) {
		if ('undefined' !== typeof conf.verbosity) node.verbosity = conf.verbosity;
		var game = game || {loops: {1: {state: function(){}}}};
		node.gsc = that.gsc = new GameSocketClient(conf);

		node.game = that.game = new Game(game, that.gsc);
		node.gsc.setGame(that.game);

		node.on('NODEGAME_READY', function(){

			// Retrieve the game and set is as observer
			node.get('LOOP', function(game) {

				//alert(game);
				console.log('ONLY ONE');
				console.log(game);
	//			var game = game.observer = true;
	//			node.game = that.game = game;
	//
	//			that.game.init();
	//
	//			that.gsc.setGame(that.game);
	//
	//			node.log('nodeGame: game loaded...');
	//			node.log('nodeGame: ready.');
			});
		});

//		node.onDATA('GAME', function(data){
//			alert(data);
//			console.log(data);
//		});

//		node.on('DATA', function(msg){
//			console.log('--------->Eh!')
//			console.log(msg);
//		});
	};

	node.fire = node.emit = function (event, p1, p2, p3) {
		that.emit(event, p1, p2, p3);
	};

	node.say = function (data, what, whom) {
		that.emit('out.say.DATA', data, whom, what);
	};

	/**
	 * Set the pair (key,value) into the server
	 * @value can be an object literal.
	 *
	 *
	 */
	node.set = function (key, value) {
		// TODO: parameter to say who will get the msg
		that.emit('out.set.DATA', value, null, key);
	}

	node.get = function (key, func) {
		that.emit('out.get.DATA', key);

		var listener = function(msg) {
			if (msg.text === key) {
				func.call(node.game, msg.data);
				if(that.removeListener('in.say.DATA',listener)){
					console.log('yes!!!');
				}
			}
			//that.printAllListeners();
		};

		node.on('in.say.DATA', listener);
	};

	// *Aliases*
	//
	// Conventions:
	//
	// - Direction:
	// 		'in' for all
	//
	// - Target:
	// 		DATA and TXT are 'say' as default
	// 		STATE and PLIST are 'set' as default

	// Sending

//	this.setSTATE = function(action,state,to){
//		var stateEvent = GameMsg.OUT + action + '.STATE';
//		fire(stateEvent,action,state,to);
//	};

	// Receiving

	// Say

	node.onTXT = function(func) {
		node.on("in.say.TXT", function(msg) {
			func.call(that.game,msg);
		});
	};

	node.onDATA = function(text, func) {
		node.on('in.say.DATA', function(msg) {
			if (text && msg.text === text) {
				func.call(that.game,msg);
			}
		});

		node.on('in.set.DATA', function(msg) {
			func.call(that.game,msg);
		});
	};

	// Set

	node.onSTATE = function(func) {
		node.on("in.set.STATE", function(msg) {
			func.call(that.game, msg);
		});
	};

	node.onPLIST = function(func) {
		node.on("in.set.PLIST", function(msg) {
			func.call(that.game, msg);
		});

		node.on("in.say.PLIST", function(msg) {
			func.call(that.game, msg);
		});
	};

	node.DONE = function (text) {
		node.emit("DONE",text);
	};

	node.TXT = function (text, to) {
		node.emit('out.say.TXT', text, to);
	};

	node.random = {};

	// Generates event at RANDOM timing in milliseconds
	// if timing is missing, default is 6000
	node.random.emit = function (event, timing){
		var timing = timing || 6000;
		setTimeout(function(event) {
			node.emit(event);
		}, Math.random()*timing, event);
	};

	node.random.exec = function (func, timing) {
		var timing = timing || 6000;
		setTimeout(function(func) {
			func.call();
		}, Math.random()*timing, func);
	}

	node.replay = function (reset) {
		if (reset) node.game.memory.clear(true);
		node.goto(new GameState({state: 1, step: 1, round: 1}));
	}

	node.goto = function(state) {
		node.game.updateState(state);
	};

	// if node
	if ('object' === typeof module && 'function' === typeof require) {

		 /**
	     * Enable file system operations
	     */

	    node.csv = {};
	    node.fs = {};

	    var fs = require('fs');
	    var path = require('path');
	    var csv = require('ya-csv');

	    /**
	     * Takes an obj and write it down to a csv file;
	     */
	    node.fs.writeCsv = function (path, obj) {
	    	var writer = csv.createCsvStreamWriter(fs.createWriteStream( path, {'flags': 'a'}));
	    	var i;
	        for (i=0;i<obj.length;i++) {
	    		writer.writeRecord(obj[i]);
	    	}
	    };

	    node.memory.dump = function (path) {
			node.fs.writeCsv(path, node.game.memory.split().fetchValues());
	    }

	}
	// end node

	node.log('nodeGame ' + node.version + ' loaded', 'ALWAYS');

})('undefined' != typeof node ? node : module.exports);<commit_msg>Widget ServerInfoDisplay working<commit_after>/*!
 * nodeGame
 */

(function (exports) {

	var node = exports;

	node.version = '0.6.6';

	node.verbosity = 0;

	node.verbosity_levels = {
			ALWAYS: -(Number.MIN_VALUE+1), // Actually, it is not really always...
			ERR: -1,
			WARN: 0,
			INFO: 1,
			DEBUG: 3
	};

	node.log = function (txt, level) {
		var level = level || 0;
		if ('string' === typeof level) {
			var level = node.verbosity_levels[level];
		}
		if (node.verbosity > level) {
			console.log(txt);
		}
	};

	// Memory related operations
	// Will be initialized later
	node.memory = {};

	// Load the auxiliary library if available in the browser
	if ('undefined' !== typeof JSUS) node.JSUS = JSUS;
	if ('undefined' !== typeof NDDB) node.NDDB = NDDB;

	// if node
	if ('object' === typeof module && 'function' === typeof require) {

		/**
	     * Expose Socket.io-client
	     *
	     * @api public
	     */

	    node.io = require('socket.io-client');

		/**
	     * Expose EventEmitter
	     *
	     * @api public
	     */

	    node.EventEmitter = require('./EventEmitter').EventEmitter;

	    /**
	     * Expose JSU
	     *
	     * @api public
	     */

	    node.JSUS = require('JSUS').JSUS;

	    /**
	     * Expose Utils
	     *
	     * @api public
	     */

	    node.utils = node.Utils = require('./Utils').Utils;

	    /**
	     * Expose GameState.
	     *
	     * @api public
	     */

	    node.GameState = require('./GameState').GameState;

	    /**
	     * Expose PlayerList.
	     *
	     * @api public
	     */

	    node.PlayerList = require('./PlayerList').PlayerList;

	    /**
	     * Expose Player.
	     *
	     * @api public
	     */

	    node.Player = require('./PlayerList').Player;

	    /**
	     * Expose GameMsg
	     *
	     * @api public
	     */

	     node.GameMsg = require('./GameMsg').GameMsg;

	    /**
	     * Expose GameLoop
	     *
	     * @api public
	     */

	    node.GameLoop = require('./GameLoop').GameLoop;

	    /**
	     * Expose GameMsgGenerator
	     *
	     * @api public
	     */

	    node.GameMsgGenerator = require('./GameMsgGenerator').GameMsgGenerator;

	    /**
	     * Expose GameSocketClient
	     *
	     * @api public
	     */

	    node.GameSocketClient = require('./GameSocketClient').GameSocketClient;

	    /**
	     * Expose NDDB
	     *
	     * @api public
	     */

	    node.NDDB = require('NDDB').NDDB;

	    /**
	     * Expose GameStorage
	     *
	     * @api public
	     */

	    node.GameDB = require('./GameDB').GameDB;

	    /**
	     * Expose Game
	     *
	     * @api public
	     */

	    node.Game = require('./Game').Game;

	  }
	  // end node

	var EventEmitter = node.EventEmitter;
	var GameSocketClient = node.GameSocketClient;
	var GameState = node.GameState;
	var GameMsg = node.GameMsg;
	var Game = node.Game;

	/**
	 * Expose constructor
	 *
	 */
	exports.nodeGame = nodeGame;

	/**
	 *  Exposing constants
	 */
	exports.actions = GameMsg.actions;
	exports.IN = GameMsg.IN;
	exports.OUT = GameMsg.OUT;
	exports.targets = GameMsg.targets;
	exports.states = GameState.iss;

	// Constructor
	nodeGame.prototype.__proto__ = EventEmitter.prototype;
	nodeGame.prototype.constructor = nodeGame;

	function nodeGame() {
		EventEmitter.call(this);
		this.gsc = null;
		this.game = null;
	};

//	node.memory.get = function (reverse) {
//		return node.game.dump(reverse);
//	}
//
//	node.memory.getValues = function(reverse) {
//		return node.game.memory.getValues(reverse);
//	}

	/**
	 * Creating an object
	 */
	var that = node.node = new nodeGame();

	node.state = function() {
		return (that.game) ? node.node.game.gameState : false;
	};

	node.on = function (event, listener) {
		var state = this.state();
		//node.log(state);

		// It is in the init function;
		if (!state || (GameState.compare(state, new GameState(), true) === 0 )) {
			that.addListener(event, listener);
			//node.log('global');
		}
		else {
			that.addLocalListener(event, listener);
			//node.log('local');
		}
	};

	node.once = function (event, listener) {
		node.on(event, listener);
		node.on(event, function(event, listener) {
			that.removeListener(event, listener);
		});
	};
	// TODO: create conf objects
	node.play = function (conf, game) {
		if ('undefined' !== typeof conf.verbosity) node.verbosity = conf.verbosity;

		node.gsc = that.gsc = new GameSocketClient(conf);

		node.game = that.game = new Game(game, that.gsc);
		//node.memory = that.game.memory;
		// INIT the game
		that.game.init.call(that.game);
		that.gsc.setGame(that.game);

		node.log('nodeGame: game loaded...');
		node.log('nodeGame: ready.');
	};

	node.observe = function (conf, game) {
		if ('undefined' !== typeof conf.verbosity) node.verbosity = conf.verbosity;
		var game = game || {loops: {1: {state: function(){}}}};
		node.gsc = that.gsc = new GameSocketClient(conf);

		node.game = that.game = new Game(game, that.gsc);
		node.gsc.setGame(that.game);

		node.on('NODEGAME_READY', function(){

			// Retrieve the game and set is as observer
			node.get('LOOP', function(game) {

				//alert(game);
				console.log('ONLY ONE');
				console.log(game);
	//			var game = game.observer = true;
	//			node.game = that.game = game;
	//
	//			that.game.init();
	//
	//			that.gsc.setGame(that.game);
	//
	//			node.log('nodeGame: game loaded...');
	//			node.log('nodeGame: ready.');
			});
		});

//		node.onDATA('GAME', function(data){
//			alert(data);
//			console.log(data);
//		});

//		node.on('DATA', function(msg){
//			console.log('--------->Eh!')
//			console.log(msg);
//		});
	};

	node.fire = node.emit = function (event, p1, p2, p3) {
		that.emit(event, p1, p2, p3);
	};

	node.say = function (data, what, whom) {
		that.emit('out.say.DATA', data, whom, what);
	};

	/**
	 * Set the pair (key,value) into the server
	 * @value can be an object literal.
	 *
	 *
	 */
	node.set = function (key, value) {
		// TODO: parameter to say who will get the msg
		that.emit('out.set.DATA', value, null, key);
	}

	node.get = function (key, func) {
		that.emit('out.get.DATA', key);

		var listener = function(msg) {
			if (msg.text === key) {
				func.call(node.game, msg.data);
				that.removeListener('in.say.DATA',listener);
			}
			//that.printAllListeners();
		};

		node.on('in.say.DATA', listener);
	};

	// *Aliases*
	//
	// Conventions:
	//
	// - Direction:
	// 		'in' for all
	//
	// - Target:
	// 		DATA and TXT are 'say' as default
	// 		STATE and PLIST are 'set' as default

	// Sending

//	this.setSTATE = function(action,state,to){
//		var stateEvent = GameMsg.OUT + action + '.STATE';
//		fire(stateEvent,action,state,to);
//	};

	// Receiving

	// Say

	node.onTXT = function(func) {
		node.on("in.say.TXT", function(msg) {
			func.call(that.game,msg);
		});
	};

	node.onDATA = function(text, func) {
		node.on('in.say.DATA', function(msg) {
			if (text && msg.text === text) {
				func.call(that.game,msg);
			}
		});

		node.on('in.set.DATA', function(msg) {
			func.call(that.game,msg);
		});
	};

	// Set

	node.onSTATE = function(func) {
		node.on("in.set.STATE", function(msg) {
			func.call(that.game, msg);
		});
	};

	node.onPLIST = function(func) {
		node.on("in.set.PLIST", function(msg) {
			func.call(that.game, msg);
		});

		node.on("in.say.PLIST", function(msg) {
			func.call(that.game, msg);
		});
	};

	node.DONE = function (text) {
		node.emit("DONE",text);
	};

	node.TXT = function (text, to) {
		node.emit('out.say.TXT', text, to);
	};

	node.random = {};

	// Generates event at RANDOM timing in milliseconds
	// if timing is missing, default is 6000
	node.random.emit = function (event, timing){
		var timing = timing || 6000;
		setTimeout(function(event) {
			node.emit(event);
		}, Math.random()*timing, event);
	};

	node.random.exec = function (func, timing) {
		var timing = timing || 6000;
		setTimeout(function(func) {
			func.call();
		}, Math.random()*timing, func);
	}

	node.replay = function (reset) {
		if (reset) node.game.memory.clear(true);
		node.goto(new GameState({state: 1, step: 1, round: 1}));
	}

	node.goto = function(state) {
		node.game.updateState(state);
	};

	// if node
	if ('object' === typeof module && 'function' === typeof require) {

		 /**
	     * Enable file system operations
	     */

	    node.csv = {};
	    node.fs = {};

	    var fs = require('fs');
	    var path = require('path');
	    var csv = require('ya-csv');

	    /**
	     * Takes an obj and write it down to a csv file;
	     */
	    node.fs.writeCsv = function (path, obj) {
	    	var writer = csv.createCsvStreamWriter(fs.createWriteStream( path, {'flags': 'a'}));
	    	var i;
	        for (i=0;i<obj.length;i++) {
	    		writer.writeRecord(obj[i]);
	    	}
	    };

	    node.memory.dump = function (path) {
			node.fs.writeCsv(path, node.game.memory.split().fetchValues());
	    }

	}
	// end node

	node.log('nodeGame ' + node.version + ' loaded', 'ALWAYS');

})('undefined' != typeof node ? node : module.exports);<|endoftext|>