<commit_before>var ExpandDong = {};

(function(ExpandDong){

    Panels = ExpandDong.Panels = function(container, options){
        // Load options
        this.options = {
            'expandRatio':  0.667,
            'resizeRatio':  0.2,
            'resizeTime':   50,
        }
        if ((options) && (options instanceof Object)) for (option in options) if (options.hasOwnProperty(option))
            this.options[option] = options[option];

        // Set active panel
        this._activePanelIndex = null;
        this._pristine = true;

        // Get list of panels and subelements
        panels = this._panels = [];

        for (var i = container.children.length - 1; i >= 0; i--) {
            if ((panelElem = container.children[i]).hasAttribute('panel')) {
                panelPreview = panelContent = null;

                for (var j = panelElem.children.length - 1; j >= 0; j--) {
                    panelChildElem = panelElem.children[j];

                    if (panelChildElem.hasAttribute('panel-preview')) {
                        panelPreview = panelChildElem;
                    } else if (panelChildElem.hasAttribute('panel-content')) {
                        panelContent = panelChildElem;
                    }
                };

                if ((panelPreview !== null) && (panelContent !== null)) {
                    panels.push({'panel': panelElem, 'preview': panelPreview, 'content': panelContent});
                }
            }
        };

        // Container properties
        containerWidth = this._containerWidth = container.clientWidth;
        eqWidth = (containerWidth - 1)/ panels.length;

        // Set starting CSS
        container.style.position = 'relative';
        container.style = 'discard';

        for (var i = panels.length - 1; i >= 0; i--) {
            // Sizing and positioning
            p = panels[i];
            p.panel.style.position = 'relative';
            p.panel.style.display = 'inline-block';
            p.panel.style.marginRight = '-4px';
            p.panel.style.height = '100%';
            p.panel.style.width = eqWidth;

            p.preview.style.position = p.content.style.position = "absolute";
            p.preview.style.top = p.preview.style.left = p.content.style.top = p.content.style.left = "0px";
            p.preview.style.height = p.preview.style.width = p.content.style.height = p.content.style.width = '100%';

            // Make all content transparent
            p.content.style.opacity = '0';
        };

        // Set width arrays
        this._currentWidths = Array.apply(null, Array(panels.length)).map(function(){ return eqWidth; });
        this._desiredWidths = this._currentWidths.slice();

        // Bind listeners

    };

    Panels.prototype.activate = function(index){
        this._activePanelIndex = index;

        if ((index < 0) || (index >= this._panels.length)) return;
        activeWidth = (this._containerWidth - 1) * this.options.expandRatio;
        inactiveWidth = (this._containerWidth - 1 - activeWidth) / (this._panels.length - 1);
        this._desiredWidths = Array.apply(null, Array(this._panels.length)).map(function(){ return inactiveWidth; });
        this._desiredWidths[index] = activeWidth;

        this._resize();
    };

    Panels.prototype.deactivate = function(){
        this._activePanelIndex = null;

        eqWidth = (this._containerWidth - 1)/ this._panels.length;
        this._desiredWidths = Array.apply(null, Array(panels.length)).map(function(){ return eqWidth; });

        this._resize(reset = true);
    };

    Panels.prototype._resize = function(reset){
        // Fancy calculations
        currentWidths = this._currentWidths;
        differences = this._desiredWidths.map(function(d, d_i){ return d - currentWidths[d_i]; });

        resizeRatio = this.options.resizeRatio;
        growths = differences.map(function(d){ return (d > 0) ? (d * resizeRatio) : 0; });
        shrinks = differences.map(function(d){ return (d < 0) ? (d * resizeRatio) : 0; });

        sum_reduce = function(acc, cur){ return acc + cur; };
        delta = growths.reduce(sum_reduce, 0) + shrinks.reduce(sum_reduce, 0);
        abs_delta = growths.reduce(sum_reduce, 0) - shrinks.reduce(sum_reduce, 0);

        compensate = delta / this._panels.length;
        compensator = function(d){ return d + compensate; };
        growths = growths.map(compensator);
        shrinks = shrinks.map(compensator);

        this._currentWidths = currentWidths.map(function(d, d_i){ return d + growths[d_i] + shrinks[d_i]; });

        // Set panel...
        for (var i = this._currentWidths.length - 1; i >= 0; i--) {
            p = this._panels[i]

            // ... widths
            p.panel.style.width = this._currentWidths[i];

            // ... opacities
            opacity_delta = (growths[i] - shrinks[i]) / this._containerWidth * 100;
            if (i === this._activePanelIndex) {
                p.preview.style.opacity = Math.log(opacity_delta);
                p.content.style.opacity = 1 - Math.log(opacity_delta);
            } else if (this._pristine == false) {
                p.preview.style.opacity = 1 - Math.log(opacity_delta);
                p.content.style.opacity = Math.log(opacity_delta);
            }
        }

        // Recursive event loop call
        if (abs_delta > 1) setTimeout(this._resize.bind(this), this.options.resizeTime);
        else if (reset) this._pristine = true;
        else  this._pristine = false;
    };

})(ExpandDong);<commit_msg>activators now stored in closures<commit_after>var ExpandDong = {};

(function(ExpandDong){

    Panels = ExpandDong.Panels = function(container, options){
        // Load options
        this.options = {
            'expandRatio':  0.667,
            'resizeRatio':  0.1,
            'resizeTime':   10,
            'trigger': 'click',
        }
        if ((options) && (options instanceof Object)) for (option in options) if (options.hasOwnProperty(option))
            this.options[option] = options[option];

        // Set active panel
        this._activePanelIndex = null;
        this._pristine = true;

        // Get list of panels and subelements
        panels = this._panels = [];

        for (var i = 0; i < container.children.length; i++) {
            if ((panelElem = container.children[i]).hasAttribute('panel')) {
                panelPreview = panelContent = null;

                for (var j = panelElem.children.length - 1; j >= 0; j--) {
                    panelChildElem = panelElem.children[j];

                    if (panelChildElem.hasAttribute('panel-preview')) {
                        panelPreview = panelChildElem;
                    } else if (panelChildElem.hasAttribute('panel-content')) {
                        panelContent = panelChildElem;
                    }
                };

                if ((panelPreview !== null) && (panelContent !== null)) {
                    panels.push({
                        'panel': panelElem,
                        'preview': panelPreview,
                        'content': panelContent,
                    });
                }
            }
        };

        // Container properties
        containerWidth = this._containerWidth = container.clientWidth;
        eqWidth = (containerWidth - 1)/ panels.length;

        // Set starting CSS
        container.style.position = 'relative';
        container.style = 'discard';

        for (var i = panels.length - 1; i >= 0; i--) {
            // Sizing and positioning
            p = panels[i];
            p.panel.style.position = 'relative';
            p.panel.style.display = 'inline-block';
            p.panel.style.marginRight = '-4px';
            p.panel.style.height = '100%';
            p.panel.style.width = eqWidth;

            p.preview.style.position = p.content.style.position = "absolute";
            p.preview.style.top = p.preview.style.left = p.content.style.top = p.content.style.left = "0px";
            p.preview.style.height = p.preview.style.width = p.content.style.height = p.content.style.width = '100%';

            // Make all content transparent
            p.content.style.opacity = '0';
        };

        // Set width arrays
        this._currentWidths = Array.apply(null, Array(panels.length)).map(function(){ return eqWidth; });
        this._desiredWidths = this._currentWidths.slice();

        // Bind listeners
        panelsContext = this;

        createActivator = function(index) {
            var index_container = {'index': index};

            return (function(){
                this.activate(index_container.index);
            }).bind(panelsContext);
        };

        for (var i = this._panels.length - 1; i >= 0; i--) {
            panel = this._panels[i].panel;
            panel.addEventListener(this.options.trigger, createActivator(i));
        };
    };

    Panels.prototype.activate = function(index){
        this._activePanelIndex = index;

        if ((index < 0) || (index >= this._panels.length)) return;
        activeWidth = (this._containerWidth - 1) * this.options.expandRatio;
        inactiveWidth = (this._containerWidth - 1 - activeWidth) / (this._panels.length - 1);
        this._desiredWidths = Array.apply(null, Array(this._panels.length)).map(function(){ return inactiveWidth; });
        this._desiredWidths[index] = activeWidth;

        this._resize();
    };

    Panels.prototype.deactivate = function(){
        this._activePanelIndex = null;

        eqWidth = (this._containerWidth - 1)/ this._panels.length;
        this._desiredWidths = Array.apply(null, Array(panels.length)).map(function(){ return eqWidth; });

        this._resize(reset = true);
    };

    Panels.prototype._resize = function(reset){
        // Fancy calculations
        currentWidths = this._currentWidths;
        differences = this._desiredWidths.map(function(d, d_i){ return d - currentWidths[d_i]; });

        resizeRatio = this.options.resizeRatio;
        growths = differences.map(function(d){ return (d > 0) ? (d * resizeRatio) : 0; });
        shrinks = differences.map(function(d){ return (d < 0) ? (d * resizeRatio) : 0; });

        sum_reduce = function(acc, cur){ return acc + cur; };
        delta = growths.reduce(sum_reduce, 0) + shrinks.reduce(sum_reduce, 0);
        abs_delta = growths.reduce(sum_reduce, 0) - shrinks.reduce(sum_reduce, 0);

        compensate = delta / this._panels.length;
        compensator = function(d){ return d + compensate; };
        growths = growths.map(compensator);
        shrinks = shrinks.map(compensator);

        this._currentWidths = currentWidths.map(function(d, d_i){ return d + growths[d_i] + shrinks[d_i]; });

        // Set panel...
        for (var i = this._currentWidths.length - 1; i >= 0; i--) {
            p = this._panels[i]

            // ... widths
            p.panel.style.width = this._currentWidths[i];

            // ... opacities
            opacity_delta = (growths[i] - shrinks[i]) / this._containerWidth * 100;
            if (i === this._activePanelIndex) {
                p.preview.style.opacity = Math.log(opacity_delta);
                p.content.style.opacity = 1 - Math.log(opacity_delta);
            } else if (this._pristine == false) {
                p.preview.style.opacity = 1 - Math.log(opacity_delta);
                p.content.style.opacity = Math.log(opacity_delta);
            }
        }

        // Recursive event loop call
        if (abs_delta > 1) setTimeout(this._resize.bind(this), this.options.resizeTime);
        else if (reset) this._pristine = true;
        else  this._pristine = false;
    };

})(ExpandDong);<|endoftext|>


