<commit_before>/*
    Written by mridul ahuja
    HOW TO USE :
        >> Load JQuery library
        >> Load autocomplete-lite.js library
        >> Initialize autocomplete on element and pass autocomplete list as an array

           EXAMPLE :

               <input type="text" id="autocomplete_input">

*/

jQuery.fn.extend({
    autocomplete_img_init: function (item_data, image_data) {
        me = $(this);

        var item_data_length = item_data.length;
        if(item_data_length === image_data.length)
        {
            var img_map = {};
            for(var i=0; i<item_data_length; i++)
            {
                img_map[item_data[i].toLowerCase()] = image_data[i];
            }

            mridautocomplete(me, item_data, img_map);
        }
        else
            console.error('Error : autocomplete-lite item count does not match the images count.');
    }
});

function mridautocomplete(input, item_data, image_data) {

    var mridautocomplete_timer = 0;

    if(!$('#mridautocomplete_css').length )
    {
        var img_dimensions = (parseInt(input.css('font-size')) - 2 ) + 'px';
        $('body').prepend('');
    }

    var item_dataList = [];

    if (Array.isArray(item_data)) {
        item_dataList = item_dataList.concat(item_data);
    } else {
        console.error('Error : autocomplete-lite takes an array as parameter. ' + typeof item_data + ' given');
        return;
    }

    var matchitem_data = function(input, item_dataList) {
        var reg = new RegExp(input.split('').join('\\w*').replace(/\W/, ""), 'i');
        return item_dataList.filter(function(item_data) {
            if (item_data.match(reg)) {
                return item_data;
            }
        });
    };

    var changeInput = function(input, item_dataList) {
        var val = input.val().toLowerCase();
        var inputAncestor = input.parent();
        var res = inputAncestor.find('.mridautocomplete-list');
        while(res.length == 0) {
          inputAncestor = inputAncestor.parent();
          res = inputAncestor.find('.mridautocomplete-list');
        }

        res.empty().hide();

        var autoCompleteResult = matchitem_data(val, item_dataList);
        if (val == "" || autoCompleteResult.length == 0) {
            return;
        }

        autoCompleteResult.forEach(function(e) {
            var p = $('
');
            p.css({
              'margin': '0px',
              'padding-left': parseInt(input.css('padding-left'),10) + parseInt(input.css('border-left-width'),10),
              'text-align': 'left',
              'font-size': input.css('font-size'),
              'cursor': 'default'
            });

            p.addClass('mrid-autocomplete-item');

            e = e.toLowerCase();

            if(e.includes(val))
            {
                var first_part = e.split(val)[0];
                var second_part = e.split(val).splice(1).join(val);

                p.html('' + first_part + '' + val + '' + second_part);
            }

            p.click(function() {
                input.val(p.text());
                res.empty().hide();
            })
            p.mouseenter(function() {
                $(this).css("background-color", "#DCDCDC");
            }).mouseleave(function() {
                $(this).css("background-color", "white");
            });
            res.append(p);
        });

        res.css({
            'left': input.position().left,
            'width': input.css('width'),
            'position': 'absolute',
            'background-color': "white",
            'border': '1px solid #dddddd',
            'max-height': '150px',
            'overflow': 'scroll',
            'overflow-x': 'hidden',
            'font-family': input.css('font-family'),
            'font-size' : input.css('font-size'),
            'z-index' : '10'
        }).insertAfter(input).show();
    };

    var res = $("
");
    res.insertAfter(input);

    input.keyup(function() {
        clearTimeout(mridautocomplete_timer);
        mridautocomplete_timer = setTimeout(function() {
                changeInput(input, item_dataList);
        }, 100);
    });

    input.keydown(function() {
            clearTimeout(mridautocomplete_timer);
    });

    function search(input, item_dataList) {
        console.log(mridautocomplete_srch);
    }

    $(document).click(function(event) {
      if (!$(event.target).closest('.mridautocomplete-list').length) {
        res.empty().hide();
      }
    });
}<commit_msg>Fix autocomplete-lite-img.js<commit_after>/*
    Written by mridul ahuja
    HOW TO USE :
        >> Load JQuery library
        >> Load autocomplete-lite.js library
        >> Initialize autocomplete on element and pass autocomplete list as an array

           EXAMPLE :

               <input type="text" id="autocomplete_input">

*/

jQuery.fn.extend({
    autocomplete_img_init: function (item_data, image_data) {
        me = $(this);

        var item_data_length = item_data.length;
        if(item_data_length === image_data.length)
        {
            var img_map = {};
            for(var i=0; i<item_data_length; i++)
            {
                img_map[item_data[i].toLowerCase()] = image_data[i];
            }

            mridautocomplete(me, item_data, img_map);
        }
        else
            console.error('Error : autocomplete-lite item count does not match the images count.');
    }
});

function mridautocomplete(input, item_data, image_data) {

    var mridautocomplete_timer = 0;

    if(!$('#mridautocomplete_css').length )
    {
        var img_dimensions = (parseInt(input.css('font-size')) - 2 ) + 'px';
        $('body').prepend('');
    }

    var item_dataList = [];

    if (Array.isArray(item_data)) {
        item_dataList = item_dataList.concat(item_data);
    } else {
        console.error('Error : autocomplete-lite takes an array as parameter. ' + typeof item_data + ' given');
        return;
    }

    var matchitem_data = function(input, item_dataList) {
        var reg = new RegExp(input.split('').join('\\w*').replace(/\W/, ""), 'i');
        return item_dataList.filter(function(item_data) {
            if (item_data.match(reg)) {
                return item_data;
            }
        });
    };

    var changeInput = function(input, item_dataList) {
        var val = input.val().toLowerCase();
        var inputAncestor = input.parent();
        var res = inputAncestor.find('.mridautocomplete-list');
        while(res.length == 0) {
          inputAncestor = inputAncestor.parent();
          res = inputAncestor.find('.mridautocomplete-list');
        }

        res.empty().hide();

        var autoCompleteResult = matchitem_data(val, item_dataList);
        if (val == "" || autoCompleteResult.length == 0) {
            return;
        }

        autoCompleteResult.forEach(function(e) {
            var p = $('
');
            p.css({
              'margin': '0px',
              'padding-left': parseInt(input.css('padding-left'),10) + parseInt(input.css('border-left-width'),10),
              'text-align': 'left',
              'font-size': input.css('font-size'),
              'cursor': 'default'
            });

            p.addClass('mrid-autocomplete-item');

            e = e.toLowerCase();

            if(e.includes(val))
            {
                var first_part = e.split(val)[0];
                var second_part = e.split(val).splice(1).join(val);

                p.html('' + first_part + '' + val + '' + second_part);
            }

            p.click(function() {
                input.val(p.text());
                res.empty().hide();
            })
            p.mouseenter(function() {
                $(this).css("background-color", "#DCDCDC");
            }).mouseleave(function() {
                $(this).css("background-color", "white");
            });
            res.append(p);
        });

        res.css({
            'left': input.position().left,
            'width': input.css('width'),
            'position': 'absolute',
            'background-color': "white",
            'border': '1px solid #dddddd',
            'max-height': '150px',
            'overflow': 'scroll',
            'overflow-x': 'hidden',
            'font-family': input.css('font-family'),
            'font-size' : input.css('font-size'),
            'z-index' : '8888'
        }).insertAfter(input).show();
    };

    var res = $("
");
    res.insertAfter(input);

    input.keyup(function() {
        clearTimeout(mridautocomplete_timer);
        mridautocomplete_timer = setTimeout(function() {
                changeInput(input, item_dataList);
        }, 100);
    });

    input.keydown(function() {
            clearTimeout(mridautocomplete_timer);
    });

    function search(input, item_dataList) {
        console.log(mridautocomplete_srch);
    }

    $(document).click(function(event) {
      if (!$(event.target).closest('.mridautocomplete-list').length) {
        res.empty().hide();
      }
    });
}<|endoftext|>


<commit_before>var EventEmitter = require('events').EventEmitter
  , util = require('util')
  , es = require('event-stream')
  ;

var gitHooks = require('./hooks');

function DefaultFrame (stream, emitter) {
  var result;
}

function make (op, length, next) {
  var result = es.through(write);
  var params = {op: op};
  var pending = length;
  var data;
  function finisher (r) {
    console.log('PENDING', pending, 'left');
    if (--pending == 0) {
      next( );
    }
  }
  var hook = gitHooks('dummy', params, finisher);
  hook.name = op;
  hook.stream = result;
  hook.params = params;
  function value (chunk) {
    if (chunk) {
      data = chunk;
    }
    return data;
  }
  hook.value = value;
  if (gitHooks.isHook(op)) {
    params.arguments = arguments;
    function finish (r) {
      if (r) { return result.end(params.lines); };
      return result.end( );
    }
    // missing params.lines
    hook = gitHooks(op, params, finish);
  }
  function write (chunk) {
    this.emit('data', hook.value(chunk));
  }
  return hook;
}

function Stream (emitters, opts) {

  var s = es.through(writer, end);
  // var s = es.through(write, end);
  function writer (chunk) {
    // console.log('should event emit', chunk, arguments);
    function next ( ) {
      console.log('NEXT', arguments);
    }
    var chain = [ ];
    // chunk.stream.write(chunk.value(chunk.params));
    this.emit('data', chunk);
  }
  /*
  function write (op, fetch, consume) {
    var params = {op: op};
    var result = es.through( );
    var chain = [ ];
    var hook = gitHooks('dummy', params, finisher);
    // take an incoming operation, like 'user', return a stream performing that
    // operation.
    var cancelled = false;
    function preventDefault ( ) {
      console.log("CANCELED");
      cancelled = true;
      result.end(null);
    }
    hook.preventDefault = preventDefault;
    function finisher (r) {
      if (!r) {
        cancelled = true;
      }
    };
    var handlers = emitters.listeners(op).length;
    var map = es.map(function (data, next) {
      var trigger = function trigger ( ) {
        // --handlers;
        console.log("LEFT", handlers);
        if (--handlers == 0) {
          result.emit('data', data);
          next(null, data);
        }
      }
      emitters.emit(op, hook, trigger);
      if (handlers == 0) {
        next(null, hook.value( ));
      }

    });

    chain.push(map);
    if (fetch) {
      var map = es.map(function (data, next) {
        next(null, fetch(data));
      });
      chain.push(map);
    }
    if (consume && fetch) {
      es.pipeline(result, chain, es.writeArray( function (err, body) {
        consume(err, body);
        result.end( );
      }));
    }

    this.emit('data', hook);
  }
  */
  function end ( ) {
    // when done
    // this.emit('data', '');
    this.end( );
  }

  function process (thing, cb) {
    // s.write(thing, cb);
    var handlers = emitters.listeners(thing).length;
    // function make (op, length, next) {
    var ev = make(thing, handlers, next);

    ev.stream.on('data', function (data) {
      console.log('LOG', 'data', data);
    });
    ev.stream.on('end', function (data) {
      console.log("END");
      if (data) {
        ev.value(data);
      }
      next( );
    });
    function next ( ) {
      cb(ev.value( ));
    }
    s.write(ev);
    return ev;
    // s.once('data', function (res
    // s.write(thing, fetch, consume);

  }

  s.process = process;

  return s;
}

module.exports = function init (opts) {
  // var emitter = new EventEmitter;
  // var emit = emitter.emit;
  var ev = new Events(opts);
  return ev;
};

function Events (opts) {
  EventEmitter.call(this);
  this.stream = Stream(this, opts);
}
util.inherits(Events, EventEmitter);
Events.prototype.user = function user (name, cb) {
  console.log('user', name);
  var hook = this.stream.process('user', function (result) {
    console.log('process user', arguments);
    cb(result);
  });
  var map = es.map(function each (data, n) {
    data.name = data.args.pop( );
    n(null, hook.value(data));
  });
  var chain = [ map ];
  hook.stream = es.pipeline(hook.stream, map);
  var body = hook.params;
  body.args = [name];
  hook.value(body);
  var handlers = this.listeners('user').length;
  var pending = handlers;
  function onEvents ( ) {
    console.log('finished events', pending);
    if (--pending == 0) {
      hook.stream.write.apply(hook.stream, hook.value( ));
      hook.stream.end( );
    }
  }
  this.emit(hook.name, hook, onEvents);

}

if (!module.parent) {
  console.log('MAIN');
  var ev = module.exports( );
  ev.on('user', function (hook, next) {
    console.log('every user request', hook.value( ), next);
    hook.stream = es.pipeline(hook.stream, es.map(function (data, N) {
      console.log(data);
      data.name = data.name.toUpperCase( );
      N(null, data);
    }));
    return next( );
  });
  ev.on('user', function (hook, next) {
    console.log('every user request 2', hook.value( ), next);
    hook.stream = es.pipeline(hook.stream, es.map(function (data, N) {
      console.log(data);
      data.name = data.name.toUpperCase( );
      data.profile = 'http://logins/' + data.name.toLowerCase( );
      N(null, data);
    }));
    return next( );
  });
  ev.user('bewest', function fetch (value) {
    console.log('USER returned value', value);
  });
}
<commit_msg>seems to be working reorg<commit_after>var EventEmitter = require('events').EventEmitter
  , util = require('util')
  , es = require('event-stream')
  ;

var gitHooks = require('./hooks');

function DefaultFrame (stream, emitter) {
  var result;
}

function make (op, length, next) {
  var result = es.through(write);
  var params = {op: op};
  var pending = length;
  var data;
  function finisher (r) {
    console.log('PENDING', pending, 'left');
    if (--pending == 0) {
      // hook.stream.write.apply(hook.stream, hook.value( ));
      // hook.stream.end( );
      next( );
    }
  }
  var hook = gitHooks('dummy', params, finisher);
  hook.name = op;
  hook.stream = result;
  hook.params = params;
  function value (chunk) {
    if (chunk) {
      data = chunk;
    }
    return data;
  }
  hook.value = value;
  if (gitHooks.isHook(op)) {
    params.arguments = arguments;
    function finish (r) {
      if (r) { return result.end(params.lines); };
      return result.end( );
    }
    // missing params.lines
    hook = gitHooks(op, params, finish);
  }
  function write (chunk) {
    this.emit('data', hook.value(chunk));
  }
  return hook;
}

function Stream (emitters, opts) {

  var s = es.through(writer, end);
  // var s = es.through(write, end);
  function writer (chunk) {
    // console.log('should event emit', chunk, arguments);
    function next ( ) {
      console.log('NEXT', arguments);
    }
    var chain = [ ];
    // chunk.stream.write(chunk.value(chunk.params));
    this.emit('data', chunk);
  }
  /*
  function write (op, fetch, consume) {
    var params = {op: op};
    var result = es.through( );
    var chain = [ ];
    var hook = gitHooks('dummy', params, finisher);
    // take an incoming operation, like 'user', return a stream performing that
    // operation.
    var cancelled = false;
    function preventDefault ( ) {
      console.log("CANCELED");
      cancelled = true;
      result.end(null);
    }
    hook.preventDefault = preventDefault;
    function finisher (r) {
      if (!r) {
        cancelled = true;
      }
    };
    var handlers = emitters.listeners(op).length;
    var map = es.map(function (data, next) {
      var trigger = function trigger ( ) {
        // --handlers;
        console.log("LEFT", handlers);
        if (--handlers == 0) {
          result.emit('data', data);
          next(null, data);
        }
      }
      emitters.emit(op, hook, trigger);
      if (handlers == 0) {
        next(null, hook.value( ));
      }

    });

    chain.push(map);
    if (fetch) {
      var map = es.map(function (data, next) {
        next(null, fetch(data));
      });
      chain.push(map);
    }
    if (consume && fetch) {
      es.pipeline(result, chain, es.writeArray( function (err, body) {
        consume(err, body);
        result.end( );
      }));
    }

    this.emit('data', hook);
  }
  */
  function end ( ) {
    // when done
    // this.emit('data', '');
    this.end( );
  }

  function process (thing, cb) {
    // s.write(thing, cb);
    var handlers = emitters.listeners(thing).length;
    // function make (op, length, next) {
    var ev = make(thing, handlers, next);

    ev.stream.on('data', function (data) {
      console.log('LOG', 'data', data);
    });
    ev.stream.on('end', function (data) {
      console.log("END");
      if (data) {
        ev.value(data);
      }
      cb(ev.value( ));
      // next( );
    });
    function next ( ) {
      // ev.strea
      ev.stream.write.apply(ev.stream, ev.value( ));
      console.log('process next');
      ev.stream.end( );
      // cb(ev.value( ));
    }
    s.write(ev);
    return ev;

  }

  s.process = process;

  return s;
}

module.exports = function init (opts) {
  // var emitter = new EventEmitter;
  // var emit = emitter.emit;
  var ev = new Events(opts);
  return ev;
};

function Events (opts) {
  EventEmitter.call(this);
  this.stream = Stream(this, opts);
}
util.inherits(Events, EventEmitter);
Events.prototype.process = function process (op, cb) {

  var hook = this.stream.process(op, function (result) {
    console.log('process op', op, arguments);
    cb(result);
  });
  var args = Array.prototype.slice.apply(arguments);
  op = args.shift( );
  console.log('op', op);
  cb = args.pop( );
  console.log('args', args);
  var body = hook.params;
  body.args = args;
  hook.value(body);
  function emit (stream) {
    stream.emit(hook.name, hook, hook.finish);
  }
  function map (fn) {
    return (hook.stream = es.pipeline(hook.stream, es.map(fn)));
  }
  hook.map = map;
  hook.inject = emit;
  // this.emit(hook.name, hook, hook.finish);
  return hook;
}
Events.prototype.user = function user (name, cb) {
  console.log('user', name);
  // var hook = this.stream.process('user', function (result) {
  var hook = this.process('user', name, function (result) {
    console.log('process user', arguments);
    cb(result);
  });
  var map = es.map(function each (data, n) {
    data.name = data.args.pop( );
    n(null, hook.value(data));
  });
  // var chain = [ map ];
  hook.stream = es.pipeline(hook.stream, map);
  /*
  var body = hook.params;
  body.args = [name];
  hook.value(body);
  */
  /*
  var handlers = this.listeners('user').length;
  var pending = handlers;
  function onEvents ( ) {
    console.log('finished events', pending);
    if (--pending == 0) {
      hook.stream.write.apply(hook.stream, hook.value( ));
      hook.stream.end( );
    }
  }
  */
  // this.emit(hook.name, hook, onEvents);
  // this.emit(hook.name, hook, hook.finish);
  hook.inject(this);
  // this.emit(hook.name, hook, hook.finish);

}

if (!module.parent) {
  console.log('MAIN');
  var ev = module.exports( );
  ev.on('user', function (hook, next) {
    console.log('every user request', hook.value( ), next);
    hook.stream = es.pipeline(hook.stream, es.map(function (data, N) {
      console.log(data);
      data.name = data.name.toUpperCase( );
      N(null, data);
    }));
    return next( );
  });
  ev.on('user', function (hook, next) {
    console.log('every user request 2', hook.value( ), next);
    hook.stream = es.pipeline(hook.stream, es.map(function (data, N) {
      console.log(data);
      data.name = data.name.toUpperCase( );
      data.profile = 'http://logins/' + data.name.toLowerCase( );
      N(null, data);
    }));
    return next( );
  });
  ev.user('bewest', function fetch (value) {
    console.log('USER returned value', value);
  });
}
<|endoftext|>


<commit_before>// IE<9 lacks Array.prototype.indexOf
if (!Array.prototype.indexOf) {
    Array.prototype.indexOf = function(needle) {
        for (i=0, l=this.length; i<l; ++i) {
            if (this[i] === needle) return i;
        }
        return -1;
    }
}

django.jQuery(function($){
    // Patch up urlify maps to generate nicer slugs in german
    if(typeof(Downcoder) != "undefined"){
        Downcoder.Initialize() ;
        Downcoder.map["ö"] = Downcoder.map["Ö"] = "oe";
        Downcoder.map["ä"] = Downcoder.map["Ä"] = "ae";
        Downcoder.map["ü"] = Downcoder.map["Ü"] = "ue";
    }

    /* .dataset.context instead of getAttribute would be nicer */
    var ItemEditor = JSON.parse(
        document.getElementById('item-editor-script').getAttribute('data-context'));

    $('h2:contains(' + ItemEditor.feincmsContentFieldsetName + ')').parent().replaceWith($('#main_wrapper'));

    var inlineGroups = (function() {
        var selector = [];
        $.each(ItemEditor.plugins, function(key, value) {
            selector.push('#' + key + '_set-group');
        });
        return $(selector.join(', '));
    })();

    var inlines = inlineGroups.find('.inline-related').detach();
    inlines.sort(function inlinesCompareFunction(a, b) {
        var aOrdering = $(a).find('.field-ordering input').val() || 1e9;
        var bOrdering = $(b).find('.field-ordering input').val() || 1e9;
        return Math.sign(aOrdering - bOrdering);
    });
    $('.order-machine').append(inlines);

    $('.order-machine .inline-related').not('.empty-form').each(function assignRegionDataAttribute() {
        var $this = $(this),
            region = $this.find('.field-region input').val();

        // Have to use attr() here because we want the data attribute to
        // be visible to selectors.
        $this.attr('data-region', region);
    });

    function moveEmptyFormsToEnd() {
        $('.order-machine').append(
            $('.order-machine .empty-form').detach()
        );
    }
    moveEmptyFormsToEnd();

    $(document).on('formset:added', function newForm(event, row, optionsPrefix) {
        moveEmptyFormsToEnd();

        var currentRegion = $('.tabs>.active').data('region');
        row.find('.field-region input').val(currentRegion);
        row.attr('data-region', currentRegion);
    });

    function selectRegion(name) {
        $('.tabs>div').removeClass('active').filter('[data-region="' + name + '"]').addClass('active');
        $('.order-machine .inline-related').not('.empty-form').hide().filter('[data-region="' + name + '"]').show();
    }

    $(document).on('click', '.tabs>div', function() {
        selectRegion($(this).data('region'));
    });

    $('.tabs>div:first').trigger('click');

    $('.order-machine').sortable({
        handle: 'h3',
        placeholder: '.placeholder'
    });
    $('.order-machine').on('click', '.delete>input[type=checkbox]', function() {
        $(this).closest('.inline-related')[this.checked ? 'addClass' : 'removeClass']('for-deletion');
    });

    $('form').submit(function(){
        $('.field-ordering input').each(function assignOrdering(index) {
            this.value = index;
        });

        var form = $(this);
        form.attr('action', form.attr('action') + window.location.hash);
        return true;
    });

    $(document).keydown(function handleCmdS(event) {
        if(event.which == 83 && event.metaKey) {
            $('form input[name=' + (event.shiftKey ? '_continue' : '_save') + ']').click();
            return false;
        }
    });

})
<commit_msg>Try that again<commit_after>// IE<9 lacks Array.prototype.indexOf
if (!Array.prototype.indexOf) {
    Array.prototype.indexOf = function(needle) {
        for (i=0, l=this.length; i<l; ++i) {
            if (this[i] === needle) return i;
        }
        return -1;
    }
}

django.jQuery(function($){
    // Patch up urlify maps to generate nicer slugs in german
    if(typeof(Downcoder) != "undefined"){
        Downcoder.Initialize() ;
        Downcoder.map["ö"] = Downcoder.map["Ö"] = "oe";
        Downcoder.map["ä"] = Downcoder.map["Ä"] = "ae";
        Downcoder.map["ü"] = Downcoder.map["Ü"] = "ue";
    }

    /* .dataset.context instead of getAttribute would be nicer */
    var ItemEditor = JSON.parse(
        document.getElementById('item-editor-script').getAttribute('data-context'));

    $('h2:contains(' + ItemEditor.feincmsContentFieldsetName + ')').parent().replaceWith($('#main_wrapper'));

    var inlineGroups = (function() {
        var selector = [];
        $.each(ItemEditor.plugins, function(key, value) {
            selector.push('#' + key + '_set-group');
        });
        return $(selector.join(', '));
    })();

    var inlines = inlineGroups.find('.inline-related').detach();
    inlines.sort(function inlinesCompareFunction(a, b) {
        var aOrdering = $(a).find('.field-ordering input').val() || 1e9;
        var bOrdering = $(b).find('.field-ordering input').val() || 1e9;
        return Math.sign(aOrdering - bOrdering);
    });
    $('.order-machine').append(inlines);

    $('.order-machine .inline-related').not('.empty-form').each(function assignRegionDataAttribute() {
        var $this = $(this),
            region = $this.find('.field-region input').val();

        // Have to use attr() here because we want the data attribute to
        // be visible to selectors.
        $this.attr('data-region', region);
    });

    function moveEmptyFormsToEnd() {
        $('.order-machine').append(
            $('.order-machine .empty-form').detach()
        );
    }
    moveEmptyFormsToEnd();

    $(document).on('formset:added', function newForm(event, row, optionsPrefix) {
        moveEmptyFormsToEnd();

        var currentRegion = $('.tabs>.active').data('region');
        row.find('.field-region input').val(currentRegion);
        row.attr('data-region', currentRegion);
    });

    function selectRegion(name) {
        $('.tabs>div').removeClass('active').filter('[data-region="' + name + '"]').addClass('active');
        $('.order-machine .inline-related').not('.empty-form').hide().filter('[data-region="' + name + '"]').show();
    }

    $(document).on('click', '.tabs>div', function() {
        selectRegion($(this).data('region'));
    });

    $('.tabs>div:first').trigger('click');

    $('.order-machine').sortable({
        handle: 'h3',
        placeholder: 'placeholder'
    });
    $('.order-machine').on('click', '.delete>input[type=checkbox]', function() {
        $(this).closest('.inline-related')[this.checked ? 'addClass' : 'removeClass']('for-deletion');
    });

    $('form').submit(function(){
        $('.field-ordering input').each(function assignOrdering(index) {
            this.value = index;
        });

        var form = $(this);
        form.attr('action', form.attr('action') + window.location.hash);
        return true;
    });

    $(document).keydown(function handleCmdS(event) {
        if(event.which == 83 && event.metaKey) {
            $('form input[name=' + (event.shiftKey ? '_continue' : '_save') + ']').click();
            return false;
        }
    });

})
<|endoftext|>


<commit_before>// express-path.js
// by @hyubs

"use strict";

var expressPath = function (app, routeParam, opt) {
	// Dependencies
	var fs = require('fs');
	var path = require('path');
	var RouteMap = require('./RouteMap');
	var RouteInfo = require('./RouteInfo');
	var ModuleHandler = require('./ModuleHandler');
	var MethodHandler = require('./MethodHandler');
	var ErrorHandler = require('./ErrorHandler');

	var MODULE_PATH = path.dirname(module.parent.parent.filename) + path.sep;

	opt = opt || {};

	var options = {
		controllersPath: ((typeof opt.controllersPath === 'undefined') ? ("controllers" + path.sep) : opt.controllersPath),
		middlewaresPath: ((typeof opt.controllersPath === 'undefined') ? ("middlewares" + path.sep) : opt.controllersPath),
		strict:          ((typeof opt.strict === 'undefined')          ? true : opt.strict),
		verbose:         ((typeof opt.verbose === 'undefined')         ? true : opt.verbose)
	};

	var errorHandler = new ErrorHandler({
		strict:  options.strict,
		verbose: options.verbose
	});

	var routeMap = new RouteMap();
	var routeInfo = new RouteInfo();
	var moduleHandler = new ModuleHandler();
	var methodHandler = new MethodHandler();

	var getModuleMethod = function (parentPath, mmPath) {
		if(routeInfo.isValidMMPath(mmPath)) {
			// If it is valid, then

			// Get the path of the controller and prefix it with the path to the controllers directory.
			var modulePath = parentPath + routeInfo.getModulePath(mmPath);

			// Check if the controller file exists.
			if(moduleHandler.fileExists(modulePath)) {
				// If it does, then

				// Retrieve the file creating an "instance".
				var moduleInstance = moduleHandler.getFile(modulePath);

				// Get the name of the method from the route info.
				var methodName = routeInfo.getMethod(mmPath);

				// Check if the method exists.
				if(methodHandler.exists(methodName, moduleInstance)) {
					// If it does, then

					// Retrieve the method.
					var method = methodHandler.get(methodName, moduleInstance);
					return method;
				}
				else {
					errorHandler.log("Could not load method for " + mmPath);
					return null;
				}
			}
			else {
				errorHandler.log("Module not found: " + controllerPath);
				return null;
			}
		}
		else {
			errorHandler.log("Invalid module-method path: " + mmPath);
			return null;
		}
	}

	// Get the map data. If routeParam was a path, then read that file.
	var map = routeMap.eval(MODULE_PATH + routeParam);

	// Check if the map is valid.
	if(routeMap.isValid(map)) {
		// If it is valid, then:

		// Loop through the map.
		for(var i in map) {
			// For each route info:
			var mapRow = map[i];

			// Get the URL path and sanitize it.
			var urlPath = mapRow[0];
			urlPath = routeInfo.sanitizeUrlPath(urlPath);

			// Get the controller-method path.
			var cmPath = mapRow[1];

			// Get the middleware-method paths.
			var mmPaths = [];
			for(var j = 2; j < mapRow.length - 1; j++) {
				mmPaths.push(mapRow[j]);
			}

			// Get the HTTP request method. If there's none, default to all.
			var httpRequestMethod;
			if(mapRow.length > 1) {
				httpRequestMethod = mapRow[mapRow.length - 1];
			}
			else {
				httpRequestMethod = 'all';
			}

			// Get the method of the controller
			var method = getModuleMethod(MODULE_PATH + options.controllersPath, cmPath);

			// Loop through all the middleware-method paths and retrieve each of the methods
			var middlewares = [];
			mmPaths.forEach(function(mmPath) {
				var middlewareMethod = getModuleMethod(MODULE_PATH + options.middlewaresPath, mmPath);
				middlewares.push(middlewareMethod);
			});

			// Finally, bind the route in the Express app
			app[httpRequestMethod](urlPath, middlewares, method);

			// If verbose is true, print out some info about the mapped routes
			if(options.verbose) {
				console.log('[' + httpRequestMethod.toUpperCase() + '] ' + urlPath + '  ->  ' + cmPath);
				if(mmPaths.length > 0) {
					console.log('    - middlewares (' + mmPaths.length + ')');
					mmPaths.forEach(function(mmPath) {
						console.log('        - ' + mmPath);
					})
				}
			}
		}
	}
	else {
		errorHandler.log("Route map should be an array. No route map defined.");
	}
};

module.exports = expressPath;

<commit_msg>Fixed incorrect check for the middlewarePath option<commit_after>// express-path.js
// by @hyubs

"use strict";

var expressPath = function (app, routeParam, opt) {
	// Dependencies
	var fs = require('fs');
	var path = require('path');
	var RouteMap = require('./RouteMap');
	var RouteInfo = require('./RouteInfo');
	var ModuleHandler = require('./ModuleHandler');
	var MethodHandler = require('./MethodHandler');
	var ErrorHandler = require('./ErrorHandler');

	var MODULE_PATH = path.dirname(module.parent.parent.filename) + path.sep;

	opt = opt || {};

	var options = {
		controllersPath: ((typeof opt.controllersPath === 'undefined') ? ("controllers" + path.sep) : opt.controllersPath),
		middlewaresPath: ((typeof opt.middlewaresPath === 'undefined') ? ("middlewares" + path.sep) : opt.controllersPath),
		strict:          ((typeof opt.strict === 'undefined')          ? true : opt.strict),
		verbose:         ((typeof opt.verbose === 'undefined')         ? true : opt.verbose)
	};

	var errorHandler = new ErrorHandler({
		strict:  options.strict,
		verbose: options.verbose
	});

	var routeMap = new RouteMap();
	var routeInfo = new RouteInfo();
	var moduleHandler = new ModuleHandler();
	var methodHandler = new MethodHandler();

	var getModuleMethod = function (parentPath, mmPath) {
		if(routeInfo.isValidMMPath(mmPath)) {
			// If it is valid, then

			// Get the path of the controller and prefix it with the path to the controllers directory.
			var modulePath = parentPath + routeInfo.getModulePath(mmPath);

			// Check if the controller file exists.
			if(moduleHandler.fileExists(modulePath)) {
				// If it does, then

				// Retrieve the file creating an "instance".
				var moduleInstance = moduleHandler.getFile(modulePath);

				// Get the name of the method from the route info.
				var methodName = routeInfo.getMethod(mmPath);

				// Check if the method exists.
				if(methodHandler.exists(methodName, moduleInstance)) {
					// If it does, then

					// Retrieve the method.
					var method = methodHandler.get(methodName, moduleInstance);
					return method;
				}
				else {
					errorHandler.log("Could not load method for " + mmPath);
					return null;
				}
			}
			else {
				errorHandler.log("Module not found: " + controllerPath);
				return null;
			}
		}
		else {
			errorHandler.log("Invalid module-method path: " + mmPath);
			return null;
		}
	}

	// Get the map data. If routeParam was a path, then read that file.
	var map = routeMap.eval(MODULE_PATH + routeParam);

	// Check if the map is valid.
	if(routeMap.isValid(map)) {
		// If it is valid, then:

		// Loop through the map.
		for(var i in map) {
			// For each route info:
			var mapRow = map[i];

			// Get the URL path and sanitize it.
			var urlPath = mapRow[0];
			urlPath = routeInfo.sanitizeUrlPath(urlPath);

			// Get the controller-method path.
			var cmPath = mapRow[1];

			// Get the middleware-method paths.
			var mmPaths = [];
			for(var j = 2; j < mapRow.length - 1; j++) {
				mmPaths.push(mapRow[j]);
			}

			// Get the HTTP request method. If there's none, default to all.
			var httpRequestMethod;
			if(mapRow.length > 1) {
				httpRequestMethod = mapRow[mapRow.length - 1];
			}
			else {
				httpRequestMethod = 'all';
			}

			// Get the method of the controller
			var method = getModuleMethod(MODULE_PATH + options.controllersPath, cmPath);

			// Loop through all the middleware-method paths and retrieve each of the methods
			var middlewares = [];
			mmPaths.forEach(function(mmPath) {
				var middlewareMethod = getModuleMethod(MODULE_PATH + options.middlewaresPath, mmPath);
				middlewares.push(middlewareMethod);
			});

			// Finally, bind the route in the Express app
			app[httpRequestMethod](urlPath, middlewares, method);

			// If verbose is true, print out some info about the mapped routes
			if(options.verbose) {
				console.log('[' + httpRequestMethod.toUpperCase() + '] ' + urlPath + '  ->  ' + cmPath);
				if(mmPaths.length > 0) {
					console.log('    - middlewares (' + mmPaths.length + ')');
					mmPaths.forEach(function(mmPath) {
						console.log('        - ' + mmPath);
					})
				}
			}
		}
	}
	else {
		errorHandler.log("Route map should be an array. No route map defined.");
	}
};

module.exports = expressPath;

<|endoftext|>


<commit_before>/*jshint laxcomma: true, smarttabs: true, node: true*/
'use strict';
/**
 * Resource Field for dealing with array values
 * @module tastypie/fields/array
 * @author Eric Satterwhite
 * @since 0.5.0
 * @requires mout/lang/kindOf
 * @requires tastypie/lib/class
 * @requires tastypie/lib/fields/api
 */

var kindOf         = require( 'mout/lang/kindOf'  )
  , Class          = require( '../class' )
  , ApiField       = require('./api')
  , ArrayField
  ;

/**
 * @constructor
 * @alias module:tastypie/fields/array
 * @extends module:tastypie/fields/api
 */
ArrayField = new Class({
	inherits: ApiField
	,options:{
		separator: ','
	  , help:'converts comma separated string into an array of value'

	}

	,type: function(){
		return 'array';
	}

	,convert: function( value ){
		var _val = [];
		switch( kindOf( value ).toLowerCase() ){
			case 'string':
				_val = value.split( this.options.separator );
				break;
			case 'array':
				_val = value;
				break;
			default:
				_val = value ? [ value ] : _val;
				break;
		}

		return _val;
	}

	,hydrate: function( bundle, cb ){
		this.parent('hydrate', bundle, function( err, value ){
			if( err ){
				cb && cb( err, null );
			}

			try{
				value = this.convert( kindOf(value) === 'String' ? JSON.parse( value ) : value );
			} catch( err ){
				value = this.convert( value );
			}

			cb(null, value );
		}.bind(this));
	}
});

module.exports = ArrayField;
<commit_msg>linting<commit_after>/*jshint laxcomma: true, smarttabs: true, node: true*/
'use strict';
/**
 * Resource Field for dealing with array values
 * @module tastypie/fields/array
 * @author Eric Satterwhite
 * @since 0.5.0
 * @requires mout/lang/kindOf
 * @requires tastypie/lib/class
 * @requires tastypie/lib/fields/api
 */

var kindOf         = require( 'mout/lang/kindOf'  )
  , Class          = require( '../class' )
  , ApiField       = require('./api')
  , ArrayField
  ;

/**
 * @constructor
 * @alias module:tastypie/fields/array
 * @extends module:tastypie/fields/api
 */
ArrayField = new Class({
	inherits: ApiField
	,options:{
		separator: ','
	  , help:'converts comma separated string into an array of value'

	}

	,type: function(){
		return 'array';
	}

	,convert: function( value ){
		var _val = [];
		switch( kindOf( value ).toLowerCase() ){
			case 'string':
				_val = value.split( this.options.separator );
				break;
			case 'array':
				_val = value;
				break;
			default:
				_val = value ? [ value ] : _val;
				break;
		}

		return _val;
	}

	,hydrate: function( bundle, cb ){
		this.parent('hydrate', bundle, function( err, value ){
			if( err ){
				return cb( err, null );
			}

			try{
				value = this.convert( kindOf(value) === 'String' ? JSON.parse( value ) : value );
			} catch( err ){
				value = this.convert( value );
			}

			return cb(null, value );
		}.bind(this));
	}
});

module.exports = ArrayField;
<|endoftext|>


<commit_before><commit_msg>Update project jssor.slider to 18.0<commit_after><|endoftext|>


<commit_before>/* eslint-disable no-magic-numbers,no-undef,semi */

user_pref('accessibility.force_disabled', 1);
user_pref('app.shield.optoutstudies.enabled', false);
user_pref('browser.cache.cache_isolation', true);
user_pref('browser.discovery.enabled', false);
user_pref('browser.fixup.alternate.enabled', false);
user_pref('browser.formfill.enable', false);
user_pref('browser.link.open_newwindow', 1);
user_pref('browser.newtabpage.enabled', false);
user_pref('browser.safebrowsing.downloads.remote.enabled', false);
user_pref('browser.urlbar.doubleClickSelectsAll', false);
user_pref('browser.urlbar.openViewOnFocus', false);
user_pref('browser.urlbar.speculativeConnect.enabled', false);
user_pref('browser.urlbar.update1', false);
user_pref('devtools.debugger.remote-enabled', false);
user_pref('devtools.inspector.activeSidebar', 'ruleview');
user_pref('devtools.inspector.showUserAgentStyles', true);
user_pref('devtools.inspector.three-pane-enabled', false);
user_pref('devtools.inspector.three-pane-first-run', false);
user_pref('dom.gamepad.enabled', false);
user_pref('dom.targetBlankNoOpener.enabled', true);
user_pref('extensions.activeThemeID', 'firefox-compact-light@mozilla.org');
user_pref('extensions.fxmonitor.enabled', false);
user_pref('extensions.htmlaboutaddons.recommendations.enabled', false);
user_pref('extensions.pocket.enabled', false);
user_pref('font.default.x-western', 'sans-serif');
user_pref('font.name.monospace.x-western', 'PragmataPro Mono Liga');
user_pref('font.name.sans-serif.el', 'Source Sans Pro');
user_pref('font.name.sans-serif.ja', 'Source Han Sans');
user_pref('font.name.sans-serif.ko', 'Source Han Sans K');
user_pref('font.name.sans-serif.x-cyrillic', 'Source Sans Pro');
user_pref('font.name.sans-serif.x-unicode', 'Source Sans Pro');
user_pref('font.name.sans-serif.x-western', 'Source Sans Pro');
user_pref('font.name.sans-serif.zh-CN', 'Source Han Sans SC');
user_pref('font.name.sans-serif.zh-HK', 'Source Han Sans HC');
user_pref('font.name.sans-serif.zh-TW', 'Source Han Sans TC');
user_pref('font.name.sans.x-western', 'Source Sans Pro');
user_pref('font.name.serif.el', 'Source Serif Pro');
user_pref('font.name.serif.ja', 'Source Han Serif');
user_pref('font.name.serif.ko', 'Source Han Serif K');
user_pref('font.name.serif.x-cyrillic', 'Source Serif Pro');
user_pref('font.name.serif.x-unicode', 'Source Sans Pro');
user_pref('font.name.serif.x-western', 'Source Serif Pro');
user_pref('font.name.serif.zh-CN', 'Source Han Serif SC');
user_pref('font.name.serif.zh-HK', 'Source Han Serif TC');
user_pref('font.name.serif.zh-TW', 'Source Han Serif TC');
user_pref('font.size.monospace.x-western', '16');
user_pref('gfx.color_management.enablev4', true);
user_pref('gfx.color_management.mode', 1);
user_pref('media.autoplay.default', 5);
user_pref('media.peerconnection.ice.default_address_only', true);
user_pref('media.peerconnection.ice.no_host', true);
user_pref('network.IDN_show_punycode', true);
user_pref('network.cookie.cookieBehavior', 1);
user_pref('network.cookie.thirdparty.sessionOnly', true);
user_pref('network.dns.disablePrefetch', true);
user_pref('network.http.referer.XOriginPolicy', 1);
user_pref('network.http.referer.XOriginTrimmingPolicy', 2);
user_pref('network.http.speculative-parallel-limit', 0);
user_pref('network.manage-offline-status', false);
user_pref('network.predictor.enabled', false);
user_pref('network.prefetch-next', false);
user_pref('network.proxy.socks_remote_dns', true);
user_pref('network.trr.mode', 5);
user_pref('permissions.default.desktop-notification', 2);
user_pref('permissions.default.geo', 2);
user_pref('plugin.state.flash', 0);
user_pref('privacy.clearOnShutdown.offlineApps', true);
user_pref('privacy.clearOnShutdown.siteSettings', true);
user_pref('privacy.firstparty.isolate', true);
user_pref('privacy.firstparty.isolate.restrict_opener_access', true);
user_pref('privacy.trackingprotection.cryptomining.enabled', true);
user_pref('privacy.trackingprotection.enabled', false); // Disable only if using uBlock Origin or similar
user_pref('privacy.trackingprotection.fingerprinting.enabled', true);
user_pref('privacy.trackingprotection.pbmode.enabled', false); // Disable only if using uBlock Origin or similar
user_pref('reader.content_width', 4);
user_pref('reader.font_size', 5);
user_pref('reader.font_type', 'sans-serif');
user_pref('reader.line_height', 3);
user_pref('security.mixed_content.block_display_content', true);
user_pref('security.mixed_content.block_object_subrequest', true);
user_pref('security.mixed_content.upgrade_display_content', true);
user_pref('signon.rememberSignons', false);
user_pref('toolkit.legacyUserProfileCustomizations.stylesheets', true);
user_pref('toolkit.telemetry.archive.enabled', false);
user_pref('toolkit.telemetry.enabled', false);
user_pref('toolkit.telemetry.unified', false);
<commit_msg>firefox: Set home page to blank<commit_after>/* eslint-disable no-magic-numbers,no-undef,semi */

user_pref('accessibility.force_disabled', 1);
user_pref('app.shield.optoutstudies.enabled', false);
user_pref('browser.cache.cache_isolation', true);
user_pref('browser.discovery.enabled', false);
user_pref('browser.fixup.alternate.enabled', false);
user_pref('browser.formfill.enable', false);
user_pref('browser.link.open_newwindow', 1);
user_pref('browser.newtabpage.enabled', false);
user_pref('browser.safebrowsing.downloads.remote.enabled', false);
user_pref('browser.startup.homepage', 'about:blank');
user_pref('browser.urlbar.doubleClickSelectsAll', false);
user_pref('browser.urlbar.openViewOnFocus', false);
user_pref('browser.urlbar.speculativeConnect.enabled', false);
user_pref('browser.urlbar.update1', false);
user_pref('devtools.debugger.remote-enabled', false);
user_pref('devtools.inspector.activeSidebar', 'ruleview');
user_pref('devtools.inspector.showUserAgentStyles', true);
user_pref('devtools.inspector.three-pane-enabled', false);
user_pref('devtools.inspector.three-pane-first-run', false);
user_pref('dom.gamepad.enabled', false);
user_pref('dom.targetBlankNoOpener.enabled', true);
user_pref('extensions.activeThemeID', 'firefox-compact-light@mozilla.org');
user_pref('extensions.fxmonitor.enabled', false);
user_pref('extensions.htmlaboutaddons.recommendations.enabled', false);
user_pref('extensions.pocket.enabled', false);
user_pref('font.default.x-western', 'sans-serif');
user_pref('font.name.monospace.x-western', 'PragmataPro Mono Liga');
user_pref('font.name.sans-serif.el', 'Source Sans Pro');
user_pref('font.name.sans-serif.ja', 'Source Han Sans');
user_pref('font.name.sans-serif.ko', 'Source Han Sans K');
user_pref('font.name.sans-serif.x-cyrillic', 'Source Sans Pro');
user_pref('font.name.sans-serif.x-unicode', 'Source Sans Pro');
user_pref('font.name.sans-serif.x-western', 'Source Sans Pro');
user_pref('font.name.sans-serif.zh-CN', 'Source Han Sans SC');
user_pref('font.name.sans-serif.zh-HK', 'Source Han Sans HC');
user_pref('font.name.sans-serif.zh-TW', 'Source Han Sans TC');
user_pref('font.name.sans.x-western', 'Source Sans Pro');
user_pref('font.name.serif.el', 'Source Serif Pro');
user_pref('font.name.serif.ja', 'Source Han Serif');
user_pref('font.name.serif.ko', 'Source Han Serif K');
user_pref('font.name.serif.x-cyrillic', 'Source Serif Pro');
user_pref('font.name.serif.x-unicode', 'Source Sans Pro');
user_pref('font.name.serif.x-western', 'Source Serif Pro');
user_pref('font.name.serif.zh-CN', 'Source Han Serif SC');
user_pref('font.name.serif.zh-HK', 'Source Han Serif TC');
user_pref('font.name.serif.zh-TW', 'Source Han Serif TC');
user_pref('font.size.monospace.x-western', '16');
user_pref('gfx.color_management.enablev4', true);
user_pref('gfx.color_management.mode', 1);
user_pref('media.autoplay.default', 5);
user_pref('media.peerconnection.ice.default_address_only', true);
user_pref('media.peerconnection.ice.no_host', true);
user_pref('network.IDN_show_punycode', true);
user_pref('network.cookie.cookieBehavior', 1);
user_pref('network.cookie.thirdparty.sessionOnly', true);
user_pref('network.dns.disablePrefetch', true);
user_pref('network.http.referer.XOriginPolicy', 1);
user_pref('network.http.referer.XOriginTrimmingPolicy', 2);
user_pref('network.http.speculative-parallel-limit', 0);
user_pref('network.manage-offline-status', false);
user_pref('network.predictor.enabled', false);
user_pref('network.prefetch-next', false);
user_pref('network.proxy.socks_remote_dns', true);
user_pref('network.trr.mode', 5);
user_pref('permissions.default.desktop-notification', 2);
user_pref('permissions.default.geo', 2);
user_pref('plugin.state.flash', 0);
user_pref('privacy.clearOnShutdown.offlineApps', true);
user_pref('privacy.clearOnShutdown.siteSettings', true);
user_pref('privacy.firstparty.isolate', true);
user_pref('privacy.firstparty.isolate.restrict_opener_access', true);
user_pref('privacy.trackingprotection.cryptomining.enabled', true);
user_pref('privacy.trackingprotection.enabled', false); // Disable only if using uBlock Origin or similar
user_pref('privacy.trackingprotection.fingerprinting.enabled', true);
user_pref('privacy.trackingprotection.pbmode.enabled', false); // Disable only if using uBlock Origin or similar
user_pref('reader.content_width', 4);
user_pref('reader.font_size', 5);
user_pref('reader.font_type', 'sans-serif');
user_pref('reader.line_height', 3);
user_pref('security.mixed_content.block_display_content', true);
user_pref('security.mixed_content.block_object_subrequest', true);
user_pref('security.mixed_content.upgrade_display_content', true);
user_pref('signon.rememberSignons', false);
user_pref('toolkit.legacyUserProfileCustomizations.stylesheets', true);
user_pref('toolkit.telemetry.archive.enabled', false);
user_pref('toolkit.telemetry.enabled', false);
user_pref('toolkit.telemetry.unified', false);
<|endoftext|>


<commit_before>'use strict';

const EventHandler = require('@scola/events');

class Queue extends EventHandler {
  constructor(config) {
    super();

    this.config = config;
    this.queue = new Set();

    this.processor = null;
    this.iterator = null;

    this.paused = true;
    this.running = false;
  }

  setProcessor(processor) {
    this.processor = processor;
  }

  start() {
    this.paused = false;
  }

  stop() {
    this.paused = true;
  }

  add(item) {
    if (this.queue.size === this.config.get('socket.queue.highWaterMark')) {
      this.run();
      return false;
    }

    this.queue.add(item);
    this.run();

    return true;
  }

  run() {
    if (this.running) {
      return;
    }

    if (this.paused) {
      return;
    }

    this.running = true;
    this.iterator = new Set(this.queue).values();
    this.process();
  }

  process() {
    const item = this.iterator.next();

    if (item.done) {
      return this.finish();
    }

    const result = this.processor(item.value);

    if (result) {
      this.queue.delete(item.value);
    }

    setTimeout(
      this.process.bind(this),
      this.config.get('socket.queue.processInterval')
    );
  }

  finish() {
    this.running = false;
    this.iterator = null;

    if (this.queue.size) {
      this.run();
    }
  }
}

module.exports = Queue;
<commit_msg>Do not use an interval to process items in queue<commit_after>'use strict';

const EventHandler = require('@scola/events');

class Queue extends EventHandler {
  constructor(config) {
    super();

    this.config = config;
    this.queue = new Set();

    this.processor = null;
    this.iterator = null;

    this.paused = true;
    this.running = false;
  }

  setProcessor(processor) {
    this.processor = processor;
    return this;
  }

  start() {
    this.paused = false;
    return this;
  }

  stop() {
    this.paused = true;
    return this;
  }

  add(item) {
    let result = false;

    if (this.queue.size < this.config.get('socket.queue.highWaterMark')) {
      this.queue.add(item);
      result = true;
    }

    this.run();
    return result;
  }

  run() {
    if (this.running || this.paused) {
      return;
    }

    this.running = true;
    this.iterator = new Set(this.queue).values();
    this.process();
  }

  process() {
    const item = this.iterator.next();

    if (item.done) {
      return this.finish();
    }

    const result = this.processor(item.value);

    if (result) {
      this.queue.delete(item.value);
    }

    this.process();
  }

  finish() {
    this.running = false;
    this.iterator = null;

    if (this.queue.size) {
      this.run();
    }
  }
}

module.exports = Queue;
<|endoftext|>


<commit_before>'use strict';

import _ from 'lodash';

let angular = require('angular');

module.exports = angular.module('spinnaker.deck.gce.tagManager.service', [])
  .factory('gceTagManager', function () {
    let resetKeys = ['command', 'securityGroups', 'securityGroupObjectsKeyedByTag', 'securityGroupObjectsKeyedById'];

    this.reset = () => {
      resetKeys.forEach((key) => delete this[key]);
    };

    this.register = (command) => {
      this.command = command;
      let { credentials, backingData } = command;
      if (backingData.securityGroups[credentials] !== undefined) {
        this.securityGroupObjects = _.cloneDeep(backingData.securityGroups[credentials].gce.global);

        initializeSecurityGroupObjects(this.securityGroupObjects, command.tags);

        let { byTag, bySecurityGroupId } = groupSecurityGroupObjects(this.securityGroupObjects);
        this.securityGroupObjectsKeyedByTag = byTag;
        this.securityGroupObjectsKeyedById = bySecurityGroupId;
      }

      if (!command.securityGroups) {
        command.securityGroups = this.inferSecurityGroupIdsFromTags(command.tags);
      }
    };

    this.inferSecurityGroupIdsFromTags = (commandTags = []) => {
      return _.chain(commandTags)
        .map(t => this.securityGroupObjectsKeyedByTag[t.value])
        .flatten()
        .map('id')
        .uniq()
        .value();
    };

    let initializeSecurityGroupObjects = (securityGroupObjects, commandTags = []) => {
      securityGroupObjects
        .forEach((sg) => {
          // Raw target tags look like '[tag-a, tag-b]'.
          let rawTags = sg.targetTags;
          sg.tagsArray = rawTags
            ? rawTags.substring(1, rawTags.length - 1).split(', ')
            : [];

          sg.selectedTags = commandTags
            ? _.intersection(commandTags.map(t => t.value), sg.tagsArray)
            : [];
        });
    };

    let groupSecurityGroupObjects = (securityGroupObjects) => {
      return securityGroupObjects.reduce((groupings, sg) => {
        let { bySecurityGroupId } = groupings;
        bySecurityGroupId[sg.id] = sg;

        return sg.tagsArray.reduce((groupings, tag) => {
          let { byTag } = groupings;
          if (!byTag[tag]) {
            byTag[tag] = [];
          }
          byTag[tag].push(sg);

          return groupings;
        }, groupings);
      }, { byTag: {}, bySecurityGroupId: {} });
    };

    this.inferSelectedSecurityGroupFromTag = _.debounce((tagName) => {
      let securityGroupObjectsWithTag = this.securityGroupObjectsKeyedByTag[tagName],
        c = this.command;

      if (securityGroupObjectsWithTag) {
        updateSelectedTagsOnSecurityGroupObjects(securityGroupObjectsWithTag, tagName);
        c.securityGroups = _.map(
          updateSelectedSecurityGroups(getSecurityGroupObjectsFromIds(c.securityGroups), securityGroupObjectsWithTag),
          'id');
      }

      // If you pause while typing "tag-a," but you really want to add "tag-abc,"
      // make sure you remove "tag-a".
      this.updateSelectedTags();
    }, 100);

    this.updateSelectedTags = () => {
      let c = this.command,
        tags = c.tags.map(t => t.value);

      getSecurityGroupObjectsFromIds(c.securityGroups)
        .forEach((sg) => {
          if (sg.selectedTags) {
            sg.selectedTags = _.intersection(sg.selectedTags, tags);
          }

          if (!_.get(sg, 'selectedTags.length')) {
            c.securityGroups = _.without(c.securityGroups, sg.id);
          }
        });
    };

    this.addTag = (tagName) => {
      let c = this.command,
        tags = c.tags,
        securityGroupObjectsWithTag = this.securityGroupObjectsKeyedByTag[tagName];

      if (!_.includes(tags.map(t => t.value), tagName)) {
        tags.push({ value: tagName });
      }

      if (securityGroupObjectsWithTag) {
        updateSelectedTagsOnSecurityGroupObjects(securityGroupObjectsWithTag, tagName);
        c.securityGroups = _.map(
          updateSelectedSecurityGroups(getSecurityGroupObjectsFromIds(c.securityGroups), securityGroupObjectsWithTag),
          'id');
      }
    };

    let getSecurityGroupObjectsFromIds = (ids) => ids.map((id) => this.securityGroupObjectsKeyedById[id]);

    let updateSelectedTagsOnSecurityGroupObjects = (securityGroupObjects, newTag) => {
      securityGroupObjects.forEach((sg) => {
        sg.selectedTags = _.chain(sg.selectedTags || [])
          .concat([newTag])
          .uniq()
          .value();
      });
    };

    let updateSelectedSecurityGroups = (oldGroups, newGroups) => {
      return _.chain(oldGroups)
        .concat(newGroups)
        .uniq()
        .value();
    };

    this.removeTag = (tagName) => {
      let c = this.command,
        securityGroupIds = c.securityGroups || [],
        securityGroupObjects = getSecurityGroupObjectsFromIds(securityGroupIds);

      securityGroupObjects.forEach((sg) => {
        if (sg.selectedTags) {
          sg.selectedTags = sg.selectedTags.filter(tag => tag !== tagName);
        }
      });

      c.tags = c.tags.filter(tag => tag.value !== tagName);
    };

    this.removeSecurityGroup = (securityGroupId) => {
      let securityGroupObject = this.securityGroupObjectsKeyedById[securityGroupId],
        tagsToRemove = securityGroupObject.selectedTags,
        c = this.command;

      getSecurityGroupObjectsFromIds(c.securityGroups)
        .forEach((sg) => {
          if (sg.selectedTags) {
            sg.selectedTags = _.difference(sg.selectedTags, tagsToRemove);
          }
        });

      securityGroupObject.selectedTags = [];
      c.tags = _.chain(c.tags)
        .map(t => t.value)
        .difference(tagsToRemove)
        .map(t => ({ value: t }))
        .value();
    };

    this.getToolTipContent = (tagName) => {
      let groups = _.get(this, ['securityGroupObjectsKeyedByTag', tagName]),
        groupIds = groups ? groups.map((sg) => sg.id) : [];

      return `This tag associates this server group with security group${groupIds.length > 1 ? 's' : ''}
              ${groupIds.join(', ')}.`;
    };

    this.showToolTip = (tagName) => {
      return !!_.get(this,['securityGroupObjectsKeyedByTag', tagName]);
    };

    return this;
  });
<commit_msg>(google) fix for deploy stage with a tag (#3235)<commit_after>'use strict';

import _ from 'lodash';

let angular = require('angular');

module.exports = angular.module('spinnaker.deck.gce.tagManager.service', [])
  .factory('gceTagManager', function () {
    let resetKeys = ['command', 'securityGroups', 'securityGroupObjectsKeyedByTag', 'securityGroupObjectsKeyedById'];

    this.reset = () => {
      resetKeys.forEach((key) => delete this[key]);
    };

    this.register = (command) => {
      this.command = command;
      let { credentials, backingData } = command;
      if (backingData.securityGroups[credentials] !== undefined) {
        this.securityGroupObjects = _.cloneDeep(backingData.securityGroups[credentials].gce.global);

        initializeSecurityGroupObjects(this.securityGroupObjects, command.tags);

        let { byTag, bySecurityGroupId } = groupSecurityGroupObjects(this.securityGroupObjects);
        this.securityGroupObjectsKeyedByTag = byTag;
        this.securityGroupObjectsKeyedById = bySecurityGroupId;
      }

      if (!command.securityGroups) {
        command.securityGroups = this.inferSecurityGroupIdsFromTags(command.tags);
      }
    };

    this.inferSecurityGroupIdsFromTags = (commandTags = []) => {
      return _.chain(commandTags)
        .map(t => this.securityGroupObjectsKeyedByTag[t.value])
        .flatten()
        .map('id')
        .compact()
        .uniq()
        .value();
    };

    let initializeSecurityGroupObjects = (securityGroupObjects, commandTags = []) => {
      securityGroupObjects
        .forEach((sg) => {
          // Raw target tags look like '[tag-a, tag-b]'.
          let rawTags = sg.targetTags;
          sg.tagsArray = rawTags
            ? rawTags.substring(1, rawTags.length - 1).split(', ')
            : [];

          sg.selectedTags = commandTags
            ? _.intersection(commandTags.map(t => t.value), sg.tagsArray)
            : [];
        });
    };

    let groupSecurityGroupObjects = (securityGroupObjects) => {
      return securityGroupObjects.reduce((groupings, sg) => {
        let { bySecurityGroupId } = groupings;
        bySecurityGroupId[sg.id] = sg;

        return sg.tagsArray.reduce((groupings, tag) => {
          let { byTag } = groupings;
          if (!byTag[tag]) {
            byTag[tag] = [];
          }
          byTag[tag].push(sg);

          return groupings;
        }, groupings);
      }, { byTag: {}, bySecurityGroupId: {} });
    };

    this.inferSelectedSecurityGroupFromTag = _.debounce((tagName) => {
      let securityGroupObjectsWithTag = this.securityGroupObjectsKeyedByTag[tagName],
        c = this.command;

      if (securityGroupObjectsWithTag) {
        updateSelectedTagsOnSecurityGroupObjects(securityGroupObjectsWithTag, tagName);
        c.securityGroups = _.map(
          updateSelectedSecurityGroups(getSecurityGroupObjectsFromIds(c.securityGroups), securityGroupObjectsWithTag),
          'id');
      }

      // If you pause while typing "tag-a," but you really want to add "tag-abc,"
      // make sure you remove "tag-a".
      this.updateSelectedTags();
    }, 100);

    this.updateSelectedTags = () => {
      let c = this.command,
        tags = c.tags.map(t => t.value);

      getSecurityGroupObjectsFromIds(c.securityGroups)
        .forEach((sg) => {
          if (sg.selectedTags) {
            sg.selectedTags = _.intersection(sg.selectedTags, tags);
          }

          if (!_.get(sg, 'selectedTags.length')) {
            c.securityGroups = _.without(c.securityGroups, sg.id);
          }
        });
    };

    this.addTag = (tagName) => {
      let c = this.command,
        tags = c.tags,
        securityGroupObjectsWithTag = this.securityGroupObjectsKeyedByTag[tagName];

      if (!_.includes(tags.map(t => t.value), tagName)) {
        tags.push({ value: tagName });
      }

      if (securityGroupObjectsWithTag) {
        updateSelectedTagsOnSecurityGroupObjects(securityGroupObjectsWithTag, tagName);
        c.securityGroups = _.map(
          updateSelectedSecurityGroups(getSecurityGroupObjectsFromIds(c.securityGroups), securityGroupObjectsWithTag),
          'id');
      }
    };

    let getSecurityGroupObjectsFromIds = (ids) => ids.map((id) => this.securityGroupObjectsKeyedById[id]);

    let updateSelectedTagsOnSecurityGroupObjects = (securityGroupObjects, newTag) => {
      securityGroupObjects.forEach((sg) => {
        sg.selectedTags = _.chain(sg.selectedTags || [])
          .concat([newTag])
          .uniq()
          .value();
      });
    };

    let updateSelectedSecurityGroups = (oldGroups, newGroups) => {
      return _.chain(oldGroups)
        .concat(newGroups)
        .uniq()
        .value();
    };

    this.removeTag = (tagName) => {
      let c = this.command,
        securityGroupIds = c.securityGroups || [],
        securityGroupObjects = getSecurityGroupObjectsFromIds(securityGroupIds);

      securityGroupObjects.forEach((sg) => {
        if (sg.selectedTags) {
          sg.selectedTags = sg.selectedTags.filter(tag => tag !== tagName);
        }
      });

      c.tags = c.tags.filter(tag => tag.value !== tagName);
    };

    this.removeSecurityGroup = (securityGroupId) => {
      let securityGroupObject = this.securityGroupObjectsKeyedById[securityGroupId],
        tagsToRemove = securityGroupObject.selectedTags,
        c = this.command;

      getSecurityGroupObjectsFromIds(c.securityGroups)
        .forEach((sg) => {
          if (sg.selectedTags) {
            sg.selectedTags = _.difference(sg.selectedTags, tagsToRemove);
          }
        });

      securityGroupObject.selectedTags = [];
      c.tags = _.chain(c.tags)
        .map(t => t.value)
        .difference(tagsToRemove)
        .map(t => ({ value: t }))
        .value();
    };

    this.getToolTipContent = (tagName) => {
      let groups = _.get(this, ['securityGroupObjectsKeyedByTag', tagName]),
        groupIds = groups ? groups.map((sg) => sg.id) : [];

      return `This tag associates this server group with security group${groupIds.length > 1 ? 's' : ''}
              ${groupIds.join(', ')}.`;
    };

    this.showToolTip = (tagName) => {
      return !!_.get(this,['securityGroupObjectsKeyedByTag', tagName]);
    };

    return this;
  });
<|endoftext|>


<commit_before>/**
 * imagex
 * author: joeyguo
 * HomePage: https://github.com/gkajs/imagex
 * MIT Licensed.
 */

var path       = require("path"),
    color      = require("./color"),
    diff       = require("./diff"),
    crop       = require("./crop"),
    unique     = require("./unique"),
    x2x        = require("./x2x"),
    images     = require("./images"),
    mini       = require("./mini"),
    file       = require("./file"),
    info       = require("./info"),
    writeFile   = file.writeFile,
    getFiles   = file.getFiles,
    deleteDir  = file.deleteDir;

var getData  = info.getData,
    getNames = info.getNames;

module.exports = function imagex(opt, callback) {

	var src       = opt.src,
		dest      = opt.dest,
		prefix    = opt.prefix,
        bgColor   = opt.bgColor,
        isDiff    = opt.isDiff,
		isCrop    = opt.isCrop,
		isUnique  = opt.isUnique,
        isSprites = opt.isSprites,
        spritesCount = opt.spritesCount,
		algorithm = opt.algorithm,
        isMini    = opt.isMini,
		isInfo = opt.isInfo,
		isReplace = opt.isReplace;

    var tmpDir    = path.join(src, "..", ".tmpGKAdir");

    if (!src) {
        console.log();
        console.log('[error]: ' + 'imagex need dir !');
        console.log('----------------------------');
        return;
    }

    // MINI source image
    if (isReplace && isMini) {
        mini(src);
        return;
    }

    getFiles(src, (src2id) => {

        if(JSON.stringify(src2id) == "{}"){
            console.log('[error]: Can not find images');
            return;
        }

        color(bgColor, tmpDir, src2id, (src2id) => {

            diff(isDiff, tmpDir, src2id, (src2id) => {

                crop(isCrop, tmpDir, src2id, (src2id, src2cutinfo) => {

                    unique(isUnique, src2id, (src2id) => {

                        var suffix = path.extname(Object.keys(src2id)[0]);

                        x2x(src2id, suffix, dest, prefix, isSprites, (src2distid, src2src, srcs, dists, src2dist) => {

                            // output images
                            images(isSprites, {
                                src2dist: src2dist,
                                dists: dists,
                                srcs: srcs,
                                src2src: src2src,
                                algorithm: algorithm,
                                spritesFilepath: path.join(dest, (prefix? (prefix + "-"): "") + "sprites" + suffix),
                                spritesCount: spritesCount,
                            }, (obj)=>{

                                deleteDir(tmpDir);

                                isMini && mini(dest);

                                var data = getData({
                                    sprites: obj.sprites,
                                    src2cutinfo: src2cutinfo,
                                    src2dist: src2dist
                                });

                                isInfo && writeFile(path.join(dest, "__info", "data.json"), JSON.stringify(data, null, '    '), () => {
                                    console.log(` ✔ __info data.json generated`);
                                })

                                callback && callback(data, {
                                	getNames: getNames,
                                });

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

    });
}<commit_msg>fixbug tmpdir<commit_after>/**
 * imagex
 * author: joeyguo
 * HomePage: https://github.com/gkajs/imagex
 * MIT Licensed.
 */

var path       = require("path"),
    color      = require("./color"),
    diff       = require("./diff"),
    crop       = require("./crop"),
    unique     = require("./unique"),
    x2x        = require("./x2x"),
    images     = require("./images"),
    mini       = require("./mini"),
    file       = require("./file"),
    info       = require("./info"),
    writeFile   = file.writeFile,
    getFiles   = file.getFiles,
    deleteDir  = file.deleteDir;

var getData  = info.getData,
    getNames = info.getNames;

module.exports = function imagex(opt, callback) {

	var src       = opt.src,
		dest      = opt.dest,
		prefix    = opt.prefix,
        bgColor   = opt.bgColor,
        isDiff    = opt.isDiff,
		isCrop    = opt.isCrop,
		isUnique  = opt.isUnique,
        isSprites = opt.isSprites,
        spritesCount = opt.spritesCount,
		algorithm = opt.algorithm,
        isMini    = opt.isMini,
		isInfo = opt.isInfo,
		isReplace = opt.isReplace;

    var tmpDir    = path.join(src, "..", ".tmpGKAdir");

    if (!src) {
        console.log();
        console.log('[error]: ' + 'imagex need dir !');
        console.log('----------------------------');
        return;
    }

    // MINI source image
    if (isReplace && isMini) {
        mini(src);
        return;
    }

    getFiles(src, (src2id) => {

        if(JSON.stringify(src2id) == "{}"){
            console.log('[error]: Can not find images');
            return;
        }

        color(bgColor, tmpDir, src2id, (src2id) => {

            diff(isDiff, tmpDir, src2id, (src2id) => {

                crop(isCrop, tmpDir, src2id, (src2id, src2cutinfo) => {

                    unique(isUnique, src2id, (src2id) => {

                        var suffix = path.extname(Object.keys(src2id)[0]);

                        x2x(src2id, suffix, dest, prefix, isSprites, (src2distid, src2src, srcs, dists, src2dist) => {

                            // output images
                            images(isSprites, {
                                src2dist: src2dist,
                                dists: dists,
                                srcs: srcs,
                                src2src: src2src,
                                algorithm: algorithm,
                                spritesFilepath: path.join(dest, (prefix? (prefix + "-"): "") + "sprites" + suffix),
                                spritesCount: spritesCount,
                            }, (obj)=>{

                                isMini && mini(dest);

                                var data = getData({
                                    sprites: obj.sprites,
                                    src2cutinfo: src2cutinfo,
                                    src2dist: src2dist
                                });

                                isInfo && writeFile(path.join(dest, "__info", "data.json"), JSON.stringify(data, null, '    '), () => {
                                    console.log(` ✔ __info data.json generated`);
                                })

                                callback && callback(data, {
                                	getNames: getNames,
                                });

                                deleteDir(tmpDir);

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

    });
}<|endoftext|>


<commit_before>module.exports = function(grunt) {
    'use strict';

    var ff = grunt.config('shared.firefox');

    return {
        'firefox-release': {
            auth: {
                host: 'ftp.mailfred.de',
                port: 21,
                authKey: 'firefox'
            },
            src: ff.path,
            dest: '/firefox',
            forceVerbose: true,
            exclusions: [
                '**/*.xpi!' + ff.file
            ]
        }
    };
};
<commit_msg>refine config for release via shell file<commit_after>/* global module, process */
module.exports = function(grunt) {
    'use strict';

    var ff = grunt.config('shared.firefox');

    return {
        'firefox-release': {
            auth: {
                host: 'ftp.mailfred.de',
                port: 21,
                authKey: 'firefox',
                authPath: process.env.FTP_DEPLOY_AUTH_PATH // may be undefined, uses the .ftppass file instead
            },
            src: ff.path,
            dest: '/firefox',
            forceVerbose: true,
            exclusions: [
                '**/*.xpi!' + ff.file // upload only the current xpi file
            ]
        }
    };
};
<|endoftext|>


<commit_before>// Whether given object is primitive

'use strict';

var setTrue = require('./Object/get-set')(true)

  , map = {};

['boolean', 'number', 'string'].forEach(setTrue, map);

module.exports = function (x) {
	return map[typeof x] || (x == null);
};
<commit_msg>Documentation<commit_after>// Whether given value is primitive

'use strict';

var setTrue = require('./Object/get-set')(true)

  , map = {};

['boolean', 'number', 'string'].forEach(setTrue, map);

module.exports = function (x) {
	return map[typeof x] || (x == null);
};
<|endoftext|>


<commit_before>// ==========================================================================
// Project:   SproutCore - JavaScript Application Framework
// Copyright: ©2006-2011 Strobe Inc. and contributors.
//            portions copyright ©2010 Apple Inc.
// License:   Licensed under MIT license (see license.js)
// ==========================================================================

/*global module test htmlbody ok equals same stop start */

var items = [
  { title: 'Menu Item', keyEquivalent: 'ctrl_shift_n' },
  { title: 'Checked Menu Item', isChecked: YES, keyEquivalent: 'ctrl_a' },
  { title: 'Selected Menu Item', keyEquivalent: 'backspace' },
  { separator: YES },
  { title: 'Menu Item with Icon', icon: 'inbox', keyEquivalent: 'ctrl_m' },
  { title: 'Menu Item with Icon', icon: 'folder', keyEquivalent: 'ctrl_p' },
  { separator: YES },
  { title: 'Selected Menu Item…', isChecked: YES, keyEquivalent: 'ctrl_shift_o' },
  { title: 'Item with Submenu', subMenu: [{ title: 'Submenu item 1' }, { title: 'Submenu item 2'}] },
  { title: 'Disabled Menu Item', isEnabled: NO }//,
  // { isSeparator: YES },
  // { groupTitle: 'Menu Label', items: [{ title: 'Nested Item' }, { title: 'Nested Item' }] }
];

var menu, anchor;

module('SC.MenuPane Methods', {
  setup: function() {
    menu = SC.MenuPane.create({
      layout: { width: 206 },
      items: items,

      displayItemsCount: 0,
      displayItemsDidChange: function() {
        this.displayItemsCount++;
      }.observes('displayItems')
    });

    anchor = SC.Pane.create({
      layout: { top: 15, left: 15, width: 100, height: 100 }
    });
  },

  teardown: function() {
    menu.remove();
    anchor.remove();
    menu.destroy();
    menu = null;
  }
});

test('popup() without anchor', function(){
  var layout;

  menu.popup();
  layout = menu.get('layout');
  equals(layout.centerX, 0, 'menu should be horizontally centered');
  equals(layout.centerY, 0, 'menu should be vertically centered');
  equals(layout.width, 206, 'menu should maintain the width specified');
  equals(layout.height, 184, 'menu height should resize based on item content');
  menu.remove();
});

test('popup() with anchor', function(){
  var layout;

  anchor.append();
  menu.popup(anchor);
  layout = menu.get('layout');
  equals(layout.left, 16, 'menu should be aligned to the left of the anchor');
  equals(layout.top, 119, 'menu should be positioned below the anchor');
  equals(layout.width, 206, 'menu should maintain the width specified');
  equals(layout.height, 184, 'menu height should resize based on item content');
  menu.remove();
});

test('displayItems', function() {
  var strings = ['Alpha', 'Beta', 'Gaga'], output, count;

  menu.menuHeight = 1;
  menu.set('items', strings);
  equals(1, menu.displayItemsCount, 'displayItems should change when items array changes');
  ok(menu.get('menuHeight') > 1, 'menuHeight should be recalculated when displayItems changes');

  output = menu.get('displayItems')[0];
  equals(SC.typeOf(output), SC.T_OBJECT, 'strings should be transformed into objects');
  equals(output.title, 'Alpha', 'title property of transformed object should match original string');
  equals(output.value, 'Alpha', 'value property of transformed object should match original string');
  equals(output.isEnabled, YES, 'isEnabled property of transformed object should be YES');

  var hashes = [
    { title: 'Yankee' },
    { title: 'Hotel' },
    { title: 'Foxtrot' } ];
  menu.set('items', hashes);

  output = menu.get('displayItems')[0];
  equals(SC.typeOf(output), SC.T_OBJECT, 'displayItems should convert hashes to objects');
  equals(output.get('title'), 'Yankee', 'object properties should correspond to hash properties');

  var objects = [
    SC.Object.create({ title: 'Whiskey' }),
    SC.Object.create({ title: 'Mystics' }),
    SC.Object.create({ title: 'Men' })
  ];
  menu.set('items', objects);

  output = menu.get('displayItems')[0];
  equals(SC.typeOf(output), SC.T_OBJECT, 'displayItems should not convert objects');
  equals(SC.guidFor(output), SC.guidFor(objects[0]), 'objects should be identical to provided objects');
});

test('displayItems - Edge Cases', function() {
  menu.set('items', [null, null, false, 0, 'Real Item']);

  var output = menu.get('displayItems');
  equals(output.get('length'), 1, 'displayItems should strip out invalid items');

  menu.set('items', ['Yellow', { title: 'Country' }, SC.Object.create({ title: 'Teeth' })]);
  output = menu.get('displayItems');

  ok(output[0].title === 'Yellow' && output[1].title === 'Country' && output[2].title === 'Teeth',
     'displayItems should accept a mix of supported item types');

  menu.set('items', []);
  equals(menu.getPath('displayItems.length'), 0, 'displayItems should be empty if items is empty');
  menu.set('items', null);
  equals(menu.get('displayItems'), null, 'displayItems should be null if items is null');
});

test('menuItemViewForContentIndex', function() {
  menu.popup();
  var view = menu.menuItemViewForContentIndex(0);
  equals(items[0].title, view.$('.value').text(), 'menu item views should match content items');
});
<commit_msg>we added more space but never updated the tests<commit_after>// ==========================================================================
// Project:   SproutCore - JavaScript Application Framework
// Copyright: ©2006-2011 Strobe Inc. and contributors.
//            portions copyright ©2010 Apple Inc.
// License:   Licensed under MIT license (see license.js)
// ==========================================================================

/*global module test htmlbody ok equals same stop start */

var items = [
  { title: 'Menu Item', keyEquivalent: 'ctrl_shift_n' },
  { title: 'Checked Menu Item', isChecked: YES, keyEquivalent: 'ctrl_a' },
  { title: 'Selected Menu Item', keyEquivalent: 'backspace' },
  { separator: YES },
  { title: 'Menu Item with Icon', icon: 'inbox', keyEquivalent: 'ctrl_m' },
  { title: 'Menu Item with Icon', icon: 'folder', keyEquivalent: 'ctrl_p' },
  { separator: YES },
  { title: 'Selected Menu Item…', isChecked: YES, keyEquivalent: 'ctrl_shift_o' },
  { title: 'Item with Submenu', subMenu: [{ title: 'Submenu item 1' }, { title: 'Submenu item 2'}] },
  { title: 'Disabled Menu Item', isEnabled: NO }//,
  // { isSeparator: YES },
  // { groupTitle: 'Menu Label', items: [{ title: 'Nested Item' }, { title: 'Nested Item' }] }
];

var menu, anchor;

module('SC.MenuPane Methods', {
  setup: function() {
    menu = SC.MenuPane.create({
      layout: { width: 206 },
      items: items,

      displayItemsCount: 0,
      displayItemsDidChange: function() {
        this.displayItemsCount++;
      }.observes('displayItems')
    });

    anchor = SC.Pane.create({
      layout: { top: 15, left: 15, width: 100, height: 100 }
    });
  },

  teardown: function() {
    menu.remove();
    anchor.remove();
    menu.destroy();
    menu = null;
  }
});

test('popup() without anchor', function(){
  var layout;

  menu.popup();
  layout = menu.get('layout');
  equals(layout.centerX, 0, 'menu should be horizontally centered');
  equals(layout.centerY, 0, 'menu should be vertically centered');
  equals(layout.width, 206, 'menu should maintain the width specified');
  equals(layout.height, 204, 'menu height should resize based on item content');
  menu.remove();
});

test('popup() with anchor', function(){
  var layout;

  anchor.append();
  menu.popup(anchor);
  layout = menu.get('layout');
  equals(layout.left, 16, 'menu should be aligned to the left of the anchor');
  equals(layout.top, 119, 'menu should be positioned below the anchor');
  equals(layout.width, 206, 'menu should maintain the width specified');
  equals(layout.height, 204, 'menu height should resize based on item content');
  menu.remove();
});

test('displayItems', function() {
  var strings = ['Alpha', 'Beta', 'Gaga'], output, count;

  menu.menuHeight = 1;
  menu.set('items', strings);
  equals(1, menu.displayItemsCount, 'displayItems should change when items array changes');
  ok(menu.get('menuHeight') > 1, 'menuHeight should be recalculated when displayItems changes');

  output = menu.get('displayItems')[0];
  equals(SC.typeOf(output), SC.T_OBJECT, 'strings should be transformed into objects');
  equals(output.title, 'Alpha', 'title property of transformed object should match original string');
  equals(output.value, 'Alpha', 'value property of transformed object should match original string');
  equals(output.isEnabled, YES, 'isEnabled property of transformed object should be YES');

  var hashes = [
    { title: 'Yankee' },
    { title: 'Hotel' },
    { title: 'Foxtrot' } ];
  menu.set('items', hashes);

  output = menu.get('displayItems')[0];
  equals(SC.typeOf(output), SC.T_OBJECT, 'displayItems should convert hashes to objects');
  equals(output.get('title'), 'Yankee', 'object properties should correspond to hash properties');

  var objects = [
    SC.Object.create({ title: 'Whiskey' }),
    SC.Object.create({ title: 'Mystics' }),
    SC.Object.create({ title: 'Men' })
  ];
  menu.set('items', objects);

  output = menu.get('displayItems')[0];
  equals(SC.typeOf(output), SC.T_OBJECT, 'displayItems should not convert objects');
  equals(SC.guidFor(output), SC.guidFor(objects[0]), 'objects should be identical to provided objects');
});

test('displayItems - Edge Cases', function() {
  menu.set('items', [null, null, false, 0, 'Real Item']);

  var output = menu.get('displayItems');
  equals(output.get('length'), 1, 'displayItems should strip out invalid items');

  menu.set('items', ['Yellow', { title: 'Country' }, SC.Object.create({ title: 'Teeth' })]);
  output = menu.get('displayItems');

  ok(output[0].title === 'Yellow' && output[1].title === 'Country' && output[2].title === 'Teeth',
     'displayItems should accept a mix of supported item types');

  menu.set('items', []);
  equals(menu.getPath('displayItems.length'), 0, 'displayItems should be empty if items is empty');
  menu.set('items', null);
  equals(menu.get('displayItems'), null, 'displayItems should be null if items is null');
});

test('menuItemViewForContentIndex', function() {
  menu.popup();
  var view = menu.menuItemViewForContentIndex(0);
  equals(items[0].title, view.$('.value').text(), 'menu item views should match content items');
});
<|endoftext|>


<commit_before>/*
 * config.js: Configuration for the jitsu CLI.
 *
 * (C) 2010, Nodejitsu Inc.
 *
 */

var nconf = require('nconf'),
    path = require('path'),
    winston = require('winston'),
    optimist = require('optimist'),
    argv = optimist.argv,
    fs = require('fs');

var config = module.exports = Object.create(nconf.Provider.prototype);

//
// Set up our default config
//
var dir = process.cwd(),
    configPath = argv.jitsuconf || argv.j,
    looking = true;

var defaults = {
  'root': process.env.HOME,
  'protocol': 'http',
  'remoteHost': 'api.nodejitsu.com',
  'userconfig': '.jitsuconf',
  'loglevel': 'info',
  'tmproot': '/tmp',
  'tar': 'tar',
  'gzipbin': 'gzip'
};

//
// Make sure the file exists if it was set explicitly
//
config.findJitsuconf = function (filename) {
  //
  // Use pre-existing config file if already found
  //
  if(!looking) {
    return true;
  }
  filename = filename || '.jitsuconf';

  if (configPath) {
    try {
      var stat = fs.statSync(fs.realpathSync(configPath));
      looking = stat.isDirectory();
    }
    catch (ex) {
      return false;
    }
  }
  while (looking) {
    try {
      var stat = fs.statSync(fs.realpathSync(configPath = path.join(dir, filename)));
      looking = stat.isDirectory();
    }
    catch (e) {
      var olddir = dir;
      dir = path.dirname(dir);

      if (olddir === dir) {
        try {
          var stat = fs.statSync(fs.realpathSync(configPath = path.join(process.env.HOME, filename)));
          if(stat.isDirectory()) {
            configPath = undefined;
          }
        }
        catch (e) {
          //
          // Ignore errors
          //
        }
        looking = false;
      }
    }
  }

  if (!configPath) {
    fs.writeFileSync(path.join(process.env.HOME, filename),JSON.stringify(defaults));
  }

  winston.silly('Using config file ' + configPath.magenta);
  config.use('file', { file: configPath });
  return true;
};

var _get = config.get,
    _load = config.load;

Object.defineProperty(defaults, 'remoteUri', {
  get: function () {
    var port = optimist.argv.port || config.get('port') || this.port || '';
    if (port) {
      port = ':' + port;
    }

    return [this.protocol, '://', (optimist.argv.remoteHost || config.get('remoteHost') || defaults.remoteHost), port].join('');
  }
});

config.load = function (filename, callback) {
  if (!callback) {
    callback = filename;
    filename = null;
  }

  //
  // Find the `.jitsuconf` file to be used for this
  // jitsu session.
  //
  if (!config.findJitsuconf(filename)) {
    return callback(new Error(configPath.magenta + ' does not exist'), true);
  }

  _load.call(config, function (err, store) {
    if (err) {
      return callback(err);
    }

    if (filename) {
      config.set('userconfig', filename);
    }

    if (store.auth) {
      var auth = store.auth.split(':');
      config.clear('auth');
      config.set('username', auth[0]);
      config.set('password', auth[1]);
      return config.save(callback);
    }

    callback(null, store);
  });
};

config.get = function (key) {
  if (optimist.argv.hasOwnProperty(key)) {
    return optimist.argv[key];
  }

  var value = _get.call(config, key);
  return typeof value !== 'undefined' ? value :  defaults[key];
};
<commit_msg>[fix] fix for home directory bug just introduced #36<commit_after>/*
 * config.js: Configuration for the jitsu CLI.
 *
 * (C) 2010, Nodejitsu Inc.
 *
 */

var nconf = require('nconf'),
    path = require('path'),
    winston = require('winston'),
    optimist = require('optimist'),
    argv = optimist.argv,
    fs = require('fs');

var config = module.exports = Object.create(nconf.Provider.prototype);

//
// Set up our default config
//
var dir = process.cwd(),
    configPath = argv.jitsuconf || argv.j,
    looking = true;

var defaults = {
  'root': process.env.HOME,
  'protocol': 'http',
  'remoteHost': 'api.nodejitsu.com',
  'userconfig': '.jitsuconf',
  'loglevel': 'info',
  'tmproot': '/tmp',
  'tar': 'tar',
  'gzipbin': 'gzip'
};

//
// Make sure the file exists if it was set explicitly
//
config.findJitsuconf = function (filename) {
  //
  // Use pre-existing config file if already found
  //
  if(!looking) {
    return true;
  }
  filename = filename || '.jitsuconf';

  if (configPath) {
    try {
      var stat = fs.statSync(fs.realpathSync(configPath));
      looking = stat.isDirectory();
    }
    catch (ex) {
      return false;
    }
  }
  while (looking) {
    try {
      var stat = fs.statSync(fs.realpathSync(configPath = path.join(dir, filename)));
      looking = stat.isDirectory();
    }
    catch (e) {
      var olddir = dir;
      dir = path.dirname(dir);

      if (olddir === dir) {
        try {
          var stat = fs.statSync(fs.realpathSync(configPath = path.join(process.env.HOME, filename)));
          if(stat.isDirectory()) {
            configPath = undefined;
          }
        }
        catch (e) {
          //
          // Ignore errors
          //
          configPath = undefined;
        }
        looking = false;
      }
    }
  }

  if (!configPath) {
    console.log(path.join(process.env.HOME, filename))
    fs.writeFileSync(configPath = path.join(process.env.HOME, filename),JSON.stringify(defaults));
  }

  winston.silly('Using config file ' + configPath.magenta);
  config.use('file', { file: configPath });
  return true;
};

var _get = config.get,
    _load = config.load;

Object.defineProperty(defaults, 'remoteUri', {
  get: function () {
    var port = optimist.argv.port || config.get('port') || this.port || '';
    if (port) {
      port = ':' + port;
    }

    return [this.protocol, '://', (optimist.argv.remoteHost || config.get('remoteHost') || defaults.remoteHost), port].join('');
  }
});

config.load = function (filename, callback) {
  if (!callback) {
    callback = filename;
    filename = null;
  }

  //
  // Find the `.jitsuconf` file to be used for this
  // jitsu session.
  //
  if (!config.findJitsuconf(filename)) {
    return callback(new Error(configPath.magenta + ' does not exist'), true);
  }

  _load.call(config, function (err, store) {
    if (err) {
      return callback(err);
    }

    if (filename) {
      config.set('userconfig', filename);
    }

    if (store.auth) {
      var auth = store.auth.split(':');
      config.clear('auth');
      config.set('username', auth[0]);
      config.set('password', auth[1]);
      return config.save(callback);
    }

    callback(null, store);
  });
};

config.get = function (key) {
  if (optimist.argv.hasOwnProperty(key)) {
    return optimist.argv[key];
  }

  var value = _get.call(config, key);
  return typeof value !== 'undefined' ? value :  defaults[key];
};
<|endoftext|>


<commit_before>import FileUploaderComponent from './FileUploader.vue';

export default class FileUploader {
	constructor({
		wrapper,
		method,
		on_success,
		doctype,
		docname,
		fieldname,
		files,
		folder,
		restrictions,
		upload_notes,
		allow_multiple,
		as_dataurl,
		disable_file_browser,
		frm
	} = {}) {
		if (frm && frm.attachments.max_reached()) {
			frappe.throw(__("Maximum Attachment Limit for this record reached."));
			return;
		}

		if (!wrapper) {
			this.make_dialog();
		} else {
			this.wrapper = wrapper.get ? wrapper.get(0) : wrapper;
		}

		this.$fileuploader = new Vue({
			el: this.wrapper,
			render: h => h(FileUploaderComponent, {
				props: {
					show_upload_button: !Boolean(this.dialog),
					doctype,
					docname,
					fieldname,
					method,
					folder,
					on_success,
					restrictions,
					upload_notes,
					allow_multiple,
					as_dataurl,
					disable_file_browser,
				}
			})
		});

		this.uploader = this.$fileuploader.$children[0];

		if (files && files.length) {
			this.uploader.add_files(files);
		}
	}

	upload_files() {
		this.dialog && this.dialog.get_primary_btn().prop('disabled', true);
		return this.uploader.upload_files()
			.then(() => {
				this.dialog && this.dialog.hide();
			});
	}

	make_dialog() {
		this.dialog = new frappe.ui.Dialog({
			title: 'Upload',
			fields: [
				{
					fieldtype: 'HTML',
					fieldname: 'upload_area'
				}
			],
			primary_action_label: __('Upload'),
			primary_action: () => this.upload_files()
		});

		this.wrapper = this.dialog.fields_dict.upload_area.$wrapper[0];
		this.dialog.show();
		this.dialog.$wrapper.on('hidden.bs.modal', function() {
			$(this).data('bs.modal', null);
			$(this).remove();
		});
	}
}
<commit_msg>fix: Update attachment limit<commit_after>import FileUploaderComponent from './FileUploader.vue';

export default class FileUploader {
	constructor({
		wrapper,
		method,
		on_success,
		doctype,
		docname,
		fieldname,
		files,
		folder,
		restrictions,
		upload_notes,
		allow_multiple,
		as_dataurl,
		disable_file_browser,
		frm
	} = {}) {
		if (frm && frm.attachments.max_reached()) {
			frappe.throw({
				title: __("Attachment Limit Reached"),
				message: __("Maximum attachment limit for this record reached."),
			});
			return;
		}

		if (!wrapper) {
			this.make_dialog();
		} else {
			this.wrapper = wrapper.get ? wrapper.get(0) : wrapper;
		}

		this.$fileuploader = new Vue({
			el: this.wrapper,
			render: h => h(FileUploaderComponent, {
				props: {
					show_upload_button: !Boolean(this.dialog),
					doctype,
					docname,
					fieldname,
					method,
					folder,
					on_success,
					restrictions,
					upload_notes,
					allow_multiple,
					as_dataurl,
					disable_file_browser,
				}
			})
		});

		this.uploader = this.$fileuploader.$children[0];

		if (files && files.length) {
			this.uploader.add_files(files);
		}
	}

	upload_files() {
		this.dialog && this.dialog.get_primary_btn().prop('disabled', true);
		return this.uploader.upload_files()
			.then(() => {
				this.dialog && this.dialog.hide();
			});
	}

	make_dialog() {
		this.dialog = new frappe.ui.Dialog({
			title: 'Upload',
			fields: [
				{
					fieldtype: 'HTML',
					fieldname: 'upload_area'
				}
			],
			primary_action_label: __('Upload'),
			primary_action: () => this.upload_files()
		});

		this.wrapper = this.dialog.fields_dict.upload_area.$wrapper[0];
		this.dialog.show();
		this.dialog.$wrapper.on('hidden.bs.modal', function() {
			$(this).data('bs.modal', null);
			$(this).remove();
		});
	}
}
<|endoftext|>


<commit_before>frappe.ui.form.ControlFloat = class ControlFloat extends frappe.ui.form.ControlInt {
	parse(value) {
		value = this.eval_expression(value);
		return isNaN(parseFloat(value)) ? null : flt(value, this.get_precision());
	}

	format_for_input(value) {
		var number_format;
		if (this.df.fieldtype==="Float" && this.df.options && this.df.options.trim()) {
			number_format = this.get_number_format();
		}
		var formatted_value = format_number(value, number_format, this.get_precision());
		return isNaN(Number(value)) ? "" : formatted_value;
	}

	get_number_format() {
		var currency = frappe.meta.get_field_currency(this.df, this.get_doc());
		return get_number_format(currency);
	}

	get_precision() {
		// round based on field precision or float precision, else don't round
		return this.df.precision || cint(frappe.boot.sysdefaults.float_precision, null);
	}
};

frappe.ui.form.ControlPercent = frappe.ui.form.ControlFloat;
<commit_msg>fix: convert back to number_format on change<commit_after>frappe.ui.form.ControlFloat = class ControlFloat extends frappe.ui.form.ControlInt {

	make_input() {
		super.make_input()
		const change_handler = e => {
			if (this.change) this.change(e);
			else {
				let value = this.get_input_value();
				this.parse_validate_and_set_in_model(value, e);
			}
		};
		// convert to number format on focusout since focus converts it to flt.
		this.$input.on("focusout", change_handler);
	}
	parse(value) {
		value = this.eval_expression(value);
		return isNaN(parseFloat(value)) ? null : flt(value, this.get_precision());
	}

	format_for_input(value) {
		var number_format;
		if (this.df.fieldtype==="Float" && this.df.options && this.df.options.trim()) {
			number_format = this.get_number_format();
		}
		var formatted_value = format_number(value, number_format, this.get_precision());
		return isNaN(Number(value)) ? "" : formatted_value;
	}

	get_number_format() {
		var currency = frappe.meta.get_field_currency(this.df, this.get_doc());
		return get_number_format(currency);
	}

	get_precision() {
		// round based on field precision or float precision, else don't round
		return this.df.precision || cint(frappe.boot.sysdefaults.float_precision, null);
	}
};

frappe.ui.form.ControlPercent = frappe.ui.form.ControlFloat;

34.4534,45<|endoftext|>