<commit_before>/*! bodyguard - v0.1.0 - 10-11-2013 */
(function(){!function(a){return udefine.configure(function(){return udefine.inject.add(a)})}("bodyguard")}).call(this),function(){udefine("bodyguard",function(){var a,b,c;return c=function(){},a=function(a,b){return null!=a?a.apply(b,arguments):void 0},b=function(d,e,f){var g,h,i,j;if(h={},h[d]=function(){},h[d].constructor.name=d,Array.isArray(e))for(i=0,j=e.length;j>i;i++)g=e[i],null!=f[g]?h[d].prototype[g]=f[g]||c:(b.silent||"undefined"!=typeof console&&null!==console&&"function"==typeof console.warn&&console.warn("Method "+g+" is not implemented."),h[d].prototype[g]=function(){return a(f[g],this)});return h[d]},b.silent=!0,b}),udefine.env.commonjs&&udefine.require("bodyguard",function(a){return module.exports=a})}.call(this);<commit_msg>Release 0.1.1<commit_after>/*! bodyguard - v0.1.1 - 10-11-2013 */
(function(){!function(a){return udefine.configure(function(){return udefine.inject.add(a)})}("bodyguard")}).call(this),function(){udefine("bodyguard",function(){var a,b,c;return c=function(){},a=function(a,b){return null!=a?a.apply(b,arguments):void 0},b=function(d,e,f){var g,h,i,j;if(h={},h[d]=function(){},h[d].constructor.name=d,Array.isArray(e))for(i=0,j=e.length;j>i;i++)g=e[i],null!=f[g]?h[d].prototype[g]=f[g]||c:(b.silent||"undefined"!=typeof console&&null!==console&&"function"==typeof console.warn&&console.warn("Method "+g+" is not implemented."),h[d].prototype[g]=function(){return a(f[g],this)});return h[d]},b.silent=!0,b}),udefine.env.commonjs&&udefine.require("bodyguard",function(a){return module.exports=a})}.call(this);<|endoftext|>


<commit_before>var DataSource = require('../index').DataSource;
var ds = new DataSource('memory');

var Order = ds.createModel('Order', {
  items: [String],
  orderDate: Date
});

var Customer = ds.createModel('Customer', {
  name: String
});

Order.belongsTo(Customer);

var order1, order2, order3;

Customer.create({name: 'John'}, function (err, customer) {
  Order.create({customerId: customer.id, orderDate: new Date(), items: ['Book']}, function (err, order) {
    order1 = order;
    order.customer(console.log);
    order.customer(true, console.log);

    Customer.create({name: 'Mary'}, function (err, customer2) {
      order.customer(customer2);
      order.customer(console.log);
    });
  });

  Order.create({orderDate: new Date(), items: ['Phone']}, function (err, order) {

    order.customer.create({name: 'Smith'}, function(err, customer2) {
      console.log(order, customer2);
      order.save(function(err, order) {
        order2 = order;
      });
    });

    var customer3 = order.customer.build({name: 'Tom'});
    console.log('Customer 3', customer3);
  });
});

Customer.hasMany(Order, {as: 'orders', foreignKey: 'customerId'});

Customer.create({name: 'Ray'}, function (err, customer) {
  Order.create({customerId: customer.id, orderDate: new Date()}, function (err, order) {
    order3 = order;
    customer.orders(console.log);
    customer.orders.create({orderDate: new Date()}, function (err, order) {
      console.log(order);
      Customer.include([customer], 'orders', function (err, results) {
        console.log('Results: ', results);
      });
      customer.orders.findById(order3.id, console.log);
      customer.orders.destroy(order3.id, console.log);
    });
  });
});

var Physician = ds.createModel('Physician', {
  name: String
});

var Patient = ds.createModel('Patient', {
  name: String
});

var Appointment = ds.createModel('Appointment', {
  physicianId: Number,
  patientId: Number,
  appointmentDate: Date
});

Appointment.belongsTo(Patient);
Appointment.belongsTo(Physician);

Physician.hasMany(Patient, {through: Appointment});
Patient.hasMany(Physician, {through: Appointment});

Physician.create({name: 'Dr John'}, function (err, physician1) {
  Physician.create({name: 'Dr Smith'}, function (err, physician2) {
    Patient.create({name: 'Mary'}, function (err, patient1) {
      Patient.create({name: 'Ben'}, function (err, patient2) {
        Appointment.create({appointmentDate: new Date(), physicianId: physician1.id, patientId: patient1.id},
          function (err, appt1) {
            Appointment.create({appointmentDate: new Date(), physicianId: physician1.id, patientId: patient2.id},
              function (err, appt2) {
                physician1.patients(console.log);
                physician1.patients({where: {name: 'Mary'}}, console.log);
                patient1.physicians(console.log);

                // Build an appointment?
                var patient3 = patient1.physicians.build({name: 'Dr X'});
                console.log('Physician 3: ', patient3, patient3.constructor.modelName);

                // Create a physician?
                patient1.physicians.create({name: 'Dr X'}, function(err, patient4) {
                  console.log('Physician 4: ', patient4, patient4.constructor.modelName);
                });

              });
          });
      });
    });
  });
});

var Assembly = ds.createModel('Assembly', {
  name: String
});

var Part = ds.createModel('Part', {
  partNumber: String
});

Assembly.hasAndBelongsToMany(Part);
Part.hasAndBelongsToMany(Assembly);

Assembly.create({name: 'car'}, function (err, assembly) {
  Part.create({partNumber: 'engine'}, function (err, part) {
    assembly.parts.add(part, function (err) {
      assembly.parts(function(err, parts) {
        console.log('Parts: ', parts);
      });

      // Build an part?
      var part3 = assembly.parts.build({partNumber: 'door'});
      console.log('Part3: ', part3, part3.constructor.modelName);

      // Create a part?
      assembly.parts.create({partNumber: 'door'}, function(err, part4) {
        console.log('Part4: ', part4, part4.constructor.modelName);

        Assembly.find({include: 'parts'}, function(err, assemblies) {
          console.log('Assemblies: ', assemblies);
        });
      });
    });

  });
});

<commit_msg>Add a path to show customer.orders(query, cb)<commit_after>var DataSource = require('../index').DataSource;
var ds = new DataSource('memory');

var Order = ds.createModel('Order', {
  items: [String],
  orderDate: Date,
  qty: Number
});

var Customer = ds.createModel('Customer', {
  name: String
});

Order.belongsTo(Customer);

var order1, order2, order3;

Customer.create({name: 'John'}, function (err, customer) {
  Order.create({customerId: customer.id, orderDate: new Date(), items: ['Book']}, function (err, order) {
    order1 = order;
    order.customer(console.log);
    order.customer(true, console.log);

    Customer.create({name: 'Mary'}, function (err, customer2) {
      order.customer(customer2);
      order.customer(console.log);
    });
  });

  Order.create({orderDate: new Date(), items: ['Phone']}, function (err, order) {

    order.customer.create({name: 'Smith'}, function(err, customer2) {
      console.log(order, customer2);
      order.save(function(err, order) {
        order2 = order;
      });
    });

    var customer3 = order.customer.build({name: 'Tom'});
    console.log('Customer 3', customer3);
  });
});

Customer.hasMany(Order, {as: 'orders', foreignKey: 'customerId'});

Customer.create({name: 'Ray'}, function (err, customer) {
  Order.create({customerId: customer.id, qty: 3, orderDate: new Date()}, function (err, order) {
    order3 = order;
    customer.orders(console.log);
    customer.orders.create({orderDate: new Date(), qty: 4}, function (err, order) {
      console.log(order);
      Customer.include([customer], 'orders', function (err, results) {
        console.log('Results: ', results);
      });
      customer.orders({where: {qty: 4}}, function(err, results) {
        console.log('customer.orders', results);
      });
      customer.orders.findById(order3.id, console.log);
      customer.orders.destroy(order3.id, console.log);
    });
  });
});

var Physician = ds.createModel('Physician', {
  name: String
});

var Patient = ds.createModel('Patient', {
  name: String
});

var Appointment = ds.createModel('Appointment', {
  physicianId: Number,
  patientId: Number,
  appointmentDate: Date
});

Appointment.belongsTo(Patient);
Appointment.belongsTo(Physician);

Physician.hasMany(Patient, {through: Appointment});
Patient.hasMany(Physician, {through: Appointment});

Physician.create({name: 'Dr John'}, function (err, physician1) {
  Physician.create({name: 'Dr Smith'}, function (err, physician2) {
    Patient.create({name: 'Mary'}, function (err, patient1) {
      Patient.create({name: 'Ben'}, function (err, patient2) {
        Appointment.create({appointmentDate: new Date(), physicianId: physician1.id, patientId: patient1.id},
          function (err, appt1) {
            Appointment.create({appointmentDate: new Date(), physicianId: physician1.id, patientId: patient2.id},
              function (err, appt2) {
                physician1.patients(console.log);
                physician1.patients({where: {name: 'Mary'}}, console.log);
                patient1.physicians(console.log);

                // Build an appointment?
                var patient3 = patient1.physicians.build({name: 'Dr X'});
                console.log('Physician 3: ', patient3, patient3.constructor.modelName);

                // Create a physician?
                patient1.physicians.create({name: 'Dr X'}, function(err, patient4) {
                  console.log('Physician 4: ', patient4, patient4.constructor.modelName);
                });

              });
          });
      });
    });
  });
});

var Assembly = ds.createModel('Assembly', {
  name: String
});

var Part = ds.createModel('Part', {
  partNumber: String
});

Assembly.hasAndBelongsToMany(Part);
Part.hasAndBelongsToMany(Assembly);

Assembly.create({name: 'car'}, function (err, assembly) {
  Part.create({partNumber: 'engine'}, function (err, part) {
    assembly.parts.add(part, function (err) {
      assembly.parts(function(err, parts) {
        console.log('Parts: ', parts);
      });

      // Build an part?
      var part3 = assembly.parts.build({partNumber: 'door'});
      console.log('Part3: ', part3, part3.constructor.modelName);

      // Create a part?
      assembly.parts.create({partNumber: 'door'}, function(err, part4) {
        console.log('Part4: ', part4, part4.constructor.modelName);

        Assembly.find({include: 'parts'}, function(err, assemblies) {
          console.log('Assemblies: ', assemblies);
        });
      });
    });

  });
});

<|endoftext|>


<commit_before>'use strict';

var sjl  = require('sjl');
var path = require('path');
var P    = require('bluebird');

var defaults =
{
    'PROXY':
    {
        'PORT': 9999
    },

    'PIPELINE': 'etc/gate.d/default'
};

var confPath = process.env.CONF_PATH || '.';
    confPath = path.join(confPath, 'gate.json');

module.exports =
{
    load: function()
    {
        return new P(function(resolve, reject)
        {
            sjl(confPath, defaults, {'silent': true})
            .then(function(conf)
            {
                if (conf)
                {
                    resolve(conf);
                }
                else
                {
                    reject(new Error('Could not load configuration'));
                }
            });
        });
    }
};
<commit_msg>Removed some useless default configuration: better fail than load wrong settings<commit_after>'use strict';

var sjl  = require('sjl');
var path = require('path');
var P    = require('bluebird');

var confPath = process.env.CONF_PATH || '.';
    confPath = path.join(confPath, 'gate.json');

module.exports =
{
    load: function()
    {
        return new P(function(resolve, reject)
        {
            sjl(confPath, {}, {'silent': true})
            .then(function(conf)
            {
                if (conf)
                {
                    resolve(conf);
                }
                else
                {
                    reject(new Error('Could not load configuration'));
                }
            })
            .catch(reject);
        });
    }
};
<|endoftext|>


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

const Z_IDX_CELL_FRONT = 30
const Z_IDX_ITEM = 20
const Z_IDX_CELL_BACK = 10

class GridListDOM {

  constructor (rootElement, options) {

    this.dom = {
      root: rootElement,
      items: [],
      cells: []
    }

    this.options = options

    this.gridList = new GridList([], {
      direction: options.direction,
      lanes: options.lanes
    })

    this.updateLayout()
  }

  get vertical () {
    return this.options.direction == 'vertical'
  }

  setRootCSS () {

    this.dom.root.style.display = 'grid'

    const lanes = this.options.lanes || '6'
    const cs = this.options.cellSize || '100px'//'1fr'
    const gs = this.options.gutterSize || '10px'

    if (this.vertical) {
      Object.assign(this.dom.root.style, {
        gridTemplateColumns: `repeat(${lanes}, [col] ${cs} [gutter] ${gs})`,
        gridTemplateRows: `repeat(100, [row] ${cs} [gutter] ${gs})`
      })
    } else {
      Object.assign(this.dom.root.style, {
        gridTemplateColumns: `repeat(100, [col] ${cs} [gutter] ${gs})`,
        gridTemplateRows: `repeat(${lanes}, [row] ${cs} [gutter] ${gs})`
      })
    }
  }

  updateLayout (newOptions = {}) {
    Object.assign(this.options, newOptions)
    this.setRootCSS()
    this.resizeGrid()
    this.reconstructTargetCells()
  }

  resizeGrid () {
    this.gridList.resizeGrid(this.options.lanes)

    this.gridList.items.forEach(item => {
      Object.assign(item.element.style, {
        gridColumn: `col ${item.x+1} / span gutter ${item.w}`,
        gridRow: `row ${item.y+1} / span gutter ${item.h}`,
        zIndex: Z_IDX_ITEM
      })

    })
  }

  reconstructTargetCells () {
    // return;
    this.dom.cells.forEach(cell => this.dom.root.removeChild(cell))
    this.dom.cells = []
    const grid = this.gridList.grid
    for (let icol = 0; icol < grid.length; ++icol) {
      const column = grid[icol]
      for (let irow = 0; irow < column.length; ++irow) {
        const [col, row] = this.vertical ? [irow, icol] : [icol, irow]
        const cell = window.document.createElement('div')

        cell.classList.add('grid-cell')
        cell.gridListPos = { col, row }
        Object.assign(cell.style, {
          // border: '1px dashed red',
          gridColumn: `col ${col+1} / span gutter 1`,
          gridRow: `row ${row+1} / span gutter 1`,
          zIndex: Z_IDX_CELL_BACK
        })

        cell.addEventListener('dragenter',
                              (e) => this.onTargetCellDragEnter(e),
                              false)

        cell.addEventListener('dragover',
                              (e) => this.onTargetCellDragOver(e),
                              false)

        this.dom.root.appendChild(cell)
        this.dom.cells.push(cell)
      }
    }
  }

  createTargetCell (col, row) {
    const cell = window.document.createElement('div')
    cell.classList.add('grid-cell')
    cell.gridListPos = { col, row }
    return cell
  }

  cellsToFront () {
    this.setCellLayerZIndex(Z_IDX_CELL_FRONT)
  }

  cellsToBack () {
    this.setCellLayerZIndex(Z_IDX_CELL_BACK)
  }

  setCellLayerZIndex (zIndex) {
    this.dom.cells.forEach(cell => cell.style.zIndex = zIndex)
  }

  /**
   * @param {HTMLElement} element
   * @param {{x,y,w,h}}   size
   */
  addItem(element, size) {

    this.addItem2(element, size)
    this.reconstructTargetCells()
  }

  addItem2 (element, size) {
    const item = Object.assign({}, size, {element})

    this.gridList.items.push(item)
    this.resizeGrid()

    // console.log('GRID', this.gridList, this.gridList.items, item)

    Object.assign(element.style, {
      gridColumn: `col ${item.x+1} / span gutter ${item.w}`,
      gridRow: `row ${item.y+1} / span gutter ${item.h}`,
      zIndex: Z_IDX_ITEM
    })

    this.makeDraggable(element)

    this.dom.root.appendChild(element)
    this.dom.items.push(element)

  }

  onTargetCellDragEnter (event) {

    console.log('ENTER DRAG AREA')

    const { col, row } = event.target.gridListPos
    const item = this.currentDrag

    if (!item) {
      return
    }

    console.log(`MOVE FROM ${item.x}, ${item.y} to ${col}, ${row}`)
    this.gridList.moveItemToPosition(item, [col, row])

    this.gridList.items.forEach(item => {
      Object.assign(item.element.style, {
        gridColumn: `col ${item.x+1} / span gutter ${item.w}`,
        gridRow: `row ${item.y+1} / span gutter ${item.h}`,
        zIndex: Z_IDX_ITEM
      })
    })
  }

  onTargetCellDragOver (event) {
    // prevents feedback-image returning to the origin
    if (event.preventDefault) {
      event.preventDefault()
    }
    event.dataTransfer.dropEffect = 'move'
  }

  onItemDragStart (event) {

    event.target.style.opacity = '0.7'
    event.dataTransfer.effectAllowed = 'move'
    event.dataTransfer.setData('text/html', '') // dummy payload

    console.log('FINSDIN', event.target)

    this.currentDrag = this.gridList.items.find(e => e.element === event.target)
    // console.log('CD', this.currentDrag)
    this.cellsToFront()
  }

  onItemDragEnd (event) {

  }

  makeDraggable (element) {
    //
    // element.setAttribute('draggable', 'true')
    // element.draggable = true

    element.childNodes[0].draggable = 'true'
    element.childNodes[0].ondragstart = (e) => {
      console.log('HANDLE RECEIVED', e)
      // element.draggable = true
      // // e.preventDefault()
      // console.log('FIREF DEOM CHILD')
      e.dataTransfer.setDragImage(element, 0, 0)
      this.onItemDragStart({
        target: element,
        dataTransfer: e.dataTransfer
      })
      // console.log('RETURNING')
    }

    const that = this

    function handleDragEnd (e) {
      console.log('DRAGEND')
      this.style.opacity = '1.0'
      that.cellsToBack();
    }

    element.childNodes[0].ondragend = (e) => {
      console.log('DRAGEND')
      element.style.opacity = '1.0'
      this.cellsToBack()
    }

    // element.addEventListener('dragstart', (e) => {
    //   console.log('ROOT RECEIVED')
    //   this.onItemDragStart(e)
    // }, false);
    // element.addEventListener('dragend', handleDragEnd, false);
  }

}

window.GridListDOM = GridListDOM

})(window)
<commit_msg>working on FF / Chrome<commit_after>(function (window) {
'use strict'

const Z_IDX_CELL_FRONT = 30
const Z_IDX_ITEM = 20
const Z_IDX_CELL_BACK = 10

class GridListDOM {

  constructor (rootElement, options) {

    this.dom = {
      root: rootElement,
      items: [],
      cells: []
    }

    this.options = options

    this.gridList = new GridList([], {
      direction: options.direction,
      lanes: options.lanes
    })

    this.updateLayout()
  }

  get vertical () {
    return this.options.direction == 'vertical'
  }

  setRootCSS () {

    this.dom.root.style.display = 'grid'

    const lanes = this.options.lanes || '6'
    const cs = this.options.cellSize || '100px'//'1fr'
    const gs = this.options.gutterSize || '10px'

    if (this.vertical) {
      Object.assign(this.dom.root.style, {
        gridTemplateColumns: `repeat(${lanes}, [col] ${cs} [gutter] ${gs})`,
        gridTemplateRows: `repeat(100, [row] ${cs} [gutter] ${gs})`
      })
    } else {
      Object.assign(this.dom.root.style, {
        gridTemplateColumns: `repeat(100, [col] ${cs} [gutter] ${gs})`,
        gridTemplateRows: `repeat(${lanes}, [row] ${cs} [gutter] ${gs})`
      })
    }
  }

  updateLayout (newOptions = {}) {
    Object.assign(this.options, newOptions)
    this.setRootCSS()
    this.resizeGrid()
    this.reconstructTargetCells()
  }

  resizeGrid () {
    this.gridList.resizeGrid(this.options.lanes)

    this.gridList.items.forEach(item => {
      Object.assign(item.element.style, {
        gridColumn: `col ${item.x+1} / span gutter ${item.w}`,
        gridRow: `row ${item.y+1} / span gutter ${item.h}`,
        zIndex: Z_IDX_ITEM
      })

    })
  }

  reconstructTargetCells () {
    // return;
    this.dom.cells.forEach(cell => this.dom.root.removeChild(cell))
    this.dom.cells = []
    const grid = this.gridList.grid
    for (let icol = 0; icol < grid.length; ++icol) {
      const column = grid[icol]
      for (let irow = 0; irow < column.length; ++irow) {
        const [col, row] = this.vertical ? [irow, icol] : [icol, irow]
        const cell = window.document.createElement('div')

        cell.classList.add('grid-cell')
        cell.gridListPos = { col, row }
        Object.assign(cell.style, {
          // border: '1px dashed red',
          gridColumn: `col ${col+1} / span gutter 1`,
          gridRow: `row ${row+1} / span gutter 1`,
          zIndex: Z_IDX_CELL_BACK
        })

        cell.addEventListener('dragenter',
                              (e) => this.onTargetCellDragEnter(e),
                              false)

        cell.addEventListener('dragover',
                              (e) => this.onTargetCellDragOver(e),
                              false)

        cell.ondragstart = (e) => {
          console.log('CELL DRAGSTART1!!!!!!')
        }

        this.dom.root.appendChild(cell)
        this.dom.cells.push(cell)
      }
    }
  }

  createTargetCell (col, row) {
    const cell = window.document.createElement('div')
    cell.classList.add('grid-cell')
    cell.gridListPos = { col, row }
    return cell
  }

  cellsToFront () {
    this.setCellLayerZIndex(Z_IDX_CELL_FRONT)
  }

  cellsToBack () {
    this.setCellLayerZIndex(Z_IDX_CELL_BACK)
  }

  setCellLayerZIndex (zIndex) {
    this.dom.cells.forEach(cell => cell.style.zIndex = zIndex)
  }

  /**
   * @param {HTMLElement} element
   * @param {{x,y,w,h}}   size
   */
  addItem(element, size) {

    this.addItem2(element, size)
    this.reconstructTargetCells()
  }

  addItem2 (element, size) {
    const item = Object.assign({}, size, {element})

    this.gridList.items.push(item)
    this.resizeGrid()

    // console.log('GRID', this.gridList, this.gridList.items, item)

    Object.assign(element.style, {
      gridColumn: `col ${item.x+1} / span gutter ${item.w}`,
      gridRow: `row ${item.y+1} / span gutter ${item.h}`,
      zIndex: Z_IDX_ITEM
    })

    this.makeDraggable(element)

    this.dom.root.appendChild(element)
    this.dom.items.push(element)

  }

  onTargetCellDragEnter (event) {

    console.log('ENTER DRAG AREA')

    const { col, row } = event.target.gridListPos
    const item = this.currentDrag

    if (!item) {
      return
    }

    console.log(`MOVE FROM ${item.x}, ${item.y} to ${col}, ${row}`)
    this.gridList.moveItemToPosition(item, [col, row])

    this.gridList.items.forEach(item => {
      Object.assign(item.element.style, {
        gridColumn: `col ${item.x+1} / span gutter ${item.w}`,
        gridRow: `row ${item.y+1} / span gutter ${item.h}`,
        zIndex: Z_IDX_ITEM
      })
    })
  }

  onTargetCellDragOver (event) {

    console.log('DRAG OVER AREA')

    // prevents feedback-image returning to the origin
    if (event.preventDefault) {
      event.preventDefault()
    }
    event.dataTransfer.dropEffect = 'move'
  }

  onItemDragStart (event) {

    event.target.style.opacity = '0.7'
    event.dataTransfer.effectAllowed = 'move'
    event.dataTransfer.setData('text/html', '') // dummy payload

    console.log('FINSDIN', event.target)

    this.currentDrag = this.gridList.items.find(e => e.element === event.target)

    setTimeout(() => {
      // timeout required by Chrome
      this.cellsToFront()
    }, 0)

  }

  onItemDragEnd (event) {

  }

  makeDraggable (element) {
    //
    // element.setAttribute('draggable', 'true')
    // element.draggable = true

    element.childNodes[0].draggable = 'true'
    element.childNodes[0].ondragstart = (e) => {
      console.log('HANDLE RECEIVED', e)
      // element.draggable = true
      // // e.preventDefault()
      // console.log('FIREF DEOM CHILD')
      e.dataTransfer.setDragImage(element, 0, 0)
      this.onItemDragStart({
        target: element,
        dataTransfer: e.dataTransfer
      })

      // e.preventDefault()

      // return false
      // console.log('RETURNING')
    }

    const that = this

    function handleDragEnd (e) {
      console.log('DRAGEND')
      this.style.opacity = '1.0'
      that.cellsToBack();
    }

    element.childNodes[0].ondragend = (e) => {
      console.log('DRAGEND')
      element.style.opacity = '1.0'
      this.cellsToBack()
    }

    // element.addEventListener('dragstart', (e) => {
    //   console.log('ROOT RECEIVED')
    //   this.onItemDragStart(e)
    // }, false);
    // element.addEventListener('dragend', handleDragEnd, false);
  }

}

window.GridListDOM = GridListDOM

})(window)
<|endoftext|>


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

var __ = require('underscore');

var storageUtil = require('../../../util/storage.util');
var utils = require('../../../util/utils');
// The dependent profiles required for preparing VM create profile
var VMStorageProfile = require('./vmStorageProfile');
var VMOsProfile = require('./vmOsProfile');
var VMHardwareProfile = require('./vmHardwareProfile');
var VMAvailabilitySetProfile = require('./vmAvailabilitySetProfile');
var VMNetworkProfile = require('./vmNetworkProfile');
var VMDiagnosticsProfile = require('./vmDiagnosticsProfile');

var $ = utils.getLocaleString;

function VMProfile(cli, resourceGroupName, params, serviceClients) {
  this.cli = cli;
  this.resourceGroupName = resourceGroupName;
  this.params = params;
  this.serviceClients = serviceClients;
}

__.extend(VMProfile.prototype, {
  generateVMProfile: function(_) {
    var vmProfile = this._parseVMProfileParams(this.params, _);

    var vmStorageProfile = new VMStorageProfile(this.cli, this.resourceGroupName, this.params, this.serviceClients);
    if (this.params.imageUrn) {
      // The Operating system profile is valid only when VM is created from platform image
      var vmOsProfile = new VMOsProfile(this.cli, this.params);
      var osProfileResult = vmOsProfile.generateOSProfile(_);
      vmProfile.osProfile = osProfileResult.profile;
    } else {
      // VM must be created either from an image (image-urn) or using an existing OS Disk
      if (!vmStorageProfile.hasAllOSDiskParams(this.params)) {
        throw new Error($('image-urn or os-disk-vhd parameter is required to create a VM'));
      }
    }

    var vmHardwareProfile = new VMHardwareProfile(this.cli, this.params);
    var hardwareProfileResult = vmHardwareProfile.generateHardwareProfile();
    vmProfile.hardwareProfile = hardwareProfileResult.profile;

    var storageProfileResult = vmStorageProfile.generateStorageProfile(_);
    vmProfile.storageProfile = storageProfileResult.profile;

    var vmAvailSetProfile = new VMAvailabilitySetProfile(this.cli, this.resourceGroupName, this.params, this.serviceClients);
    var availsetProfileResult = vmAvailSetProfile.generateAvailabilitySetProfile(_);
    vmProfile.availabilitySet = availsetProfileResult.profile;

    var vmNetworkProfile = new VMNetworkProfile(this.cli, this.resourceGroupName, this.params, this.serviceClients);
    var networkProfileResult = vmNetworkProfile.generateNetworkProfile(_);
    vmProfile.networkProfile = networkProfileResult.profile;

    if (this.params.tags && typeof this.params.tags === 'string') {
      vmProfile.tags = vmProfile.tags || {};
      vmProfile.tags = this._parseTags(vmProfile.tags, this.params.tags);
    }

    if (!utils.stringIsNullOrEmpty(this.params.licenseType)) {
      vmProfile.licenseType = this.params.licenseType;
    }

    // Diagnostics
    if (this.params.disableBootDiagnostics !== null || this.params.enableBootDiagnostics !== null || this.params.bootDiagnosticsStorageUri !== null) {
      if (this.params.enableBootDiagnostics && this.params.bootDiagnosticsStorageUri === null) {
        var stoInfo = storageProfileResult.storageAccountInfo;
        var stoProfile = null;

        if (stoInfo === null) {
          stoInfo = vmStorageProfile._createStorageAccountIfRequired(_);
        }

        if (stoInfo !== null && stoInfo.profile && stoInfo.profile.storageAccount) {
          stoProfile = stoInfo.profile.storageAccount;
        }
        else if (stoInfo !== null && stoInfo.profile) {
          stoProfile = stoInfo.profile;
        }

        if (stoProfile !== null && stoProfile.primaryEndpoints && stoProfile.primaryEndpoints.blob) {
          var foundElem = false;
          for (var itemKey in storageUtil.AccountTypeForChanging) {
            if (storageUtil.AccountTypeForChanging[itemKey] === stoProfile.sku.name) {
              foundElem = true;
              break;
            }
          }

          if (!foundElem) {
            // The storage type does not support boot diagnostics.
            // Generate hash code for dependent resource naming
            var hash = utils.getHash(this.resourceGroupName + this.params.location + this.params.imageUrn);
            var bootStorageName = ('clisto' + hash + this.params.vmName.replace('-', '')).slice(0, 24).toLowerCase();
            var createRequestProfile = {
              sku: { name: 'Standard_LRS' },
              kind: 'Storage',
              name: bootStorageName,
              location: this.params.location
            };
            this.serviceClients.storageManagementClient.storageAccounts.create(this.resourceGroupName, bootStorageName, createRequestProfile, _);
            var bootStoProfile = vmStorageProfile._findStorageAccount(bootStorageName, _);
            this.params.bootDiagnosticsStorageUri = bootStoProfile.primaryEndpoints.blob;
          }
          else {
            this.params.bootDiagnosticsStorageUri = stoProfile.primaryEndpoints.blob;
          }
        }
        else {
          this.params.disableBootDiagnostics = true;
          this.params.enableBootDiagnostics = false;
          this.params.bootDiagnosticsStorageUri = null;
        }
      }

      var vmDiagnosticsProfile = new VMDiagnosticsProfile(this.cli, this.params);
      var diagnosticsProfileResult = vmDiagnosticsProfile.generateDiagnosticsProfile();
      vmProfile.diagnosticsProfile = diagnosticsProfileResult.profile;
    }
    else {
      vmProfile.diagnosticsProfile = null;
    }

    // Plan
    if (this.params.plan) {
      vmProfile.plan = this.params.plan;
    }

    return {
      profile: vmProfile
    };
  },

  updateVMProfile: function(virtualMachine, _) {
    if (this.params.disableBootDiagnostics !== null || this.params.enableBootDiagnostics !== null || this.params.bootDiagnosticsStorageUri !== null) {
      if ((this.params.disableBootDiagnostics && this.params.enableBootDiagnostics) || (this.params.disableBootDiagnostics && this.params.bootDiagnosticsStorageUri)) {
        throw new Error($('Either only "--disable-boot-diagnostics" or "--enable-boot-diagnostics" with "--boot-diagnostics-storage-uri" can be specified.'));
      }
    }
    else if (!utils.atLeastOneParameIsSet([this.params.nicIds, this.params.nicNames, this.params.vmSize, this.params.newOsDiskSize]) && this.params.tags === true) {
      throw new Error($('At least one optional parameter should be specified.'));
    }

    if (this.params.nicIds || this.params.nicNames) {
      var vmNetworkProfile = new VMNetworkProfile(this.cli, this.resourceGroupName, this.params, this.serviceClients);
      var validNICs = vmNetworkProfile.validateNICs(_);
      virtualMachine.networkProfile.networkInterfaces = validNICs;
    }

    if (this.params.tags && typeof this.params.tags === 'string') {
      virtualMachine.tags = virtualMachine.tags || {};
      virtualMachine.tags = this._parseTags(virtualMachine.tags, this.params.tags);
    }

    if (this.params.tags === false) {
      virtualMachine.tags = {};
    }

    if (!utils.stringIsNullOrEmpty(this.params.vmSize)) {
      var vmHardwareProfile = new VMHardwareProfile(this.cli, this.params);
      virtualMachine.hardwareProfile = vmHardwareProfile.updateHardwareProfile(virtualMachine.hardwareProfile);
    }

    if (this.params.enableBootDiagnostics !== null) {
      var vmDiagnosticsProfile = new VMDiagnosticsProfile(this.cli, this.params);
      var diagnosticsProfileResult = vmDiagnosticsProfile.generateDiagnosticsProfile();
      virtualMachine.diagnosticsProfile = diagnosticsProfileResult.profile;
    }

    if (this.params.newOsDiskSize) {
      if (!virtualMachine.storageProfile) {
        virtualMachine.storageProfile = {};
      }
      if (!virtualMachine.storageProfile.osDisk) {
        virtualMachine.storageProfile.osDisk = {};
      }
      virtualMachine.storageProfile.osDisk.diskSizeGB = parseInt(this.params.newOsDiskSize);
    }

    return virtualMachine;
  },

  _parseTags: function(oldTags, tags) {
    var parsedTags = oldTags;
    utils.stringTrimEnd(tags, ';').split(';').forEach(function (tagValue) {
      var tv = tagValue.split('=');
      if (tv.length === 2) {
        parsedTags[tv[0]] = tv[1];
      } else {
        parsedTags[tv[0]] = '';
      }
    });

    return parsedTags;
  },

  _parseVMProfileParams: function(params, _) {
    if (!params.location) {
      params.location = this.cli.interaction.prompt($('Enter location: '), _);
    }

    if (!params.vmName) {
      params.vmName = this.cli.interaction.prompt($('Enter VM name: '), _);
    }

    var vmProfile = {
      name: params.vmName,
      location: params.location,
      tags: {},
      osProfile: null,
      hardwareProfile: null,
      storageProfile: null,
      availabilitySetReference: null,
      networkProfile: null,
      diagnosticsProfile: null
    };

    return vmProfile;
  }
});

module.exports = VMProfile;
<commit_msg>Fix #3248 on VM command's end.<commit_after>/**
 * Copyright (c) Microsoft.  All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

var __ = require('underscore');

var storageUtil = require('../../../util/storage.util');
var utils = require('../../../util/utils');
// The dependent profiles required for preparing VM create profile
var VMStorageProfile = require('./vmStorageProfile');
var VMOsProfile = require('./vmOsProfile');
var VMHardwareProfile = require('./vmHardwareProfile');
var VMAvailabilitySetProfile = require('./vmAvailabilitySetProfile');
var VMNetworkProfile = require('./vmNetworkProfile');
var VMDiagnosticsProfile = require('./vmDiagnosticsProfile');

var $ = utils.getLocaleString;

function VMProfile(cli, resourceGroupName, params, serviceClients) {
  this.cli = cli;
  this.resourceGroupName = resourceGroupName;
  this.params = params;
  this.serviceClients = serviceClients;
}

__.extend(VMProfile.prototype, {
  generateVMProfile: function(_) {
    var vmProfile = this._parseVMProfileParams(this.params, _);

    var vmStorageProfile = new VMStorageProfile(this.cli, this.resourceGroupName, this.params, this.serviceClients);
    if (this.params.imageUrn) {
      // The Operating system profile is valid only when VM is created from platform image
      var vmOsProfile = new VMOsProfile(this.cli, this.params);
      var osProfileResult = vmOsProfile.generateOSProfile(_);
      vmProfile.osProfile = osProfileResult.profile;
    } else {
      // VM must be created either from an image (image-urn) or using an existing OS Disk
      if (!vmStorageProfile.hasAllOSDiskParams(this.params)) {
        throw new Error($('image-urn or os-disk-vhd parameter is required to create a VM'));
      }
    }

    var vmHardwareProfile = new VMHardwareProfile(this.cli, this.params);
    var hardwareProfileResult = vmHardwareProfile.generateHardwareProfile();
    vmProfile.hardwareProfile = hardwareProfileResult.profile;

    var storageProfileResult = vmStorageProfile.generateStorageProfile(_);
    vmProfile.storageProfile = storageProfileResult.profile;

    var vmAvailSetProfile = new VMAvailabilitySetProfile(this.cli, this.resourceGroupName, this.params, this.serviceClients);
    var availsetProfileResult = vmAvailSetProfile.generateAvailabilitySetProfile(_);
    vmProfile.availabilitySet = availsetProfileResult.profile;

    var vmNetworkProfile = new VMNetworkProfile(this.cli, this.resourceGroupName, this.params, this.serviceClients);
    var networkProfileResult = vmNetworkProfile.generateNetworkProfile(_);
    vmProfile.networkProfile = networkProfileResult.profile;

    if (this.params.tags && typeof this.params.tags === 'string') {
      vmProfile.tags = vmProfile.tags || {};
      vmProfile.tags = this._parseTags(vmProfile.tags, this.params.tags);
    }

    if (!utils.stringIsNullOrEmpty(this.params.licenseType)) {
      vmProfile.licenseType = this.params.licenseType;
    }

    // Diagnostics
    if (this.params.disableBootDiagnostics !== null || this.params.enableBootDiagnostics !== null || this.params.bootDiagnosticsStorageUri !== null) {
      if (this.params.enableBootDiagnostics && this.params.bootDiagnosticsStorageUri === null) {
        var stoInfo = storageProfileResult.storageAccountInfo;
        var stoProfile = null;

        if (stoInfo === null) {
          stoInfo = vmStorageProfile._createStorageAccountIfRequired(_);
        }

        if (stoInfo !== null && stoInfo.profile && stoInfo.profile.storageAccount) {
          stoProfile = stoInfo.profile.storageAccount;
        }
        else if (stoInfo !== null && stoInfo.profile) {
          stoProfile = stoInfo.profile;
        }

        if (stoProfile !== null && stoProfile.primaryEndpoints && stoProfile.primaryEndpoints.blob) {
          var foundElem = false;
          for (var itemKey in storageUtil.AccountTypeForChanging) {
            if (storageUtil.AccountTypeForChanging[itemKey] === stoProfile.sku.name) {
              foundElem = true;
              break;
            }
          }

          if (!foundElem) {
            // The storage type does not support boot diagnostics.
            // Generate hash code for dependent resource naming
            var hash = utils.getHash(this.resourceGroupName + this.params.location + this.params.imageUrn);
            var bootStorageName = ('clisto' + hash + this.params.vmName.replace('-', '')).slice(0, 24).toLowerCase();
            var createRequestProfile = {
              sku: { name: 'Standard_LRS' },
              kind: 'Storage',
              name: bootStorageName,
              location: this.params.location
            };
            this.serviceClients.storageManagementClient.storageAccounts.create(this.resourceGroupName, bootStorageName, createRequestProfile, _);
            var bootStoProfile = vmStorageProfile._findStorageAccount(bootStorageName, _);
            this.params.bootDiagnosticsStorageUri = bootStoProfile.primaryEndpoints.blob;
          }
          else {
            this.params.bootDiagnosticsStorageUri = stoProfile.primaryEndpoints.blob;
          }
        }
        else {
          this.params.disableBootDiagnostics = true;
          this.params.enableBootDiagnostics = false;
          this.params.bootDiagnosticsStorageUri = null;
        }
      }

      var vmDiagnosticsProfile = new VMDiagnosticsProfile(this.cli, this.params);
      var diagnosticsProfileResult = vmDiagnosticsProfile.generateDiagnosticsProfile();
      vmProfile.diagnosticsProfile = diagnosticsProfileResult.profile;
    }
    else {
      vmProfile.diagnosticsProfile = null;
    }

    // Plan
    if (this.params.plan) {
      vmProfile.plan = this.params.plan;
    }

    return {
      profile: vmProfile
    };
  },

  updateVMProfile: function(virtualMachine, _) {
    if (this.params.disableBootDiagnostics !== null || this.params.enableBootDiagnostics !== null || this.params.bootDiagnosticsStorageUri !== null) {
      if ((this.params.disableBootDiagnostics && this.params.enableBootDiagnostics) || (this.params.disableBootDiagnostics && this.params.bootDiagnosticsStorageUri)) {
        throw new Error($('Either only "--disable-boot-diagnostics" or "--enable-boot-diagnostics" with "--boot-diagnostics-storage-uri" can be specified.'));
      }
    }
    else if (!utils.atLeastOneParameIsSet([this.params.nicIds, this.params.nicNames, this.params.vmSize, this.params.newOsDiskSize]) && this.params.tags === true) {
      throw new Error($('At least one optional parameter should be specified.'));
    }

    if (this.params.nicIds || this.params.nicNames) {
      var vmNetworkProfile = new VMNetworkProfile(this.cli, this.resourceGroupName, this.params, this.serviceClients);
      var validNICs = vmNetworkProfile.validateNICs(_);
      virtualMachine.networkProfile.networkInterfaces = validNICs;
    }

    if (this.params.tags && typeof this.params.tags === 'string') {
      virtualMachine.tags = virtualMachine.tags || {};
      virtualMachine.tags = this._parseTags(virtualMachine.tags, this.params.tags);
    }

    if (this.params.tags === false) {
      virtualMachine.tags = {};
    }

    if (!utils.stringIsNullOrEmpty(this.params.vmSize)) {
      var vmHardwareProfile = new VMHardwareProfile(this.cli, this.params);
      virtualMachine.hardwareProfile = vmHardwareProfile.updateHardwareProfile(virtualMachine.hardwareProfile);
    }

    if (this.params.enableBootDiagnostics !== null) {
      var vmDiagnosticsProfile = new VMDiagnosticsProfile(this.cli, this.params);
      var diagnosticsProfileResult = vmDiagnosticsProfile.generateDiagnosticsProfile();
      virtualMachine.diagnosticsProfile = diagnosticsProfileResult.profile;
    }

    if (this.params.newOsDiskSize) {
      if (!virtualMachine.storageProfile) {
        virtualMachine.storageProfile = {};
      }
      if (!virtualMachine.storageProfile.osDisk) {
        virtualMachine.storageProfile.osDisk = {};
      }
      virtualMachine.storageProfile.osDisk.diskSizeGB = parseInt(this.params.newOsDiskSize);
    }

    if (virtualMachine.networkProfile !== null && virtualMachine.networkProfile.networkInterfaces !== null) {
      var vmNics = virtualMachine.networkProfile.networkInterfaces;
      for (var nicIndex in vmNics) {
        if (utils.ignoreCaseEquals('' + vmNics[nicIndex].primary, 'true')) {
          vmNics[nicIndex].primary = true;
        }
        else if (utils.ignoreCaseEquals('' + vmNics[nicIndex].primary, 'false')) {
          vmNics[nicIndex].primary = false;
        }
      }
    }

    return virtualMachine;
  },

  _parseTags: function(oldTags, tags) {
    var parsedTags = oldTags;
    utils.stringTrimEnd(tags, ';').split(';').forEach(function (tagValue) {
      var tv = tagValue.split('=');
      if (tv.length === 2) {
        parsedTags[tv[0]] = tv[1];
      } else {
        parsedTags[tv[0]] = '';
      }
    });

    return parsedTags;
  },

  _parseVMProfileParams: function(params, _) {
    if (!params.location) {
      params.location = this.cli.interaction.prompt($('Enter location: '), _);
    }

    if (!params.vmName) {
      params.vmName = this.cli.interaction.prompt($('Enter VM name: '), _);
    }

    var vmProfile = {
      name: params.vmName,
      location: params.location,
      tags: {},
      osProfile: null,
      hardwareProfile: null,
      storageProfile: null,
      availabilitySetReference: null,
      networkProfile: null,
      diagnosticsProfile: null
    };

    return vmProfile;
  }
});

module.exports = VMProfile;
<|endoftext|>


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

    var copymitter = require('copymitter');

    module.exports = function(args, fn) {
        if (!args.from)
            fn(Error('"from" could not be empty"'));
        else if (!args.to)
            fn(Error('"to" could not be empty"'));
        else if (!args.files)
            fn(Error('"files" could not be empty"'));
        else
            processing(args.from, args.to, args.files.split(','), fn);
    };

    function processing(from, to, files, fn) {
        var cp, done;

        cp = copymitter(from, to, files);

        cp.on('error', function(error) {
            done = true;
            cp.abort();
            fn(error);
        });

        cp.on('end', function() {
            !done && fn();
        });
    }
})();
<commit_msg>chore(copy) rm iife<commit_after>'use strict';

var copymitter = require('copymitter');

module.exports = function(args, fn) {
    if (!args.from)
        fn(Error('"from" could not be empty"'));
    else if (!args.to)
        fn(Error('"to" could not be empty"'));
    else if (!args.files)
        fn(Error('"files" could not be empty"'));
    else
        processing(args.from, args.to, args.files.split(','), fn);
};

function processing(from, to, files, fn) {
    var cp, done;

    cp = copymitter(from, to, files);

    cp.on('error', function(error) {
        done = true;
        cp.abort();
        fn(error);
    });

    cp.on('end', function() {
        !done && fn();
    });
}
<|endoftext|>


<commit_before>/*
 *  url.js
 *
 *  A lightweight JavaScript library that modifies the page url without refresh.
 *  Example:
 *
 *    Url.addSearch("param", "value");
 *
 *  Copyright (c) 2014 jillix GmbH
 *
 * */
(function (window) {

    /*
     *  Util query string function
     *  Thanks: http://stackoverflow.com/a/901144/1420197
     *
     * */
    function queryString (name) {
        name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
        var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
            results = regex.exec(location.search);
        return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
    }

    /*
     *  Replaces a character at known index
     *  http://stackoverflow.com/a/1431113/1420197
     *
     * */
    function replaceAt (word, start, end, character) {
        return word.substr(0, start) + character + word.substr(end + character.length);
    }

    /*
     * Adds a parameter=value to the url
     *
     * */
    function addSearch(param, value) {

        // get location search string
        var cSearch     = location.search

            // get current parameter value
          , cParamValue = queryString(param)

            // new search string will be modified
          , newSearch   = cSearch;

        // the parameter already exists and it is equal with the value
        if (cParamValue === value) {
            return;

        // the parameter already exists BUT it is NOT equal with the value
        } else if (cParamValue) {

            // get the index
            var cSearchIndex = cSearch.indexOf("?" + param + "=");

            // nothing found
            if (cSearchIndex < 0) {

                // try again with '&'
                cSearchIndex = cSearch.indexOf("&" + param + "=");
            }

            // get old value
            var oldValue = cSearch.substring(cSearchIndex + 2 + param.length)
              , indexOfAnd = oldValue.indexOf("&");

            if (indexOfAnd !== -1) {
                oldValue = oldValue.substring(0, indexOfAnd);
            }

            // set the new search parameter value
            newSearch = replaceAt(
                newSearch
              , cSearchIndex + 2 + param.length
              , cSearchIndex - 1 + param.length + oldValue.length
              , value
            );

        // the parameter DOESN'T exist
        } else {

            // add the new parameter
            newSearch = cSearch + (!cSearch ? "?" : "&") + param + "=" + value;
        }

        // and finally replace the state
        window.history.replaceState(null, "", newSearch + location.hash);
    }

    /*
     *  Returns the location
     *
     * */
    function getLocation () {
        return window.location.pathname + window.location.search + window.location.hash;
    }

    // export the Url object
    window.Url = {
        getLocation: getLocation
      , addSearch:   addSearch
      , queryString: queryString
    };
})(window);
<commit_msg>Started to fix the problem with updating search param<commit_after>/*
 *  url.js
 *
 *  A lightweight JavaScript library that modifies the page url without refresh.
 *  Example:
 *
 *    Url.addSearch("param", "value");
 *
 *  Copyright (c) 2014 jillix GmbH
 *
 * */
(function (window) {

    /*
     *  Util query string function
     *  Thanks: http://stackoverflow.com/a/901144/1420197
     *
     * */
    function queryString (name, notDecoded) {
        name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
        var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
            results = regex.exec(location.search);
        if (results == null) {
            return "";
        } else {
            var encoded = results[1].replace(/\+/g, " ");
            if (notDecoded) {
                return encoded;
            }
            return decodeURIComponent(encoded)
        }
    }

    /*
     *  Replaces a character at known index
     *  http://stackoverflow.com/a/1431113/1420197
     *
     * */
    function replaceAt (word, start, end, character) {
        return word.substr(0, start) + character + word.substr(end + character.length);
    }

    /*
     * Adds a parameter=value to the url
     *
     * */
    function addSearch(param, value) {

        // current search, old parameter value
        var cSearch     = location.search
          , newSearch   = cSearch
          , cParamValue = queryString(param, true)
          ;

        // encode value
        value = encodeURIComponent(value);

        // the parameter already exists and it is equal with the value
        if (cParamValue === value) {
            return;
        }

        // the parameter already exists BUT it is NOT equal with the value
        if (cParamValue) {

            // /?param=value%20anotherword&param2=1

            // get the index
            var cSearchIndex = cSearch.indexOf("?" + param + "=");
            if (cSearchIndex < 0) {
                cSearchIndex = cSearch.indexOf("&" + param + "=");
            }

            // get old value
            var oldValue = cSearch.substring(cSearchIndex + 2 + param.length)
              , indexOfAnd = oldValue.indexOf("&")
              ;

            if (indexOfAnd !== -1) {
                oldValue = oldValue.substring(0, indexOfAnd);
            }

            // set the new search parameter value
            newSearch = replaceAt(
                newSearch
              , cSearchIndex + 2 + param.length
              , cSearchIndex - 1 + param.length + oldValue.length
              , value
            );
        // the parameter DOESN'T exist
        // add the new parameter
        } else {
            newSearch = cSearch + (!cSearch ? "?" : "&") + param + "=" + value;
        }

        // and finally replace the state
        window.history.replaceState(null, "", newSearch + location.hash);
    }

    /*
     *  Returns the location
     *
     * */
    function getLocation () {
        return window.location.pathname + window.location.search + window.location.hash;
    }

    // export the Url object
    window.Url = {
        getLocation: getLocation
      , addSearch:   addSearch
      , queryString: queryString
    };
})(window);
<|endoftext|>


<commit_before>/*
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 *
*/

var exec = require('cordova/exec');
var channel = require('cordova/channel');
var modulemapper = require('cordova/modulemapper');

function InAppBrowser() {
   this.channels = {
        'loadstart': channel.create('loadstart'),
        'loadstop' : channel.create('loadstop'),
        'loaderror' : channel.create('loaderror'),
        'exit' : channel.create('exit')
   };
}

InAppBrowser.prototype = {
    _eventHandler: function (event) {
        if (event.type in this.channels) {
            this.channels[event.type].fire(event);
        }
    },
    close: function (eventname) {
        exec(null, null, "InAppBrowser", "close", []);
    },
    addEventListener: function (eventname,f) {
        if (eventname in this.channels) {
            this.channels[eventname].subscribe(f);
        }
    },
    removeEventListener: function(eventname, f) {
        if (eventname in this.channels) {
            this.channels[eventname].unsubscribe(f);
        }
    },
    executeScript: function(injectDetails, cb) {
        var script,
            sourceString;
        if (injectDetails.code) {
            exec(cb, null, "InAppBrowser", "injectScriptCode", [injectDetails.code]);
        } else if (injectDetails.file) {
            sourceString = JSON.stringify(injectDetails.file);
            script = "(function(d) { var c = d.createElement('script'); c.src = " + sourceString + "; d.body.appendChild(c); })(document)";
            exec(cb, null, "InAppBrowser", "injectScriptCode", [script]);
        } else {
            throw new Error('executeScript requires exactly one of code or file to be specified');
        }
    },
    insertCSS: function(injectDetails, cb) {
        var script,
            sourceString;
        if (injectDetails.code) {
            sourceString = JSON.stringify(injectDetails.code);
            script = "(function(d) { var c = d.createElement('style'); c.innerHTML = " + sourceString + "; d.body.appendChild(c); })(document)";
            exec(cb, null, "InAppBrowser", "injectScriptCode", [script]);
        } else if (injectDetails.file) {
            sourceString = JSON.stringify(injectDetails.file);
            script = "(function(d) { var c = d.createElement('link'); c.rel='stylesheet', c.type='text/css'; c.href = " + sourceString + "; d.body.appendChild(c); })(document)";
            exec(cb, null, "InAppBrowser", "injectScriptCode", [script]);
        } else {
            throw new Error('insertCSS requires exactly one of code or file to be specified');
        }
    }
};

module.exports = function(strUrl, strWindowName, strWindowFeatures) {
    var iab = new InAppBrowser();
    var cb = function(eventname) {
       iab._eventHandler(eventname);
    };

    // Don't catch calls that write to existing frames (e.g. named iframes).
    if (window.frames && window.frames[strWindowName]) {
        var origOpenFunc = modulemapper.getOriginalSymbol(window, 'open');
        return origOpenFunc.apply(window, arguments);
    }

    exec(cb, cb, "InAppBrowser", "open", [strUrl, strWindowName, strWindowFeatures]);
    return iab;
};

<commit_msg>[CB-2785] Switch executeScript/injectCSS to call dedicated plugin methods<commit_after>/*
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 *
*/

var exec = require('cordova/exec');
var channel = require('cordova/channel');
var modulemapper = require('cordova/modulemapper');

function InAppBrowser() {
   this.channels = {
        'loadstart': channel.create('loadstart'),
        'loadstop' : channel.create('loadstop'),
        'loaderror' : channel.create('loaderror'),
        'exit' : channel.create('exit')
   };
}

InAppBrowser.prototype = {
    _eventHandler: function (event) {
        if (event.type in this.channels) {
            this.channels[event.type].fire(event);
        }
    },
    close: function (eventname) {
        exec(null, null, "InAppBrowser", "close", []);
    },
    addEventListener: function (eventname,f) {
        if (eventname in this.channels) {
            this.channels[eventname].subscribe(f);
        }
    },
    removeEventListener: function(eventname, f) {
        if (eventname in this.channels) {
            this.channels[eventname].unsubscribe(f);
        }
    },

    executeScript: function(injectDetails, cb) {
        if (injectDetails.code) {
            exec(cb, null, "InAppBrowser", "injectScriptCode", [injectDetails.code, !!cb]);
        } else if (injectDetails.file) {
            exec(cb, null, "InAppBrowser", "injectScriptFile", [injectDetails.file, !!cb]);
        } else {
            throw new Error('executeScript requires exactly one of code or file to be specified');
        }
    },

    insertCSS: function(injectDetails, cb) {
        if (injectDetails.code) {
            exec(cb, null, "InAppBrowser", "injectStyleCode", [injectDetails.code, !!cb]);
        } else if (injectDetails.file) {
            exec(cb, null, "InAppBrowser", "injectStyleFile", [injectDetails.file, !!cb]);
        } else {
            throw new Error('insertCSS requires exactly one of code or file to be specified');
        }
    }
};

module.exports = function(strUrl, strWindowName, strWindowFeatures) {
    var iab = new InAppBrowser();
    var cb = function(eventname) {
       iab._eventHandler(eventname);
    };

    // Don't catch calls that write to existing frames (e.g. named iframes).
    if (window.frames && window.frames[strWindowName]) {
        var origOpenFunc = modulemapper.getOriginalSymbol(window, 'open');
        return origOpenFunc.apply(window, arguments);
    }

    exec(cb, cb, "InAppBrowser", "open", [strUrl, strWindowName, strWindowFeatures]);
    return iab;
};

<|endoftext|>


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

    var copymitter  = require('copymitter'),
        mellow      = require('mellow');

    module.exports = function(socket, options) {
        if (!options)
            options = {};

        listen(socket, options);
    };

    function getRoot(root) {
        var value;

        if (typeof root === 'function')
            value = root();
        else
            value = root;

        return value;
    }

    function listen(socket, options) {
        var prefix  = options.prefix || 'spero',
            root    = options.root   || '/';

        socket.of(prefix)
            .on('connection', function(socket) {
                socket.on('copy', function(from, to, files) {
                    var value   = getRoot(root);

                    from        = mellow.pathToWin(from, value);
                    to          = mellow.pathToWin(to, value);
                    copy(socket, from, to, files);
                });

                socket.on('error', function(error) {
                    console.error('spero', error);
                });

                socket.on('disconnect', function() {
                    console.log('spero', 'disconnect');
                });
            })
            .on('error', function(error) {
                console.error(error);
            });
    }

    function copy(socket, from, to, files) {
        var cp = copymitter(from, to, files);

        socket.on('pause', cp.pause);

        cp.on('file', function(name) {
            socket.emit('file', name);
        });

        cp.on('progress', function(percent) {
            socket.emit('progress', percent);
        });

        cp.on('error', function(error, name, i, percent) {
            var msg         = error.code + ' :' + error.path,
                rm          = function() {
                    socket.removeListener('continue', onContinue);
                    socket.removeListener('abort', onAbort);
                },

                onAbort     = function() {
                    cp.abort();
                    rm();
                },

                onContinue  = function() {
                    cp.continue();
                    rm();
                };

            console.error(percent, ' -> ', name, ':', error.message);

            socket.emit('err', msg, name);
            socket.on('continue', onContinue);
            socket.on('abort',  onAbort);
        });

        cp.on('end', function() {
            socket.emit('end');
            socket.removeListener('pause', cp.pause);
        });
    }

})();
<commit_msg>feature(copy) emit progress on error<commit_after>(function() {
    'use strict';

    var copymitter  = require('copymitter'),
        mellow      = require('mellow');

    module.exports = function(socket, options) {
        if (!options)
            options = {};

        listen(socket, options);
    };

    function getRoot(root) {
        var value;

        if (typeof root === 'function')
            value = root();
        else
            value = root;

        return value;
    }

    function listen(socket, options) {
        var prefix  = options.prefix || 'spero',
            root    = options.root   || '/';

        socket.of(prefix)
            .on('connection', function(socket) {
                socket.on('copy', function(from, to, files) {
                    var value   = getRoot(root);

                    from        = mellow.pathToWin(from, value);
                    to          = mellow.pathToWin(to, value);
                    copy(socket, from, to, files);
                });

                socket.on('error', function(error) {
                    console.error('spero', error);
                });
            })
            .on('error', function(error) {
                console.error(error);
            });
    }

    function copy(socket, from, to, files) {
        var cp = copymitter(from, to, files);

        socket.on('pause', cp.pause);

        cp.on('file', function(name) {
            socket.emit('file', name);
        });

        cp.on('progress', function(percent) {
            socket.emit('progress', percent);
        });

        cp.on('error', function(error, name, i, percent) {
            var msg         = error.code + ' :' + error.path,
                rm          = function() {
                    socket.removeListener('continue', onContinue);
                    socket.removeListener('abort', onAbort);
                },

                onAbort     = function() {
                    cp.abort();
                    rm();
                },

                onContinue  = function() {
                    cp.continue();
                    rm();
                };

            socket.emit('err', msg, name);
            socket.emit('progress', percent);

            socket.on('continue', onContinue);
            socket.on('abort',  onAbort);
        });

        cp.on('end', function() {
            socket.emit('end');
            socket.removeListener('pause', cp.pause);
        });
    }

})();
<|endoftext|>


<commit_before>'use strict';

const path = require('path');
const HardSourceWebpackPlugin = require('hard-source-webpack-plugin');
const paths = require('./paths');
const Typeof = require('../utils/typeof');

let config = require('./webpack.config.base');

if (Typeof.isUndefined(config.output.filename)) {
	config.output.filename = '[name]-[chunkhash:8].js';
}
if (Typeof.isUndefined(config.output.chunkFilename)) {
	config.output.chunkFilename = '[name]-chunk-[chunkhash:8].js';
}

config.output.pathinfo = false;
config.devtool = false;

config.plugins.push(
	new HardSourceWebpackPlugin({
		cacheDirectory: path.join(
			paths.appCache,
			'hard-source',
			'[confighash]'
		),
		info: {
			mode: 'none',
			level: 'error',
		},
	})
);

config.mode = 'production';

module.exports = config;
<commit_msg>add HardSourceWebpackPlugin config<commit_after>'use strict';

const path = require('path');
const HardSourceWebpackPlugin = require('hard-source-webpack-plugin');
const paths = require('./paths');
const Typeof = require('../utils/typeof');

let config = require('./webpack.config.base');

if (Typeof.isUndefined(config.output.filename)) {
	config.output.filename = '[name]-[chunkhash:8].js';
}
if (Typeof.isUndefined(config.output.chunkFilename)) {
	config.output.chunkFilename = '[name]-chunk-[chunkhash:8].js';
}

config.output.pathinfo = false;
config.devtool = false;

config.plugins.push(
	new HardSourceWebpackPlugin({
		cacheDirectory: path.join(
			paths.appCache,
			'hard-source',
			'[confighash]'
		),
		// Either a string of object hash function given a webpack config.
		configHash: function(webpackConfig) {
			// node-object-hash on npm can be used to build this.
			return require('node-object-hash')({ sort: false }).hash(
				webpackConfig
			);
		},
		// Clean up large, old caches automatically.
		cachePrune: {
			// Caches younger than `maxAge` are not considered for deletion. They must
			// be at least this (default: 2 days) old in milliseconds.
			maxAge: 2 * 24 * 60 * 60 * 1000,
			// All caches together must be larger than `sizeThreshold` before any
			// caches will be deleted. Together they must be at least this
			// (default: 50 MB) big in bytes.
			sizeThreshold: 50 * 1024 * 1024,
		},
		info: {
			mode: 'none',
			level: 'error',
		},
	})
);

config.mode = 'production';

module.exports = config;
<|endoftext|>


<commit_before>'use strict';

var events = require('events');
var fs = require('fs');
var path = require('path');
var util = require('util');

var EventEmitter = events.EventEmitter;

var inherits = util.inherits;

/**
 * @emits {}
 * @param {String} directory Абсолютный путь
 * @param {Core}   parent
 */
function Core(directory, parent) {
  EventEmitter.call(this);

  this.path = directory;

  if (!parent) {
    return this;
  }

  if (!(parent instanceof Core)) {
    throw new Error('derive props from parent failed');
  }

  this._deriveProps(parent);
}

inherits(Core, EventEmitter);

var proto = Core.prototype;

/**
 * @param {Number} count
 */
proto._addOrders = function (count) {
  this._orders = (this._orders || 0) + (count || 1);
};

/**
 * @emits {done}
 */
proto._checkOrders = function () {
  if (this._orders === 0) {
    this.emit('done');
  }
};

/**
 * @param {Core} parent
 */
proto._deriveProps = function (parent) {
  var props = [
    '_block',
    '_elem',
    '_mod'
  ];

  props.forEach(function (prop) {
    if (parent[prop]) {
      this[prop] = parent[prop];
    }
  }, this);
};

/**
 * @param  {String}  dirname
 * @return {Boolean}
 */
proto._isMod = function (dirname) {
  return /^_\w/.test(dirname);
};

proto._removeOrder = function () {
  this._orders--;
};

/**
 * @emits {raw}
 */
proto._readdir = function () {
  var directory = this.path;
  var that = this;

  this.on('raw', this._stats);

  fs.readdir(directory, function (err, files) {
    if (err) {
      throw err;
    }

    that._addOrders(files.length);

    files.forEach(function (file) {
      that.emit('raw', path.join(directory, file), file);
    });

    that.removeListener('raw', that._stats);
  });
};

/**
 * @param  {String} suffix
 * @return {String}
 */
proto._resolveFilename = function (suffix) {
  return suffix.replace('?', this.name);
};

/**
 * @param  {String} filename
 * @return {String}
 */
proto._resolveFilepath = function (filename) {
  return path.join(this.path, filename);
};

/**
 * @emits {directory}
 * @emits {file}
 * @param {String}    filepath Абсолютный путь.
 * @param {String}    file
 */
proto._stats = function (filepath, file) {
  var that = this;

  fs.stat(filepath, function (err, stats) {
    if (err) {
      throw err;
    }

    that._removeOrder();

    if (stats.isDirectory()) {
      that.emit('directory', filepath, file);
    }

    if (stats.isFile()) {
      that.emit('file', filepath, file);
    }

    that._checkOrders();
  });
};

/**
 * @param  {String} suffix
 * @return {Core}
 */
proto.has = function (suffix) {
  var filename = this._resolveFilename(suffix);
  var filepath = this._resolveFilepath(filename);
  var that = this;

  this._addOrders();

  fs.stat(filepath, function (err, stats) {
    if (err && err.code !== 'ENOENT') {
      throw err;
    }

    that._removeOrder();

    if (stats.isFile()) {
      that.emit(suffix, filepath, filename);
    } else {
      that.emit(suffix, null, filename);
    }

    that._checkOrders();
  });

  return this;
};

/**
 * @return {Core}
 */
proto.read = function () {
  this.emit('done');
  return this;
};

module.exports = Core;
<commit_msg>Core inherits from Queue<commit_after>'use strict';

var fs = require('fs');
var path = require('path');
var util = require('util');

var Queue = require('./queue');

var inherits = util.inherits;

/**
 * @emits {}
 * @param {String} directory Абсолютный путь
 * @param {Core}   parent
 */
function Core(directory, parent) {
  Queue.call(this);

  this.path = directory;

  if (!parent) {
    return this;
  }

  if (!(parent instanceof Core)) {
    throw new Error('derive props from parent failed');
  }

  this._deriveProps(parent);
}

inherits(Core, Queue);

var proto = Core.prototype;

/**
 * @param {Core} parent
 */
proto._deriveProps = function (parent) {
  var props = [
    '_block',
    '_elem',
    '_mod'
  ];

  props.forEach(function (prop) {
    if (parent[prop]) {
      this[prop] = parent[prop];
    }
  }, this);
};

/**
 * @param  {String}  dirname
 * @return {Boolean}
 */
proto._isMod = function (dirname) {
  return /^_\w/.test(dirname);
};

/**
 * @emits {raw}
 */
proto._readdir = function () {
  var directory = this.path;
  var that = this;

  this.on('raw', this._stats);

  fs.readdir(directory, function (err, files) {
    if (err) {
      throw err;
    }

    that._addOrders(files.length);

    files.forEach(function (file) {
      that.emit('raw', path.join(directory, file), file);
    });

    that.removeListener('raw', that._stats);
  });
};

/**
 * @param  {String} suffix
 * @return {String}
 */
proto._resolveFilename = function (suffix) {
  return suffix.replace('?', this.name);
};

/**
 * @param  {String} filename
 * @return {String}
 */
proto._resolveFilepath = function (filename) {
  return path.join(this.path, filename);
};

/**
 * @emits {directory}
 * @emits {file}
 * @param {String}    filepath Абсолютный путь.
 * @param {String}    file
 */
proto._stats = function (filepath, file) {
  var that = this;

  fs.stat(filepath, function (err, stats) {
    if (err) {
      throw err;
    }

    that._removeOrder();

    if (stats.isDirectory()) {
      that.emit('directory', filepath, file);
    }

    if (stats.isFile()) {
      that.emit('file', filepath, file);
    }

    that._checkOrders();
  });
};

/**
 * @param  {String} suffix
 * @return {Core}
 */
proto.has = function (suffix) {
  var filename = this._resolveFilename(suffix);
  var filepath = this._resolveFilepath(filename);
  var that = this;

  this._addOrders();

  fs.stat(filepath, function (err, stats) {
    if (err && err.code !== 'ENOENT') {
      throw err;
    }

    that._removeOrder();

    if (stats.isFile()) {
      that.emit(suffix, filepath, filename);
    } else {
      that.emit(suffix, null, filename);
    }

    that._checkOrders();
  });

  return this;
};

/**
 * @return {Core}
 */
proto.read = function () {
  this.emit('done');
  return this;
};

module.exports = Core;
<|endoftext|>


<commit_before>
function SimpleStructure( mmtfData ){

    var d = mmtfData;

    function getBond( index ){
        return [
            d.bondStore.atomIndex1[ index ],
            d.bondStore.atomIndex2[ index ],
            d.bondStore.bondOrder[ index ]
        ];
    }

    function getAtom( index ){
        var groupIndex = d.atomStore.groupIndex[ index ];
        var group = d.groupMap[ d.groupStore.groupTypeId[ groupIndex ] ];
        var groupAtomOffset = d.groupStore.atomOffset[ groupIndex ];
        var groupAtomIndex = index - groupAtomOffset;
        return [
            groupIndex,
            d.atomStore.xCoord[ index ],
            d.atomStore.yCoord[ index ],
            d.atomStore.zCoord[ index ],
            d.atomStore.bFactor ? d.atomStore.bFactor[ index ] : null,
            group.atomInfo[ groupAtomIndex * 2 ],
            d.atomStore.atomId ? d.atomStore.atomId[ index ] : null,
            group.hetFlag,
            d.atomStore.altLabel ? String.fromCharCode( d.atomStore.altLabel[ index ] ) : null,
            group.atomInfo[ groupAtomIndex * 2 + 1 ],
            d.atomStore.insCode ? String.fromCharCode( d.atomStore.insCode[ index ] ) : null,
            d.atomStore.occupancy ? d.atomStore.occupancy[ index ] : null
        ];
    }

    function getGroup( index ){
        var group = d.groupMap[ d.groupStore.groupTypeId[ index ] ];
        var sstrucCode = d.groupStore.secStruct[ index ];
        return [
            d.groupStore.chainIndex[ index ],
            d.groupStore.atomOffset[ index ],
            d.groupStore.atomCount[ index ],
            d.groupStore.groupNum[ index ],
            group.resName,
            sstrucMap[ sstrucCode ]
        ];
    }

    function getChain( index ){
        var chainName = "";
        for( var k = 0; k < 4; ++k ){
            var code = d.chainStore.chainName[ 4 * index + k ];
            if( code ){
                chainName += String.fromCharCode( code );
            }else{
                break;
            }
        }
        return [
            d.chainStore.modelIndex[ index ],
            d.chainStore.groupOffset[ index ],
            d.chainStore.groupCount[ index ],
            chainName
        ];
    }

    function getModel( index ){
        return [
            d.modelStore.chainOffset[ index ],
            d.modelStore.chainCount[ index ]
        ];
    }

    function eachBond( callback ){
        for( var i = 0; i < d.numBonds; ++i ){
            callback.apply( null, getBond( i ) );
        }
    }

    function eachAtom( callback ){
        for( var i = 0; i < d.numAtoms; ++i ){
            callback.apply( null, getAtom( i ) );
        }
    }

    function eachGroup( callback ){
        for( var i = 0; i < d.numGroups; ++i ){
            callback.apply( null, getGroup( i ) );
        }
    }

    function eachChain( callback ){
        for( var i = 0; i < d.numChains; ++i ){
            callback.apply( null, getChain( i ) );
        }
    }

    function eachModel( callback ){
        for( var i = 0; i < d.numModels; ++i ){
            callback.apply( null, getModel( i ) );
        }
    }

    var sstrucMap = {
        "0": "i",  // pi helix
        "1": "s",  // bend
        "2": "h",  // alpha helix
        "3": "e",  // extended
        "4": "g",  // 3-10 helix
        "5": "b",  // bridge
        "6": "t",  // turn
        "7": "l",  // coil
        "-1": ""   // NA
    };

    // API

    this.unitCell = d.unitCell;
    this.spaceGroup = d.spaceGroup;
    this.bioAssembly = d.bioAssembly;
    this.pdbId = d.pdbId;
    this.title = d.title;

    this.numBonds = d.numBonds;
    this.numAtoms = d.numAtoms;
    this.numGroups = d.numGroups;
    this.numChains = d.numChains;
    this.numModels = d.numModels;

    this.bondStore = d.bondStore;
    this.atomStore = d.atomStore;
    this.groupStore = d.groupStore;
    this.chainStore = d.chainStore;
    this.modelStore = d.modelStore;

    this.groupMap = d.groupMap;

    this.getBond = getBond;
    this.getAtom = getAtom;
    this.getGroup = getGroup;
    this.getChain = getChain;
    this.getModel = getModel;

    this.eachBond = eachBond;
    this.eachAtom = eachAtom;
    this.eachGroup = eachGroup;
    this.eachChain = eachChain;
    this.eachModel = eachModel;

}
<commit_msg>renamed field according to spec<commit_after>
function SimpleStructure( mmtfData ){

    var d = mmtfData;

    function getBond( index ){
        return [
            d.bondStore.atomIndex1[ index ],
            d.bondStore.atomIndex2[ index ],
            d.bondStore.bondOrder[ index ]
        ];
    }

    function getAtom( index ){
        var groupIndex = d.atomStore.groupIndex[ index ];
        var group = d.groupMap[ d.groupStore.groupTypeId[ groupIndex ] ];
        var groupAtomOffset = d.groupStore.atomOffset[ groupIndex ];
        var groupAtomIndex = index - groupAtomOffset;
        return [
            groupIndex,
            d.atomStore.xCoord[ index ],
            d.atomStore.yCoord[ index ],
            d.atomStore.zCoord[ index ],
            d.atomStore.bFactor ? d.atomStore.bFactor[ index ] : null,
            group.atomInfo[ groupAtomIndex * 2 ],
            d.atomStore.atomId ? d.atomStore.atomId[ index ] : null,
            group.hetFlag,
            d.atomStore.altLabel ? String.fromCharCode( d.atomStore.altLabel[ index ] ) : null,
            group.atomInfo[ groupAtomIndex * 2 + 1 ],
            d.atomStore.insCode ? String.fromCharCode( d.atomStore.insCode[ index ] ) : null,
            d.atomStore.occupancy ? d.atomStore.occupancy[ index ] : null
        ];
    }

    function getGroup( index ){
        var group = d.groupMap[ d.groupStore.groupTypeId[ index ] ];
        var sstrucCode = d.groupStore.secStruct[ index ];
        return [
            d.groupStore.chainIndex[ index ],
            d.groupStore.atomOffset[ index ],
            d.groupStore.atomCount[ index ],
            d.groupStore.groupNum[ index ],
            group.groupName,
            sstrucMap[ sstrucCode ]
        ];
    }

    function getChain( index ){
        var chainName = "";
        for( var k = 0; k < 4; ++k ){
            var code = d.chainStore.chainName[ 4 * index + k ];
            if( code ){
                chainName += String.fromCharCode( code );
            }else{
                break;
            }
        }
        return [
            d.chainStore.modelIndex[ index ],
            d.chainStore.groupOffset[ index ],
            d.chainStore.groupCount[ index ],
            chainName
        ];
    }

    function getModel( index ){
        return [
            d.modelStore.chainOffset[ index ],
            d.modelStore.chainCount[ index ]
        ];
    }

    function eachBond( callback ){
        for( var i = 0; i < d.numBonds; ++i ){
            callback.apply( null, getBond( i ) );
        }
    }

    function eachAtom( callback ){
        for( var i = 0; i < d.numAtoms; ++i ){
            callback.apply( null, getAtom( i ) );
        }
    }

    function eachGroup( callback ){
        for( var i = 0; i < d.numGroups; ++i ){
            callback.apply( null, getGroup( i ) );
        }
    }

    function eachChain( callback ){
        for( var i = 0; i < d.numChains; ++i ){
            callback.apply( null, getChain( i ) );
        }
    }

    function eachModel( callback ){
        for( var i = 0; i < d.numModels; ++i ){
            callback.apply( null, getModel( i ) );
        }
    }

    var sstrucMap = {
        "0": "i",  // pi helix
        "1": "s",  // bend
        "2": "h",  // alpha helix
        "3": "e",  // extended
        "4": "g",  // 3-10 helix
        "5": "b",  // bridge
        "6": "t",  // turn
        "7": "l",  // coil
        "-1": ""   // NA
    };

    // API

    this.unitCell = d.unitCell;
    this.spaceGroup = d.spaceGroup;
    this.bioAssembly = d.bioAssembly;
    this.pdbId = d.pdbId;
    this.title = d.title;

    this.numBonds = d.numBonds;
    this.numAtoms = d.numAtoms;
    this.numGroups = d.numGroups;
    this.numChains = d.numChains;
    this.numModels = d.numModels;

    this.bondStore = d.bondStore;
    this.atomStore = d.atomStore;
    this.groupStore = d.groupStore;
    this.chainStore = d.chainStore;
    this.modelStore = d.modelStore;

    this.groupMap = d.groupMap;

    this.getBond = getBond;
    this.getAtom = getAtom;
    this.getGroup = getGroup;
    this.getChain = getChain;
    this.getModel = getModel;

    this.eachBond = eachBond;
    this.eachAtom = eachAtom;
    this.eachGroup = eachGroup;
    this.eachChain = eachChain;
    this.eachModel = eachModel;

}
<|endoftext|>