<commit_before>var Peers = (function() {
  var encoder = new tnetbin.Encoder({arraybuffer: true});
  var decoder = new tnetbin.Decoder();
  var blobDecoder = new tnetbin.Decoder({arraybuffer: true});

  function Peer(id, config) {
    var pc = new RTCPeerConnection({
      iceServers: [{
        // please contact me if you plan to use this server
        url: 'turn:webrtc.monkeypatch.me:1025?transport=udp',
        credential: 'hibuddy',
        username: 'hibuddy'
      }]
    });
    var dc;

    pc.oniceconnectionstatechange = this._onIceStateChange.bind(this);
    pc.onicecandidate = function(event) {
      this.trigger("icecandidate", event);
    }.bind(this);
    dc = pc.createDataChannel("waggle", {id: 0, negotiated: true});
    dc.onopen = this._onDatachannelOpen.bind(this);
    dc.onmessage = this._onMessage.bind(this);
    dc.onclose = this.trigger.bind(this, "disconnected");
    dc.binaryType = "arraybuffer";

    this.id = id;
    this.pc = pc;
    this.dc = dc;
    this.queue = [];
    this._timeout = null;
  }

  Peer.prototype = {
    request: function(chunk) {
      console.log("request chunk #" + chunk.id + " from " + this.id);

      this._send({
        type: "request",
        swarmId: chunk.swarm,
        chunkId: chunk.id
      });
    },

    send: function(chunk) {
      this._send({
        type: "chunk",
        swarmId: chunk.swarm,
        chunkId: chunk.id
      }, chunk.data);
    },

    createOffer: function(callback) {
      console.log("createoffer");
      this.pc.createOffer(function(offer) {
        this.pc.setLocalDescription(offer, function() {
          callback(offer);
        });
      }.bind(this), function() {});

      this.timeout.after(3).seconds();
    },

    createAnswer: function(offer, callback) {
      offer = new RTCSessionDescription(offer);
      this.pc.setRemoteDescription(offer, function() {
        this.pc.createAnswer(function(answer) {
          this.pc.setLocalDescription(answer, function() {
            callback(answer)
          });
        }.bind(this), function() {});
      }.bind(this), function() {});

      this.timeout.after(3).seconds();
    },

    complete: function(answer, callback) {
      answer = new RTCSessionDescription(answer);
      this.pc.setRemoteDescription(answer, callback);
      this.timeout.clear();
    },

    addIceCandidate: function(candidate) {
      candidate = new RTCIceCandidate(candidate);
      this.pc.addIceCandidate(candidate);
    },

    isConnected: function() {
      var iceState = this.pc.iceConnectionState;
      if (iceState === "connected" ||
          iceState === "completed")
        return true;

      return false;
    },

    willConnect: function() {
      var iceState = this.pc.iceConnectionState;
      if (iceState === "new" ||
          iceState === "checking")
        return true;

      return false;
    },

    disconnect: function() {
      if (this.dc)
        this.dc.close();
      this.pc.close();
    },

    get timeout() {
      return {
        after: function(n) {
          return {
            seconds: function() {
              var trigger = this.trigger.bind(this, "unreachable");
              var time = n * 1000;
              this._timeout = setTimeout(trigger, time);
            }.bind(this)
          };
        }.bind(this),

        clear: function() {
          clearTimeout(this._timeout);
        }.bind(this)
      };
    },

    _onIceStateChange: function() {
      // XXX: display an error if the ice connection failed
      console.log("ice: " + this.pc.iceConnectionState);
      if (this.pc.iceConnectionState === "failed") {
        console.error("Something went wrong: the connection failed");
        this.trigger("failure");
      }

      if (this.pc.iceConnectionState === "connected") {
        this.timeout.clear();
        this.trigger("connected");
      }

      if (this.pc.iceConnectionState === "disconnected" ||
          this.pc.iceConnectionState === "closed")
        this.trigger("diconnected");
    },

    _send: function(message, blob) {
      if (this.dc.readyState === "connecting") {
        this.queue.push([message, blob]);
        return;
      }

      message = encoder.encode(message);
      blob = blob ? encoder.encode(blob) : new Uint8Array(0);
      // TODO: handle errors when the datachannel is closed
      this.dc.send(tnetbin.concatArrayBuffers([message, blob]));
    },

    _onDatachannelOpen: function() {
      var item, message, blob;
      while (this.queue.length > 0) {
        item = this.queue.shift();
        message = item[0];
        blob = item[1];
        this._send(message, blob);
      }
    },

    _onMessage: function(event) {
      var payload, message, remain;

      payload = decoder.decode(event.data);
      message = payload.value;
      remain = payload.remain;

      if (remain) {
        payload = blobDecoder.decode(remain);
        message.blob = payload.value;
      } else
        message.blob = undefined

      this.trigger(message.type, message);
    }
  };

  MicroEvent.mixin(Peer);
  Peer.prototype.on = Peer.prototype.bind;

  function Peers(config) {
    this.peers = {};
    this.unreachable = new Set();
  }

  Peers.prototype = {
    get: function(id) {
      return this.peers[id];
    },

    add: function(id) {
      var peer = new Peer(id);
      this.peers[id] = peer;
      this.trigger("add", peer);
      return peer;
    },

    remove: function(id) {
      delete this.peers[id];
    },

    in: function(peers) {
      peers = [...peers];
      return {
        connected: function() {
          return peers.reduce(function(acc, uid) {
            if (this.isConnected(uid))
              acc.push(uid);
            return acc;
          }.bind(this), []);
        }.bind(this),

        notConnected: function() {
          return peers.reduce(function(acc, uid) {
            if (!this.isConnected(uid))
              acc.push(uid);

            return acc;
          }.bind(this), []);
        }.bind(this),

        reachable: function() {
          return peers.reduce(function(acc, uid) {
            var mayBeReachable = !this.unreachable.has(uid);
            if (mayBeReachable)
              acc.push(uid);

            return acc;
          }.bind(this), []);
        }.bind(this)
      };
    },

    isConnected: function(id) {
      var peer = this.peers[id];
      if (!peer)
        return false;

      var iceState = peer.pc.iceConnectionState;
      if (iceState === "failed" ||
          iceState === "disconnected" ||
          iceState === "closed")
        return false;

      return peer.pc.iceConnectionState === "connected";
    },

    connected: function() {
      return this.in(Object.keys(this.peers)).connected();
    },

    forEach: function(callback) {
      Object.keys(this.peers).forEach(function(id) {
        callback(this.peers[id]);
      }.bind(this));
    }
  };

  MicroEvent.mixin(Peers);
  Peers.prototype.on = Peers.prototype.bind;

  return Peers;
}());
<commit_msg>Replace a magic number by Peer.TIMEOUT<commit_after>var Peers = (function() {
  var encoder = new tnetbin.Encoder({arraybuffer: true});
  var decoder = new tnetbin.Decoder();
  var blobDecoder = new tnetbin.Decoder({arraybuffer: true});

  function Peer(id, config) {
    var pc = new RTCPeerConnection({
      iceServers: [{
        // please contact me if you plan to use this server
        url: 'turn:webrtc.monkeypatch.me:1025?transport=udp',
        credential: 'hibuddy',
        username: 'hibuddy'
      }]
    });
    var dc;

    pc.oniceconnectionstatechange = this._onIceStateChange.bind(this);
    pc.onicecandidate = function(event) {
      this.trigger("icecandidate", event);
    }.bind(this);
    dc = pc.createDataChannel("waggle", {id: 0, negotiated: true});
    dc.onopen = this._onDatachannelOpen.bind(this);
    dc.onmessage = this._onMessage.bind(this);
    dc.onclose = this.trigger.bind(this, "disconnected");
    dc.binaryType = "arraybuffer";

    this.id = id;
    this.pc = pc;
    this.dc = dc;
    this.queue = [];
    this._timeout = null;
  }

  Peer.TIMEOUT = 10;

  Peer.prototype = {
    request: function(chunk) {
      console.log("request chunk #" + chunk.id + " from " + this.id);

      this._send({
        type: "request",
        swarmId: chunk.swarm,
        chunkId: chunk.id
      });
    },

    send: function(chunk) {
      this._send({
        type: "chunk",
        swarmId: chunk.swarm,
        chunkId: chunk.id
      }, chunk.data);
    },

    createOffer: function(callback) {
      this.pc.createOffer(function(offer) {
        this.pc.setLocalDescription(offer, function() {
          callback(offer);
        });
      }.bind(this), function() {});

      this.timeout.after(Peer.TIMEOUT).seconds();
    },

    createAnswer: function(offer, callback) {
      offer = new RTCSessionDescription(offer);
      this.pc.setRemoteDescription(offer, function() {
        this.pc.createAnswer(function(answer) {
          this.pc.setLocalDescription(answer, function() {
            callback(answer)
          });
        }.bind(this), function() {});
      }.bind(this), function() {});

      this.timeout.after(Peer.TIMEOUT).seconds();
    },

    complete: function(answer, callback) {
      answer = new RTCSessionDescription(answer);
      this.pc.setRemoteDescription(answer, callback);
      this.timeout.clear();
    },

    addIceCandidate: function(candidate) {
      candidate = new RTCIceCandidate(candidate);
      this.pc.addIceCandidate(candidate);
    },

    isConnected: function() {
      var iceState = this.pc.iceConnectionState;
      if (iceState === "connected" ||
          iceState === "completed")
        return true;

      return false;
    },

    willConnect: function() {
      var iceState = this.pc.iceConnectionState;
      if (iceState === "new" ||
          iceState === "checking")
        return true;

      return false;
    },

    disconnect: function() {
      if (this.dc)
        this.dc.close();
      this.pc.close();
    },

    get timeout() {
      return {
        after: function(n) {
          return {
            seconds: function() {
              var trigger = this.trigger.bind(this, "unreachable");
              var time = n * 1000;
              this._timeout = setTimeout(trigger, time);
            }.bind(this)
          };
        }.bind(this),

        clear: function() {
          clearTimeout(this._timeout);
        }.bind(this)
      };
    },

    _onIceStateChange: function() {
      // XXX: display an error if the ice connection failed
      console.log("ice: " + this.pc.iceConnectionState);
      if (this.pc.iceConnectionState === "failed") {
        console.error("Something went wrong: the connection failed");
        this.trigger("failure");
      }

      if (this.pc.iceConnectionState === "connected") {
        this.timeout.clear();
        this.trigger("connected");
      }

      if (this.pc.iceConnectionState === "disconnected" ||
          this.pc.iceConnectionState === "closed")
        this.trigger("diconnected");
    },

    _send: function(message, blob) {
      if (this.dc.readyState === "connecting") {
        this.queue.push([message, blob]);
        return;
      }

      message = encoder.encode(message);
      blob = blob ? encoder.encode(blob) : new Uint8Array(0);
      // TODO: handle errors when the datachannel is closed
      this.dc.send(tnetbin.concatArrayBuffers([message, blob]));
    },

    _onDatachannelOpen: function() {
      var item, message, blob;
      while (this.queue.length > 0) {
        item = this.queue.shift();
        message = item[0];
        blob = item[1];
        this._send(message, blob);
      }
    },

    _onMessage: function(event) {
      var payload, message, remain;

      payload = decoder.decode(event.data);
      message = payload.value;
      remain = payload.remain;

      if (remain) {
        payload = blobDecoder.decode(remain);
        message.blob = payload.value;
      } else
        message.blob = undefined

      this.trigger(message.type, message);
    }
  };

  MicroEvent.mixin(Peer);
  Peer.prototype.on = Peer.prototype.bind;

  function Peers(config) {
    this.peers = {};
    this.unreachable = new Set();
  }

  Peers.prototype = {
    get: function(id) {
      return this.peers[id];
    },

    add: function(id) {
      var peer = new Peer(id);
      this.peers[id] = peer;
      this.trigger("add", peer);
      return peer;
    },

    remove: function(id) {
      delete this.peers[id];
    },

    in: function(peers) {
      peers = [...peers];
      return {
        connected: function() {
          return peers.reduce(function(acc, uid) {
            if (this.isConnected(uid))
              acc.push(uid);
            return acc;
          }.bind(this), []);
        }.bind(this),

        notConnected: function() {
          return peers.reduce(function(acc, uid) {
            if (!this.isConnected(uid))
              acc.push(uid);

            return acc;
          }.bind(this), []);
        }.bind(this),

        reachable: function() {
          return peers.reduce(function(acc, uid) {
            var mayBeReachable = !this.unreachable.has(uid);
            if (mayBeReachable)
              acc.push(uid);

            return acc;
          }.bind(this), []);
        }.bind(this)
      };
    },

    isConnected: function(id) {
      var peer = this.peers[id];
      if (!peer)
        return false;

      var iceState = peer.pc.iceConnectionState;
      if (iceState === "failed" ||
          iceState === "disconnected" ||
          iceState === "closed")
        return false;

      return peer.pc.iceConnectionState === "connected";
    },

    connected: function() {
      return this.in(Object.keys(this.peers)).connected();
    },

    forEach: function(callback) {
      Object.keys(this.peers).forEach(function(id) {
        callback(this.peers[id]);
      }.bind(this));
    }
  };

  MicroEvent.mixin(Peers);
  Peers.prototype.on = Peers.prototype.bind;

  return Peers;
}());
<|endoftext|>


<commit_before>/***** BEGIN LICENSE BLOCK ***** {{{
Version: MPL 1.1/GPL 2.0/LGPL 2.1

The contents of this file are subject to the Mozilla Public License Version
1.1 (the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.mozilla.org/MPL/

Software distributed under the License is distributed on an "AS IS" basis,
WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
for the specific language governing rights and limitations under the
License.

(c) 2006-2008: Martin Stubenschrott <stubenschrott@gmx.net>

Alternatively, the contents of this file may be used under the terms of
either the GNU General Public License Version 2 or later (the "GPL"), or
the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
in which case the provisions of the GPL or the LGPL are applicable instead
of those above. If you wish to allow use of your version of this file only
under the terms of either the GPL or the LGPL, and not to allow others to
use your version of this file under the terms of the MPL, indicate your
decision by deleting the provisions above and replace them with the notice
and other provisions required by the GPL or the LGPL. If you do not delete
the provisions above, a recipient may use your version of this file under
the terms of any one of the MPL, the GPL or the LGPL.
}}} ***** END LICENSE BLOCK *****/

// Do NOT create instances of this class yourself, use the helper method
// mappings.add() instead
function Map(modes, cmds, description, action, extraInfo) //{{{
{
    if (!modes || (!cmds || !cmds.length) || !action)
        return null;

    if (!extraInfo)
        extraInfo = {};

    this.modes = modes;
    // only store keysyms with uppercase modifier strings
    this.names = cmds.map(function (cmd) cmd.replace(/[casm]-/g, String.toUpperCase));
    this.action = action;

    this.flags = extraInfo.flags || 0;
    this.description = description || "";
    this.rhs = extraInfo.rhs || null;
    this.noremap = extraInfo.noremap || false;
};

Map.prototype = {

    hasName: function (name)
    {
        return this.names.indexOf(name) >= 0;
    },

    execute: function (motion, count, argument)
    {
        var args = [];

        if (this.flags & Mappings.flags.MOTION)
            args.push(motion);
        if (this.flags & Mappings.flags.COUNT)
            args.push(count);
        if (this.flags & Mappings.flags.ARGUMENT)
            args.push(argument);

        let self = this;
        // FIXME: Kludge.
        if (this.names[0] != ".")
            mappings.repeat = function () self.action.apply(self, args);
        return this.action.apply(this, args);
    }

}; //}}}

function Mappings() //{{{
{
    ////////////////////////////////////////////////////////////////////////////////
    ////////////////////// PRIVATE SECTION /////////////////////////////////////////
    /////////////////////////////////////////////////////////////////////////////{{{

    var main = []; // default mappings
    var user = []; // user created mappings

    for (let mode in modes)
    {
        main[mode] = [];
        user[mode] = [];
    }

    function addMap(map, userMap)
    {
        var where = userMap ? user : main;
        map.modes.forEach(function (mode) { where[mode].push(map); });
    }

    function getMap(mode, cmd, stack)
    {
        var maps = stack[mode];

        for (let [,map] in Iterator(maps))
        {
            if (map.hasName(cmd))
                return map;
        }

        return null;
    }

    function removeMap(mode, cmd)
    {
        var maps = user[mode];
        var names;

        for (let [i, map] in Iterator(maps))
        {
            for (let [j, name] in Iterator(map.names))
            {
                if (name == cmd)
                {
                    map.names.splice(j, 1);
                    if (map.names.length == 0)
                        maps.splice(i, 1);
                    return;
                }
            }
        }
    }

    function expandLeader(keyString)
    {
        var leaderRegexp = /<Leader>/i;
        var currentLeader = mappings.getMapLeader();
        return keyString.replace(leaderRegexp, currentLeader);
    }

    function mappingsIterator(modes, stack)
    {
        var output;
        var maps = stack[modes[0]];

        for (let i = 0; i < maps.length; i++)
        {
            output = true;
            for (let index = 1; index < modes.length; index++) // check other modes
            {
                output = false; // toggle false, only true whan also found in this mode
                for (let j = 0; j < user[modes[index]].length; j++) // maps
                {
                    // NOTE: when other than user maps, there might be more than only one names[x].
                    //       since only user mappings gets queried here, only names[0] gets checked for equality.
                    if (maps[i].rhs == user[modes[index]][j].rhs && maps[i].names[0] == user[modes[index]][j].names[0])
                    {
                        output = true;
                        break; // found on this mode - check next mode, if there is one, where it could still fail...
                    }
                }
                break; // not found in this mode -> map wont' match all modes...
            }
            if (output)
                yield maps[i];
        }
    }

    function addMapCommands(ch, modes, modeDescription)
    {
        // 0 args -> list all maps
        // 1 arg  -> list the maps starting with args
        // 2 args -> map arg1 to arg*
        function map(args, mode, noremap)
        {
            if (!args.arguments.length)
            {
                mappings.list(mode);
                return;
            }

            // ?:\s+ <- don't remember; (...)? optional = rhs
            let [lhs] = args.arguments;
            let rhs = args.literalArg;

            if (!rhs) // list the mapping
            {
                mappings.list(mode, expandLeader(lhs));
            }
            else
            {
                for (let [,m] in Iterator(mode))
                {
                    mappings.addUserMap([m], [lhs],
                            "User defined mapping",
                            function (count) { events.feedkeys((count > 1 ? count : "") + rhs, noremap, "<silent>" in args); },
                            {
                                flags: Mappings.flags.COUNT,
                                rhs: rhs,
                                noremap: noremap,
                            });
                }
            }
        }

        modeDescription = modeDescription ? " in " + modeDescription + " mode" : "";

        const opts = {
                completer: function (filter) completion.userMapping(filter, modes),
                options: [
                    [["<silent>", "<Silent>"],  commands.OPTION_NOARG]
                ],
                argCount: 1,
                literal: true
        };

        commands.add([ch ? ch + "m[ap]" : "map"],
            "Map a key sequence" + modeDescription,
            function (args) { map(args, modes, false); },
            opts);

        commands.add([ch + "no[remap]"],
            "Map a key sequence without remapping keys" + modeDescription,
            function (args) { map(args, modes, true); },
            opts);

        commands.add([ch + "mapc[lear]"],
            "Remove all mappings" + modeDescription,
            function () { modes.forEach(function (mode) { mappings.removeAll(mode); }); },
            { argCount: "0" });

        commands.add([ch + "unm[ap]"],
            "Remove a mapping" + modeDescription,
            function (args)
            {
                args = args.string;

                if (!args)
                {
                    liberator.echoerr("E474: Invalid argument");
                    return;
                }

                let found = false;
                for (let [,mode] in Iterator(modes))
                {
                    if (mappings.hasMap(mode, args))
                    {
                        mappings.remove(mode, args);
                        found = true;
                    }
                }
                if (!found)
                    liberator.echoerr("E31: No such mapping");
            },
            { completer: function (filter) completion.userMapping(filter, modes) });
    }

    /////////////////////////////////////////////////////////////////////////////}}}
    ////////////////////// COMMANDS ////////////////////////////////////////////////
    /////////////////////////////////////////////////////////////////////////////{{{

    addMapCommands("",  [modes.NORMAL], "");
    addMapCommands("c", [modes.COMMAND_LINE], "command line");
    addMapCommands("i", [modes.INSERT, modes.TEXTAREA], "insert");
    if (liberator.has("mail"))
        addMapCommands("m", [modes.MESSAGE], "message");

    /////////////////////////////////////////////////////////////////////////////}}}
    ////////////////////// PUBLIC SECTION //////////////////////////////////////////
    /////////////////////////////////////////////////////////////////////////////{{{

    // FIXME:
    Mappings.flags = {
        ALLOW_EVENT_ROUTING: 1 << 0, // if set, return true inside the map command to pass the event further to firefox
        MOTION:              1 << 1,
        COUNT:               1 << 2,
        ARGUMENT:            1 << 3
    };

    return {

        // NOTE: just normal mode for now
        __iterator__: function () mappingsIterator([modes.NORMAL], main),

        // used by :mkvimperatorrc to save mappings
        getUserIterator: function (mode) mappingsIterator(mode, user),

        add: function (modes, keys, description, action, extra)
        {
            addMap(new Map(modes, keys, description, action, extra), false);
        },

        addUserMap: function (modes, keys, description, action, extra)
        {
            keys = keys.map(function (key) expandLeader(key));
            var map = new Map(modes, keys, description || "User defined mapping", action, extra);

            // remove all old mappings to this key sequence
            for (let i = 0; i < map.names.length; i++)
            {
                for (let j = 0; j < map.modes.length; j++)
                    removeMap(map.modes[j], map.names[i]);
            }

            addMap(map, true);
        },

        get: function (mode, cmd)
        {
            mode = mode || modes.NORMAL;
            return getMap(mode, cmd, user) || getMap(mode, cmd, main);
        },

        getDefault: function (mode, cmd)
        {
            mode = mode || modes.NORMAL;
            return getMap(mode, cmd, main);
        },

        // returns an array of mappings with names which START with "cmd" (but are NOT "cmd")
        getCandidates: function (mode, cmd)
        {
            let mappings = user[mode].concat(main[mode]);
            let matches = [];

            for (let [,map] in Iterator(mappings))
            {
                for (let [,name] in Iterator(map.names))
                {
                    if (name.indexOf(cmd) == 0 && name.length > cmd.length)
                    {
                        // for < only return a candidate if it doesn't look like a <c-x> mapping
                        if (cmd != "<" || !/^<.+>/.test(name))
                            matches.push(map);
                    }
                }
            }

            return matches;
        },

        getMapLeader: function ()
        {
            var leaderRef = liberator.variableReference("mapleader");
            return leaderRef[0] ? leaderRef[0][leaderRef[1]] : "\\";
        },

        // returns whether the user added a custom user map
        hasMap: function (mode, cmd)
        {
            return user[mode].some(function (map) map.hasName(cmd));
        },

        remove: function (mode, cmd)
        {
            removeMap(mode, cmd);
        },

        removeAll: function (mode)
        {
            user[mode] = [];
        },

        list: function (modes, filter)
        {
            // modes means, a map must exist in both modes in order to get listed
            var maps = user[modes[0]]; // duplicate (reference) (first mode where it must match)
            var output = [];

            if (!maps || maps.length == 0)
            {
                liberator.echo("No mappings found");
                return;
            }

            for (let [i, map] in Iterator(maps)) // check on maps items (first mode)
            {
                output[i] = !filter || map.names[0] == filter;
                if (!output[i]) // does it match the filter first of all?
                    continue;
                for (let [, mode] in Iterator(modes))
                {
                    output[i] = false; // toggle false, only true whan also found in this mode
                    for (let [, usermode] in Iterator(user[mode]))
                    {
                        // NOTE: when other than user maps, there might be more than only one names[x].
                        //       since only user mappings gets queried here, only names[0] gets checked for equality.
                        if (map.rhs == usermode.rhs && map.names[0] == usermode.names[0])
                        {
                            output[i] = true;
                            break; // found on this mode - ok, check next mode...
                        }
                    }
                    break; // not found in this mode -> map wont' match all modes...
                }
            }

            // anything found?
            var flag = output.some(function (x) x);
            if (!flag)
            {
                liberator.echo("No mappings found");
                return;
            }

            var modeSign = "";
            modes.forEach(function (mode)
            {
                if (mode == modes.NORMAL)
                    modeSign += "n";
                if ((mode == modes.INSERT || mode == modes.TEXTAREA) && modeSign.indexOf("i") == -1)
                    modeSign += "i";
                if (mode == modes.COMMAND_LINE)
                    modeSign += "c";
                if (mode == modes.MESSAGRE)
                    modeSign += "m";
            });

            let _maps = (map for ([i, map] in Iterator(maps))
                             if (output[i]));
            let list =

                    {
                        template.map(_maps, function (map)
                            template.map(map.names, function (name)

                                {modeSign} {name}
                                {map.noremap ? "*" : " "}
                                {map.rhs || "function () { ... }"}

))
                    }

;
            commandline.echo(list, commandline.HL_NORMAL, commandline.FORCE_MULTILINE);
        }

    };
    //}}}
}; //}}}

// vim: set fdm=marker sw=4 ts=4 et:
<commit_msg>simplify expandLeader()<commit_after>/***** BEGIN LICENSE BLOCK ***** {{{
Version: MPL 1.1/GPL 2.0/LGPL 2.1

The contents of this file are subject to the Mozilla Public License Version
1.1 (the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.mozilla.org/MPL/

Software distributed under the License is distributed on an "AS IS" basis,
WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
for the specific language governing rights and limitations under the
License.

(c) 2006-2008: Martin Stubenschrott <stubenschrott@gmx.net>

Alternatively, the contents of this file may be used under the terms of
either the GNU General Public License Version 2 or later (the "GPL"), or
the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
in which case the provisions of the GPL or the LGPL are applicable instead
of those above. If you wish to allow use of your version of this file only
under the terms of either the GPL or the LGPL, and not to allow others to
use your version of this file under the terms of the MPL, indicate your
decision by deleting the provisions above and replace them with the notice
and other provisions required by the GPL or the LGPL. If you do not delete
the provisions above, a recipient may use your version of this file under
the terms of any one of the MPL, the GPL or the LGPL.
}}} ***** END LICENSE BLOCK *****/

// Do NOT create instances of this class yourself, use the helper method
// mappings.add() instead
function Map(modes, cmds, description, action, extraInfo) //{{{
{
    if (!modes || (!cmds || !cmds.length) || !action)
        return null;

    if (!extraInfo)
        extraInfo = {};

    this.modes = modes;
    // only store keysyms with uppercase modifier strings
    this.names = cmds.map(function (cmd) cmd.replace(/[casm]-/g, String.toUpperCase));
    this.action = action;

    this.flags = extraInfo.flags || 0;
    this.description = description || "";
    this.rhs = extraInfo.rhs || null;
    this.noremap = extraInfo.noremap || false;
};

Map.prototype = {

    hasName: function (name)
    {
        return this.names.indexOf(name) >= 0;
    },

    execute: function (motion, count, argument)
    {
        var args = [];

        if (this.flags & Mappings.flags.MOTION)
            args.push(motion);
        if (this.flags & Mappings.flags.COUNT)
            args.push(count);
        if (this.flags & Mappings.flags.ARGUMENT)
            args.push(argument);

        let self = this;
        // FIXME: Kludge.
        if (this.names[0] != ".")
            mappings.repeat = function () self.action.apply(self, args);
        return this.action.apply(this, args);
    }

}; //}}}

function Mappings() //{{{
{
    ////////////////////////////////////////////////////////////////////////////////
    ////////////////////// PRIVATE SECTION /////////////////////////////////////////
    /////////////////////////////////////////////////////////////////////////////{{{

    var main = []; // default mappings
    var user = []; // user created mappings

    for (let mode in modes)
    {
        main[mode] = [];
        user[mode] = [];
    }

    function addMap(map, userMap)
    {
        var where = userMap ? user : main;
        map.modes.forEach(function (mode) { where[mode].push(map); });
    }

    function getMap(mode, cmd, stack)
    {
        var maps = stack[mode];

        for (let [,map] in Iterator(maps))
        {
            if (map.hasName(cmd))
                return map;
        }

        return null;
    }

    function removeMap(mode, cmd)
    {
        var maps = user[mode];
        var names;

        for (let [i, map] in Iterator(maps))
        {
            for (let [j, name] in Iterator(map.names))
            {
                if (name == cmd)
                {
                    map.names.splice(j, 1);
                    if (map.names.length == 0)
                        maps.splice(i, 1);
                    return;
                }
            }
        }
    }

    function expandLeader(keyString) keyString.replace(/<Leader>/i, mappings.getMapLeader())

    function mappingsIterator(modes, stack)
    {
        var output;
        var maps = stack[modes[0]];

        for (let i = 0; i < maps.length; i++)
        {
            output = true;
            for (let index = 1; index < modes.length; index++) // check other modes
            {
                output = false; // toggle false, only true whan also found in this mode
                for (let j = 0; j < user[modes[index]].length; j++) // maps
                {
                    // NOTE: when other than user maps, there might be more than only one names[x].
                    //       since only user mappings gets queried here, only names[0] gets checked for equality.
                    if (maps[i].rhs == user[modes[index]][j].rhs && maps[i].names[0] == user[modes[index]][j].names[0])
                    {
                        output = true;
                        break; // found on this mode - check next mode, if there is one, where it could still fail...
                    }
                }
                break; // not found in this mode -> map wont' match all modes...
            }
            if (output)
                yield maps[i];
        }
    }

    function addMapCommands(ch, modes, modeDescription)
    {
        // 0 args -> list all maps
        // 1 arg  -> list the maps starting with args
        // 2 args -> map arg1 to arg*
        function map(args, mode, noremap)
        {
            if (!args.arguments.length)
            {
                mappings.list(mode);
                return;
            }

            // ?:\s+ <- don't remember; (...)? optional = rhs
            let [lhs] = args.arguments;
            let rhs = args.literalArg;

            if (!rhs) // list the mapping
            {
                mappings.list(mode, expandLeader(lhs));
            }
            else
            {
                for (let [,m] in Iterator(mode))
                {
                    mappings.addUserMap([m], [lhs],
                            "User defined mapping",
                            function (count) { events.feedkeys((count > 1 ? count : "") + rhs, noremap, "<silent>" in args); },
                            {
                                flags: Mappings.flags.COUNT,
                                rhs: rhs,
                                noremap: noremap,
                            });
                }
            }
        }

        modeDescription = modeDescription ? " in " + modeDescription + " mode" : "";

        const opts = {
                completer: function (filter) completion.userMapping(filter, modes),
                options: [
                    [["<silent>", "<Silent>"],  commands.OPTION_NOARG]
                ],
                argCount: 1,
                literal: true
        };

        commands.add([ch ? ch + "m[ap]" : "map"],
            "Map a key sequence" + modeDescription,
            function (args) { map(args, modes, false); },
            opts);

        commands.add([ch + "no[remap]"],
            "Map a key sequence without remapping keys" + modeDescription,
            function (args) { map(args, modes, true); },
            opts);

        commands.add([ch + "mapc[lear]"],
            "Remove all mappings" + modeDescription,
            function () { modes.forEach(function (mode) { mappings.removeAll(mode); }); },
            { argCount: "0" });

        commands.add([ch + "unm[ap]"],
            "Remove a mapping" + modeDescription,
            function (args)
            {
                args = args.string;

                if (!args)
                {
                    liberator.echoerr("E474: Invalid argument");
                    return;
                }

                let found = false;
                for (let [,mode] in Iterator(modes))
                {
                    if (mappings.hasMap(mode, args))
                    {
                        mappings.remove(mode, args);
                        found = true;
                    }
                }
                if (!found)
                    liberator.echoerr("E31: No such mapping");
            },
            { completer: function (filter) completion.userMapping(filter, modes) });
    }

    /////////////////////////////////////////////////////////////////////////////}}}
    ////////////////////// COMMANDS ////////////////////////////////////////////////
    /////////////////////////////////////////////////////////////////////////////{{{

    addMapCommands("",  [modes.NORMAL], "");
    addMapCommands("c", [modes.COMMAND_LINE], "command line");
    addMapCommands("i", [modes.INSERT, modes.TEXTAREA], "insert");
    if (liberator.has("mail"))
        addMapCommands("m", [modes.MESSAGE], "message");

    /////////////////////////////////////////////////////////////////////////////}}}
    ////////////////////// PUBLIC SECTION //////////////////////////////////////////
    /////////////////////////////////////////////////////////////////////////////{{{

    // FIXME:
    Mappings.flags = {
        ALLOW_EVENT_ROUTING: 1 << 0, // if set, return true inside the map command to pass the event further to firefox
        MOTION:              1 << 1,
        COUNT:               1 << 2,
        ARGUMENT:            1 << 3
    };

    return {

        // NOTE: just normal mode for now
        __iterator__: function () mappingsIterator([modes.NORMAL], main),

        // used by :mkvimperatorrc to save mappings
        getUserIterator: function (mode) mappingsIterator(mode, user),

        add: function (modes, keys, description, action, extra)
        {
            addMap(new Map(modes, keys, description, action, extra), false);
        },

        addUserMap: function (modes, keys, description, action, extra)
        {
            keys = keys.map(function (key) expandLeader(key));
            var map = new Map(modes, keys, description || "User defined mapping", action, extra);

            // remove all old mappings to this key sequence
            for (let i = 0; i < map.names.length; i++)
            {
                for (let j = 0; j < map.modes.length; j++)
                    removeMap(map.modes[j], map.names[i]);
            }

            addMap(map, true);
        },

        get: function (mode, cmd)
        {
            mode = mode || modes.NORMAL;
            return getMap(mode, cmd, user) || getMap(mode, cmd, main);
        },

        getDefault: function (mode, cmd)
        {
            mode = mode || modes.NORMAL;
            return getMap(mode, cmd, main);
        },

        // returns an array of mappings with names which START with "cmd" (but are NOT "cmd")
        getCandidates: function (mode, cmd)
        {
            let mappings = user[mode].concat(main[mode]);
            let matches = [];

            for (let [,map] in Iterator(mappings))
            {
                for (let [,name] in Iterator(map.names))
                {
                    if (name.indexOf(cmd) == 0 && name.length > cmd.length)
                    {
                        // for < only return a candidate if it doesn't look like a <c-x> mapping
                        if (cmd != "<" || !/^<.+>/.test(name))
                            matches.push(map);
                    }
                }
            }

            return matches;
        },

        getMapLeader: function ()
        {
            var leaderRef = liberator.variableReference("mapleader");
            return leaderRef[0] ? leaderRef[0][leaderRef[1]] : "\\";
        },

        // returns whether the user added a custom user map
        hasMap: function (mode, cmd)
        {
            return user[mode].some(function (map) map.hasName(cmd));
        },

        remove: function (mode, cmd)
        {
            removeMap(mode, cmd);
        },

        removeAll: function (mode)
        {
            user[mode] = [];
        },

        list: function (modes, filter)
        {
            // modes means, a map must exist in both modes in order to get listed
            var maps = user[modes[0]]; // duplicate (reference) (first mode where it must match)
            var output = [];

            if (!maps || maps.length == 0)
            {
                liberator.echo("No mappings found");
                return;
            }

            for (let [i, map] in Iterator(maps)) // check on maps items (first mode)
            {
                output[i] = !filter || map.names[0] == filter;
                if (!output[i]) // does it match the filter first of all?
                    continue;
                for (let [, mode] in Iterator(modes))
                {
                    output[i] = false; // toggle false, only true whan also found in this mode
                    for (let [, usermode] in Iterator(user[mode]))
                    {
                        // NOTE: when other than user maps, there might be more than only one names[x].
                        //       since only user mappings gets queried here, only names[0] gets checked for equality.
                        if (map.rhs == usermode.rhs && map.names[0] == usermode.names[0])
                        {
                            output[i] = true;
                            break; // found on this mode - ok, check next mode...
                        }
                    }
                    break; // not found in this mode -> map wont' match all modes...
                }
            }

            // anything found?
            var flag = output.some(function (x) x);
            if (!flag)
            {
                liberator.echo("No mappings found");
                return;
            }

            var modeSign = "";
            modes.forEach(function (mode)
            {
                if (mode == modes.NORMAL)
                    modeSign += "n";
                if ((mode == modes.INSERT || mode == modes.TEXTAREA) && modeSign.indexOf("i") == -1)
                    modeSign += "i";
                if (mode == modes.COMMAND_LINE)
                    modeSign += "c";
                if (mode == modes.MESSAGRE)
                    modeSign += "m";
            });

            let _maps = (map for ([i, map] in Iterator(maps))
                             if (output[i]));
            let list =

                    {
                        template.map(_maps, function (map)
                            template.map(map.names, function (name)

                                {modeSign} {name}
                                {map.noremap ? "*" : " "}
                                {map.rhs || "function () { ... }"}

))
                    }

;
            commandline.echo(list, commandline.HL_NORMAL, commandline.FORCE_MULTILINE);
        }

    };
    //}}}
}; //}}}

// vim: set fdm=marker sw=4 ts=4 et:
<|endoftext|>


<commit_before>import React from 'react'
import ReactGA from 'react-ga'
// MOBILIZATION and external dependencies
import { Mobilization } from 'bonde-webpage'
import { PluggableWidget, FinishMessageCustom } from 'bonde-webpage/lib/ux'
import mobilizationConnect from './mobilization.connected'
// DRAFT PLUGIN and external dependencies
import { DraftPlugin } from 'bonde-webpage/lib/plugins/draft'
// FORM PLUGIN and external dependencies
import FormPlugin from './plugin-form.connected'
import { FormAnalytics, FormTellAFriend } from 'bonde-webpage/lib/plugins/form'
// CONTENT PLUGIN and external dependencies
import { ContentPlugin } from 'bonde-webpage/lib/plugins/content'
// PRESSURE PLUGIN and external dependencies
import PressurePlugin from './plugin-pressure.connected'
import { PressureAnalytics, PressureTellAFriend } from 'bonde-webpage/lib/plugins/pressure'
import { client as graphqlClient } from 'store'
// PRESSURE PLUGIN and external dependencies
import DonationPlugin from './plugin-donation.connected'
import { DonationAnalytics, DonationTellAFriend } from 'bonde-webpage/lib/plugins/donation'
// TODO: Icons should be inside plugin reference.
import { PressureEmailIcon, PressurePhoneIcon } from './icons'

const MyCustonPressurePlugin = (props) => (
  <PressurePlugin
    {...props}
    analyticsEvents={PressureAnalytics}
    graphqlClient={graphqlClient}
    overrides={{
      FinishCustomMessage: { component: FinishMessageCustom },
      FinishDefaultMessage: { component: PressureTellAFriend },
    }}
  />
)

const plugins = [
  {
    kind: 'draft',
    component: DraftPlugin,
    options: { noOverlay: true }
  },
  {
    kind: 'form',
    component: (props) => (
      <FormPlugin
        {...props}
        analyticsEvents={FormAnalytics}
        overrides={{
          FinishCustomMessage: { component: FinishMessageCustom },
          FinishDefaultMessage: { component: FormTellAFriend },
        }}
      />
    ),
    options: DraftPlugin.setOptions({
      label: 'Formulário',
      icon: () => (<i className='fa fa-list block white' />),
      action: (widget) => {
        console.log(`update widget ${widget.id}`)
      }
    })
  },
  {
    kind: 'donation',
    component: (props) => (
      <DonationPlugin
        {...props}
        analyticsEvents={DonationAnalytics}
        overrides={{
          FinishCustomMessage: { component: FinishMessageCustom },
          FinishDefaultMessage: { component: DonationTellAFriend },
        }}
      />
    ),
    options: DraftPlugin.setOptions({
      label: 'Doação',
      icon: () => (<i className='fa fa-money block white' />),
      action: (widget) => {
        console.log(`update widget ${widget.id}`)
      }
    })
  },
  {
    kind: 'pressure',
    component: MyCustonPressurePlugin,
    options: DraftPlugin.setOptions({
      label: 'Pressão por e-mail',
      icon: PressureEmailIcon,
      action: (widget) => {
        console.log(`update widget ${widget.id}`)
      }
    })
  },
  {
    kind: 'pressure-phone',
    component: MyCustonPressurePlugin,
    options: DraftPlugin.setOptions({
      label: 'Pressão por telefone',
      icon: PressurePhoneIcon,
      action: (widget) => {
        console.log(`update widget ${widget.id}`)
      }
    })
  },
  {
    kind: 'content',
    component: ContentPlugin,
    options: Object.assign(
      {},
      DraftPlugin.setOptions({
        label: 'Texto',
        icon: () => (<i className='fa fa-font block white' />),
        action: (widget) => {
          console.log(`update widget ${widget.id}`)
        }
      }),
      { noOverlay: true }
    )
  }
]

class MobilizationPreview extends React.Component {

  componentDidMount () {
    const isTest = false
    if (!isTest && this.props.mobilization) {
      const { mobilization } = this.props

      ReactGA.initialize('UA-26278513-30')
      ReactGA.pageview('/' + mobilization.slug)

      if (mobilization.google_analytics_code) {
        ReactGA.initialize(
          mobilization.google_analytics_code,
          { gaOptions: { name: 'MobilizationTracker' } }
        )
        ReactGA.ga('MobilizationTracker.send', 'pageview', '/')
      }
    }
  }

  render () {
    // Properties received by HOC
    const { blocks, widgets } = this.props
    return (
      <Mobilization
        linkTo={b => `block-${b.id}`}
        blocks={blocks}
        widgets={widgets}
        widgetComponent={PluggableWidget}
        extraWidgetProps={{
          mobilization: this.props.mobilization,
          editable: this.props.editable,
          plugins: plugins
        }}
      />
    )
  }
}

export default mobilizationConnect(MobilizationPreview)
<commit_msg>fix(admin): pass theme props to webpage mobilization<commit_after>import React from 'react'
import ReactGA from 'react-ga'
// MOBILIZATION and external dependencies
import { Mobilization } from 'bonde-webpage'
import { PluggableWidget, FinishMessageCustom } from 'bonde-webpage/lib/ux'
import mobilizationConnect from './mobilization.connected'
// DRAFT PLUGIN and external dependencies
import { DraftPlugin } from 'bonde-webpage/lib/plugins/draft'
// FORM PLUGIN and external dependencies
import FormPlugin from './plugin-form.connected'
import { FormAnalytics, FormTellAFriend } from 'bonde-webpage/lib/plugins/form'
// CONTENT PLUGIN and external dependencies
import { ContentPlugin } from 'bonde-webpage/lib/plugins/content'
// PRESSURE PLUGIN and external dependencies
import PressurePlugin from './plugin-pressure.connected'
import { PressureAnalytics, PressureTellAFriend } from 'bonde-webpage/lib/plugins/pressure'
import { client as graphqlClient } from 'store'
// PRESSURE PLUGIN and external dependencies
import DonationPlugin from './plugin-donation.connected'
import { DonationAnalytics, DonationTellAFriend } from 'bonde-webpage/lib/plugins/donation'
// TODO: Icons should be inside plugin reference.
import { PressureEmailIcon, PressurePhoneIcon } from './icons'

const MyCustonPressurePlugin = (props) => (
  <PressurePlugin
    {...props}
    analyticsEvents={PressureAnalytics}
    graphqlClient={graphqlClient}
    overrides={{
      FinishCustomMessage: { component: FinishMessageCustom },
      FinishDefaultMessage: { component: PressureTellAFriend },
    }}
  />
)

const plugins = [
  {
    kind: 'draft',
    component: DraftPlugin,
    options: { noOverlay: true }
  },
  {
    kind: 'form',
    component: (props) => (
      <FormPlugin
        {...props}
        analyticsEvents={FormAnalytics}
        overrides={{
          FinishCustomMessage: { component: FinishMessageCustom },
          FinishDefaultMessage: { component: FormTellAFriend },
        }}
      />
    ),
    options: DraftPlugin.setOptions({
      label: 'Formulário',
      icon: () => (<i className='fa fa-list block white' />),
      action: (widget) => {
        console.log(`update widget ${widget.id}`)
      }
    })
  },
  {
    kind: 'donation',
    component: (props) => (
      <DonationPlugin
        {...props}
        analyticsEvents={DonationAnalytics}
        overrides={{
          FinishCustomMessage: { component: FinishMessageCustom },
          FinishDefaultMessage: { component: DonationTellAFriend },
        }}
      />
    ),
    options: DraftPlugin.setOptions({
      label: 'Doação',
      icon: () => (<i className='fa fa-money block white' />),
      action: (widget) => {
        console.log(`update widget ${widget.id}`)
      }
    })
  },
  {
    kind: 'pressure',
    component: MyCustonPressurePlugin,
    options: DraftPlugin.setOptions({
      label: 'Pressão por e-mail',
      icon: PressureEmailIcon,
      action: (widget) => {
        console.log(`update widget ${widget.id}`)
      }
    })
  },
  {
    kind: 'pressure-phone',
    component: MyCustonPressurePlugin,
    options: DraftPlugin.setOptions({
      label: 'Pressão por telefone',
      icon: PressurePhoneIcon,
      action: (widget) => {
        console.log(`update widget ${widget.id}`)
      }
    })
  },
  {
    kind: 'content',
    component: ContentPlugin,
    options: Object.assign(
      {},
      DraftPlugin.setOptions({
        label: 'Texto',
        icon: () => (<i className='fa fa-font block white' />),
        action: (widget) => {
          console.log(`update widget ${widget.id}`)
        }
      }),
      { noOverlay: true }
    )
  }
]

class MobilizationPreview extends React.Component {

  componentDidMount () {
    const isTest = false
    if (!isTest && this.props.mobilization) {
      const { mobilization } = this.props

      ReactGA.initialize('UA-26278513-30')
      ReactGA.pageview('/' + mobilization.slug)

      if (mobilization.google_analytics_code) {
        ReactGA.initialize(
          mobilization.google_analytics_code,
          { gaOptions: { name: 'MobilizationTracker' } }
        )
        ReactGA.ga('MobilizationTracker.send', 'pageview', '/')
      }
    }
  }

  render () {
    // Properties received by HOC
    const { blocks, widgets } = this.props
    const {
      color_scheme: colorScheme,
      header_font: headerFont,
      body_font: bodyFont
    } = this.props.mobilization

    return (
      <Mobilization
        colorScheme={colorScheme}
        headerFont={headerFont}
        bodyFont={bodyFont}
        linkTo={b => `block-${b.id}`}
        blocks={blocks}
        widgets={widgets}
        widgetComponent={PluggableWidget}
        extraWidgetProps={{
          mobilization: this.props.mobilization,
          editable: this.props.editable,
          plugins: plugins
        }}
      />
    )
  }
}

export default mobilizationConnect(MobilizationPreview)
<|endoftext|>


<commit_before>// see http://vuejs-templates.github.io/webpack for documentation.
const path = require('path')

module.exports = {
  build: {
    env: require('./prod.env'),
    index: path.resolve(__dirname, '../dist/index.html'),
    assetsRoot: path.resolve(__dirname, '../dist'),
    assetsSubDirectory: 'static',
    assetsPublicPath: '/',
    productionSourceMap: true,
    // Gzip off by default as many popular static hosts such as
    // Surge or Netlify already gzip all static assets for you.
    // Before setting to `true`, make sure to:
    // npm install --save-dev compression-webpack-plugin
    productionGzip: false,
    productionGzipExtensions: ['js', 'css'],
    // Run the build command with an extra argument to
    // View the bundle analyzer report after build finishes:
    // `npm run build --report`
    // Set to `true` or `false` to always turn it on or off
    bundleAnalyzerReport: process.env.npm_config_report
  },
  dev: {
    env: require('./dev.env'),
    port: 8080,
    autoOpenBrowser: true,
    assetsSubDirectory: 'static',
    assetsPublicPath: '/',
    proxyTable: {},
    // CSS Sourcemaps off by default because relative paths are "buggy"
    // with this option, according to the CSS-Loader README
    // (https://github.com/webpack/css-loader#sourcemaps)
    // In our experience, they generally work as expected,
    // just be aware of this issue when enabling this option.
    cssSourceMap: false
  }
}
<commit_msg>Fix Webpack configuration<commit_after>// see http://vuejs-templates.github.io/webpack for documentation.
const path = require('path')

module.exports = {
  build: {
    env: require('./prod.env'),
    index: path.resolve(__dirname, '../dist/index.html'),
    assetsRoot: path.resolve(__dirname, '../dist'),
    assetsSubDirectory: 'static',
    assetsPublicPath: '',
    productionSourceMap: true,
    // Gzip off by default as many popular static hosts such as
    // Surge or Netlify already gzip all static assets for you.
    // Before setting to `true`, make sure to:
    // npm install --save-dev compression-webpack-plugin
    productionGzip: false,
    productionGzipExtensions: ['js', 'css'],
    // Run the build command with an extra argument to
    // View the bundle analyzer report after build finishes:
    // `npm run build --report`
    // Set to `true` or `false` to always turn it on or off
    bundleAnalyzerReport: process.env.npm_config_report
  },
  dev: {
    env: require('./dev.env'),
    port: 8080,
    autoOpenBrowser: true,
    assetsSubDirectory: 'static',
    assetsPublicPath: '',
    proxyTable: {},
    // CSS Sourcemaps off by default because relative paths are "buggy"
    // with this option, according to the CSS-Loader README
    // (https://github.com/webpack/css-loader#sourcemaps)
    // In our experience, they generally work as expected,
    // just be aware of this issue when enabling this option.
    cssSourceMap: false
  }
}
<|endoftext|>


<commit_before>import _ from 'lodash';
import * as utils from '../datasource-zabbix/utils';
import { getDefaultTarget } from './triggers_panel_ctrl';

class TriggersTabCtrl {

  /** @ngInject */
  constructor($scope, $rootScope, uiSegmentSrv, templateSrv) {
    $scope.editor = this;
    this.panelCtrl = $scope.ctrl;
    this.panel = this.panelCtrl.panel;
    this.templateSrv = templateSrv;
    this.datasources = this.panelCtrl.datasources;

    // Load scope defaults
    var scopeDefaults = {
      getGroupNames: {},
      getHostNames: {},
      getApplicationNames: {},
      getProxyNames: {},
      oldTarget: _.cloneDeep(this.panel.targets)
    };
    _.defaultsDeep(this, scopeDefaults);

    this.initDatasources();
    this.panelCtrl.refresh();
  }

  initDatasources() {
    return this.panelCtrl.initDatasources()
    .then((datasources) => {
      _.each(datasources, (datasource) => {
        this.bindSuggestionFunctions(datasource);
      });
    });
  }

  bindSuggestionFunctions(datasource) {
    // Map functions for bs-typeahead
    let ds = datasource.name;
    this.getGroupNames[ds] = _.bind(this.suggestGroups, this, datasource);
    this.getHostNames[ds] = _.bind(this.suggestHosts, this, datasource);
    this.getApplicationNames[ds] = _.bind(this.suggestApps, this, datasource);
    this.getProxyNames[ds] = _.bind(this.suggestProxies, this, datasource);
  }

  suggestGroups(datasource, query, callback) {
    return datasource.zabbix.getAllGroups()
    .then(groups => {
      return _.map(groups, 'name');
    })
    .then(callback);
  }

  suggestHosts(datasource, query, callback) {
    let groupFilter = datasource.replaceTemplateVars(this.panel.targets[datasource.name].group.filter);
    return datasource.zabbix.getAllHosts(groupFilter)
    .then(hosts => {
      return _.map(hosts, 'name');
    })
    .then(callback);
  }

  suggestApps(datasource, query, callback) {
    let groupFilter = datasource.replaceTemplateVars(this.panel.targets[datasource.name].group.filter);
    let hostFilter = datasource.replaceTemplateVars(this.panel.targets[datasource.name].host.filter);
    return datasource.zabbix.getAllApps(groupFilter, hostFilter)
    .then(apps => {
      return _.map(apps, 'name');
    })
    .then(callback);
  }

  suggestProxies(datasource, query, callback) {
    return datasource.zabbix.getProxies()
    .then(proxies => _.map(proxies, 'host'))
    .then(callback);
  }

  datasourcesChanged() {
    _.each(this.panel.datasources, (ds) => {
      if (!this.panel.targets[ds]) {
        this.panel.targets[ds] = getDefaultTarget();
      }
    });
    this.parseTarget();
  }

  parseTarget() {
    this.initDatasources()
    .then(() => {
      var newTarget = _.cloneDeep(this.panel.targets);
      if (!_.isEqual(this.oldTarget, newTarget)) {
        this.oldTarget = newTarget;
        this.panelCtrl.refresh();
      }
    });
  }

  isRegex(str) {
    return utils.isRegex(str);
  }

  isVariable(str) {
    return utils.isTemplateVariable(str, this.templateSrv.variables);
  }
}

export function triggerPanelTriggersTab() {
  return {
    restrict: 'E',
    scope: true,
    templateUrl: 'public/plugins/alexanderzobnin-zabbix-app/panel-triggers/partials/triggers_tab.html',
    controller: TriggersTabCtrl,
  };
}
<commit_msg>problems: fix panel update when datasource removed from targets<commit_after>import _ from 'lodash';
import * as utils from '../datasource-zabbix/utils';
import { getDefaultTarget } from './triggers_panel_ctrl';

class TriggersTabCtrl {

  /** @ngInject */
  constructor($scope, $rootScope, uiSegmentSrv, templateSrv) {
    $scope.editor = this;
    this.panelCtrl = $scope.ctrl;
    this.panel = this.panelCtrl.panel;
    this.templateSrv = templateSrv;
    this.datasources = this.panelCtrl.datasources;

    // Load scope defaults
    var scopeDefaults = {
      getGroupNames: {},
      getHostNames: {},
      getApplicationNames: {},
      getProxyNames: {},
      oldTarget: _.cloneDeep(this.panel.targets)
    };
    _.defaultsDeep(this, scopeDefaults);

    this.initDatasources();
    this.panelCtrl.refresh();
  }

  initDatasources() {
    return this.panelCtrl.initDatasources()
    .then((datasources) => {
      _.each(datasources, (datasource) => {
        this.bindSuggestionFunctions(datasource);
      });
    });
  }

  bindSuggestionFunctions(datasource) {
    // Map functions for bs-typeahead
    let ds = datasource.name;
    this.getGroupNames[ds] = _.bind(this.suggestGroups, this, datasource);
    this.getHostNames[ds] = _.bind(this.suggestHosts, this, datasource);
    this.getApplicationNames[ds] = _.bind(this.suggestApps, this, datasource);
    this.getProxyNames[ds] = _.bind(this.suggestProxies, this, datasource);
  }

  suggestGroups(datasource, query, callback) {
    return datasource.zabbix.getAllGroups()
    .then(groups => {
      return _.map(groups, 'name');
    })
    .then(callback);
  }

  suggestHosts(datasource, query, callback) {
    let groupFilter = datasource.replaceTemplateVars(this.panel.targets[datasource.name].group.filter);
    return datasource.zabbix.getAllHosts(groupFilter)
    .then(hosts => {
      return _.map(hosts, 'name');
    })
    .then(callback);
  }

  suggestApps(datasource, query, callback) {
    let groupFilter = datasource.replaceTemplateVars(this.panel.targets[datasource.name].group.filter);
    let hostFilter = datasource.replaceTemplateVars(this.panel.targets[datasource.name].host.filter);
    return datasource.zabbix.getAllApps(groupFilter, hostFilter)
    .then(apps => {
      return _.map(apps, 'name');
    })
    .then(callback);
  }

  suggestProxies(datasource, query, callback) {
    return datasource.zabbix.getProxies()
    .then(proxies => _.map(proxies, 'host'))
    .then(callback);
  }

  datasourcesChanged() {
    _.each(this.panel.datasources, (ds) => {
      if (!this.panel.targets[ds]) {
        this.panel.targets[ds] = getDefaultTarget();
      }
    });
    // Remove unchecked targets
    _.each(this.panel.targets, (target, ds) => {
      if (!_.includes(this.panel.datasources, ds)) {
        delete this.panel.targets[ds];
      }
    });
    this.parseTarget();
  }

  parseTarget() {
    this.initDatasources()
    .then(() => {
      var newTarget = _.cloneDeep(this.panel.targets);
      if (!_.isEqual(this.oldTarget, newTarget)) {
        this.oldTarget = newTarget;
        this.panelCtrl.refresh();
      }
    });
  }

  isRegex(str) {
    return utils.isRegex(str);
  }

  isVariable(str) {
    return utils.isTemplateVariable(str, this.templateSrv.variables);
  }
}

export function triggerPanelTriggersTab() {
  return {
    restrict: 'E',
    scope: true,
    templateUrl: 'public/plugins/alexanderzobnin-zabbix-app/panel-triggers/partials/triggers_tab.html',
    controller: TriggersTabCtrl,
  };
}
<|endoftext|>


<commit_before>var XPATHPARSER_VERSION = 14;
export default XPATHPARSER_VERSION;
<commit_msg>Up the parser version.<commit_after>var XPATHPARSER_VERSION = 15;
export default XPATHPARSER_VERSION;
<|endoftext|>


<commit_before>define(["dojo/main", "ppwcode/contracts/doh",
        "../UrlBuilder"],
  function(dojo, doh,
           UrlBuilder) {

    doh.register("ppwcode vernacular persistence UrlBuilder", [

      function testConstructor() {
        var subject = new UrlBuilder();
        doh.invars(subject);
      }

      // can't test anything else; this is an interface

    ]);

  }
);
<commit_msg>added License<commit_after>/*
 Copyright 2013 - $Date $ by PeopleWare n.v.

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 */

define(["dojo/main", "ppwcode/contracts/doh",
        "../UrlBuilder"],
  function(dojo, doh,
           UrlBuilder) {

    doh.register("ppwcode vernacular persistence UrlBuilder", [

      function testConstructor() {
        var subject = new UrlBuilder();
        doh.invars(subject);
      }

      // can't test anything else; this is an interface

    ]);

  }
);
<|endoftext|>


<commit_before>import crypto from 'crypto';
import {IPreset} from './defs';
import {AdvancedBuffer, getRandomInt, getRandomChunks, numberToBuffer} from '../utils';

/**
 * @description
 *   A simple obfuscator to significantly randomize the length of each packet.
 *   It can be used to prevent statistical analysis based on packet length.
 *
 * @examples
 *   {
 *     "name": "obfs-random-padding"
 *   }
 *
 * @protocol
 *
 *   # TCP stream
 *   +-----------+-----------+-----+
 *   |  Chunk_0  |  Chunk_1  | ... |
 *   +-----------+-----------+-----+
 *   | Variable  | Variable  | ... |
 *   +-----------+-----------+-----+
 *
 *   # Chunk_i
 *   +------------+-----------+----------+-----------+
 *   | PaddingLen |  Padding  |  DataLen |   Data    |
 *   +------------+-----------+----------+-----------+
 *   |     1      | Variable  |    2     | Variable  |
 *   +------------+-----------+----------+-----------+
 *
 * @explain
 *   1. PaddingLen is randomly picked from [0, 0xFF].
 *   2. PADDING is filled with random bytes.
 *   3. Because DataLen occupies 2 bytes, the length of each Data is therefore limited to [0, 0xFFFF].
 *   4. PaddingLen and DataLen are big-endian.
 */
export default class ObfsRandomPaddingPreset extends IPreset {

  _adBuf = null;

  constructor() {
    super();
    this._adBuf = new AdvancedBuffer({
      getPacketLength: this.onReceiving.bind(this)
    });
    this._adBuf.on('data', this.onChunkReceived.bind(this));
  }

  beforeOut({buffer}) {
    const chunks = getRandomChunks(buffer, 0, 0xffff).map((data) => {
      const pLen = getRandomInt(0, 0xff);
      const padding = crypto.randomBytes(pLen);
      return Buffer.concat([numberToBuffer(pLen, 1), padding, numberToBuffer(data.length), data]);
    });
    return Buffer.concat(chunks);
  }

  beforeIn({buffer, next, fail}) {
    this._adBuf.put(buffer, {next, fail});
  }

  onReceiving(buffer, {fail}) {
    if (buffer.length < 3) {
      return fail(`too short to get padding length, dump=${buffer.toString('hex')}`);
    }
    const pLen = buffer[0];
    if (buffer.length < 1 + pLen) {
      return; // too short to drop Padding
    }
    const dLen = buffer.readUInt16BE(1 + pLen);
    if (buffer.length < 1 + pLen + 2 + dLen) {
      return; // too short to get Data
    }
    return 1 + pLen + 2 + dLen;
  }

  onChunkReceived(chunk, {next}) {
    const pLen = chunk[0];
    next(chunk.slice(1 + pLen + 2));
  }

}
<commit_msg>presets: fix obfs-random-padding<commit_after>import crypto from 'crypto';
import {IPreset} from './defs';
import {AdvancedBuffer, getRandomInt, getRandomChunks, numberToBuffer} from '../utils';

/**
 * @description
 *   A simple obfuscator to significantly randomize the length of each packet.
 *   It can be used to prevent statistical analysis based on packet length.
 *
 * @examples
 *   {
 *     "name": "obfs-random-padding"
 *   }
 *
 * @protocol
 *
 *   # TCP stream
 *   +-----------+-----------+-----+
 *   |  Chunk_0  |  Chunk_1  | ... |
 *   +-----------+-----------+-----+
 *   | Variable  | Variable  | ... |
 *   +-----------+-----------+-----+
 *
 *   # Chunk_i
 *   +------------+-----------+----------+-----------+
 *   | PaddingLen |  Padding  |  DataLen |   Data    |
 *   +------------+-----------+----------+-----------+
 *   |     1      | Variable  |    2     | Variable  |
 *   +------------+-----------+----------+-----------+
 *
 * @explain
 *   1. PaddingLen is randomly picked from [0, 0xFF].
 *   2. PADDING is filled with random bytes.
 *   3. Because DataLen occupies 2 bytes, the length of each Data is therefore limited to [0, 0xFFFF].
 *   4. PaddingLen and DataLen are big-endian.
 */
export default class ObfsRandomPaddingPreset extends IPreset {

  _adBuf = null;

  constructor() {
    super();
    this._adBuf = new AdvancedBuffer({
      getPacketLength: this.onReceiving.bind(this)
    });
    this._adBuf.on('data', this.onChunkReceived.bind(this));
  }

  beforeOut({buffer}) {
    const chunks = getRandomChunks(buffer, 0, 0xffff).map((data) => {
      const pLen = getRandomInt(0, 0xff);
      const padding = crypto.randomBytes(pLen);
      return Buffer.concat([numberToBuffer(pLen, 1), padding, numberToBuffer(data.length), data]);
    });
    return Buffer.concat(chunks);
  }

  beforeIn({buffer, next}) {
    this._adBuf.put(buffer, {next});
  }

  onReceiving(buffer) {
    if (buffer.length < 3) {
      return; // too short to get PaddingLen
    }
    const pLen = buffer[0];
    if (buffer.length < 1 + pLen + 2) {
      return; // too short to drop Padding and get DataLen
    }
    const dLen = buffer.readUInt16BE(1 + pLen);
    if (buffer.length < 1 + pLen + 2 + dLen) {
      return; // too short to get Data
    }
    return 1 + pLen + 2 + dLen;
  }

  onChunkReceived(chunk, {next}) {
    const pLen = chunk[0];
    next(chunk.slice(1 + pLen + 2));
  }

}
<|endoftext|>


<commit_before>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
// @flow
import { oneLine } from 'common-tags';

export function uploadBinaryProfileData(): * {
  const xhr = new XMLHttpRequest();
  let isAborted = false;

  return {
    abortFunction: (): void => {
      isAborted = true;
      xhr.abort();
    },
    startUpload: (
      data: $TypedArray,
      progressChangeCallback?: number => mixed
    ): Promise<string> =>
      new Promise((resolve, reject) => {
        if (isAborted) {
          reject(new Error('The request was already aborted.'));
          return;
        }

        xhr.onload = () => {
          if (xhr.status === 200) {
            resolve(xhr.responseText);
          } else {
            reject(
              new Error(
                `xhr onload with status != 200, xhr.statusText: ${xhr.statusText}`
              )
            );
          }
        };

        xhr.onerror = () => {
          console.error(
            'There was an XHR error in uploadBinaryProfileData()',
            xhr
          );
          reject(
            new Error(
              // The profile store does not give useful responses.
              // See: https://github.com/firefox-devtools/profiler/issues/998
              xhr.statusText
                ? oneLine`
                    There was an issue uploading the profile to the server. This is often
                    caused by the profile file size being too large. The error
                    response was: ${xhr.statusText}
                  `
                : 'Unable to make a connection to publish the profile.'
            )
          );
        };

        xhr.upload.onprogress = e => {
          if (progressChangeCallback && e.lengthComputable) {
            progressChangeCallback(e.loaded / e.total);
          }
        };

        xhr.open('POST', 'https://profile-store.appspot.com/compressed-store');
        xhr.send(data);
      }),
  };
}
<commit_msg>Add necessary code to use the new profiler server<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
// @flow
import { oneLine } from 'common-tags';

const PUBLISHING_ENDPOINT = 'https://api.profiler.firefox.com/compressed-store';
const ACCEPT_HEADER_VALUE = 'application/vnd.firefox-profiler+json;version=1.0';

export function uploadBinaryProfileData(): * {
  const xhr = new XMLHttpRequest();
  let isAborted = false;

  return {
    abortFunction: (): void => {
      isAborted = true;
      xhr.abort();
    },
    startUpload: (
      data: $TypedArray,
      progressChangeCallback?: number => mixed
    ): Promise<string> =>
      new Promise((resolve, reject) => {
        if (isAborted) {
          reject(new Error('The request was already aborted.'));
          return;
        }

        xhr.onload = () => {
          switch (xhr.status) {
            case 413:
              reject(
                new Error(
                  oneLine`
                    The profile size is too large.
                    You can try enabling some of the privacy features to trim its size down.
                  `
                )
              );
              break;
            default:
              if (xhr.status >= 200 && xhr.status <= 299) {
                // Success!
                resolve(xhr.responseText);
              } else {
                reject(
                  new Error(
                    `xhr onload with status != 200, xhr.statusText: ${xhr.statusText}`
                  )
                );
              }
          }
        };

        xhr.onerror = () => {
          console.error(
            'There was an XHR network error in uploadBinaryProfileData()',
            xhr
          );

          let errorMessage =
            'Unable to make a connection to publish the profile.';
          if (xhr.statusText) {
            errorMessage += ` The error response was: ${xhr.statusText}`;
          }
          reject(new Error(errorMessage));
        };

        xhr.upload.onprogress = e => {
          if (progressChangeCallback && e.lengthComputable) {
            progressChangeCallback(e.loaded / e.total);
          }
        };

        xhr.open('POST', PUBLISHING_ENDPOINT);
        xhr.setRequestHeader('Accept', ACCEPT_HEADER_VALUE);
        xhr.send(data);
      }),
  };
}
<|endoftext|>


<commit_before><commit_msg>Move tooltip hiding to constructor<commit_after><|endoftext|>


<commit_before>define([
    'knockout',
    'underscore',
    'viewmodels/widget'
], function(ko, _, WidgetViewModel) {
    /**
     * A viewmodel used for domain widgets
     *
     * @constructor
     * @name DomainWidgetViewModel
     *
     * @param  {string} params - a configuration object
     */
    var DomainWidgetViewModel = function(params) {
        var self = this;

        WidgetViewModel.apply(this, [params]);

        var value = self.configForm ? self.defaultValue : self.value;

        if (this.node.config.options) {
            this.options = this.node.config.options;
            ko.unwrap(this.options).forEach(function(option) {
                if (!ko.isObservable(option.text)) {
                    option.text = ko.observable(option.text);
                }
            });
            // force the node config to refresh (so it detects text observables)
            this.node.configKeys.valueHasMutated();
        }

        var flattenOptions = function(opt, allOpts) {
            if (opt['id'] !== undefined) {
                allOpts.push(opt);
            }
            if (opt.children) {
                opt.children.forEach(function(child) {
                    flattenOptions(child, allOpts);
                });
            }
            return allOpts;
        };

        this.toggleOptionSelection = function (opt) {
            var selected = !self.isOptionSelected(opt);
            self.setOptionSelection(opt, selected);
        };

        this.setOptionSelection = function (opt, selected) {
            if (ko.unwrap(self.disabled) === false) {
                if (self.multiple) {
                    var val = value();
                    value(
                        selected ?
                        _.union([opt.id], val) :
                        _.without(val ? val : [], opt.id)
                    );
                } else if (selected) {
                  if (value() === opt.id) {
                      value(null)
                    }
                  else {
                      value(opt.id);
                  }
                }
            }
        };

        this.isOptionSelected = function (opt) {
            var selected = false;
            var val = value();
            if (val && val.indexOf) {
                selected = val.indexOf(opt.id) >= 0;
            }
            return selected;
        };

        this.flatOptions = ko.computed(function() {
            var options = ko.unwrap(self.options) || [];
            var flatOptions = [];
            options.forEach(function(option) {
                flattenOptions(option, flatOptions);
            });
            return flatOptions;
        });

        this.multiple = false;

        this.displayValue = ko.computed(function() {
            var val = self.value();
            var opts = ko.unwrap(self.flatOptions);
            var displayVal = null;
            if (val) {
                Array.isArray(val) || (val = [val]);
                displayVal = _.without(
                    _.map(val, function(id) {
                        var opt = _.find(opts, function(opt) {
                            return opt.id === id;
                        });
                        return opt ? ko.unwrap(opt.text) : null;
                    }),
                    null
                ).join(', ');
            }
            return displayVal;
        });
    };

    return DomainWidgetViewModel;
});
<commit_msg>Fixes bug in domain radio widget. re #3701<commit_after>define([
    'knockout',
    'underscore',
    'viewmodels/widget'
], function(ko, _, WidgetViewModel) {
    /**
     * A viewmodel used for domain widgets
     *
     * @constructor
     * @name DomainWidgetViewModel
     *
     * @param  {string} params - a configuration object
     */
    var DomainWidgetViewModel = function(params) {
        var self = this;

        WidgetViewModel.apply(this, [params]);

        var value = self.configForm ? self.defaultValue : self.value;

        if (this.node.config.options) {
            this.options = this.node.config.options;
            ko.unwrap(this.options).forEach(function(option) {
                if (!ko.isObservable(option.text)) {
                    option.text = ko.observable(option.text);
                }
            });
            // force the node config to refresh (so it detects text observables)
            this.node.configKeys.valueHasMutated();
        }

        var flattenOptions = function(opt, allOpts) {
            if (opt['id'] !== undefined) {
                allOpts.push(opt);
            }
            if (opt.children) {
                opt.children.forEach(function(child) {
                    flattenOptions(child, allOpts);
                });
            }
            return allOpts;
        };

        this.toggleOptionSelection = function (opt) {
            var selected = !self.isOptionSelected(opt);
            self.setOptionSelection(opt, selected);
        };

        this.setOptionSelection = function (opt, selected) {
            if (ko.unwrap(self.disabled) === false) {
                var optid = ko.unwrap(opt.id);
                if (self.multiple) {
                    var val = value();
                    value(
                        selected ?
                        _.union([optid], val) :
                        _.without(val ? val : [], optid)
                    );
                } else if (selected) {
                  if (value() === optid) {
                      value(null)
                    }
                  else {
                      value(optid);
                  }
                }
            }
        };

        this.isOptionSelected = function (opt) {
            var selected = false;
            var val = value();
            if (val && val.indexOf) {
                selected = val.indexOf(ko.unwrap(opt.id)) >= 0;
            }
            return selected;
        };

        this.flatOptions = ko.computed(function() {
            var options = ko.unwrap(self.options) || [];
            var flatOptions = [];
            options.forEach(function(option) {
                flattenOptions(option, flatOptions);
            });
            return flatOptions;
        });

        this.multiple = false;

        this.displayValue = ko.computed(function() {
            var val = self.value();
            var opts = ko.unwrap(self.flatOptions);
            var displayVal = null;
            if (val) {
                Array.isArray(val) || (val = [val]);
                displayVal = _.without(
                    _.map(val, function(id) {
                        var opt = _.find(opts, function(opt) {
                            return opt.id === id;
                        });
                        return opt ? ko.unwrap(opt.text) : null;
                    }),
                    null
                ).join(', ');
            }
            return displayVal;
        });
    };

    return DomainWidgetViewModel;
});
<|endoftext|>


<commit_before>/**
 * This file contains all necessary Angular controller definitions for 'frontend.admin.login-history' module.
 *
 * Note that this file should only contain controllers and nothing else.
 */
(function() {
  'use strict';

  angular.module('frontend.consumers')
    .controller('ConsumersController', [
      '_','$scope', '$log', '$state','ConsumerService','$q','MessageService',
        'RemoteStorageService','UserService','SocketHelperService',
        '$uibModal','DialogService','ConsumerModel','ListConfig',
      function controller(_,$scope, $log, $state, ConsumerService,$q,MessageService,
                          RemoteStorageService,UserService,SocketHelperService,
                          $uibModal,DialogService,ConsumerModel,ListConfig ) {

          ConsumerModel.setScope($scope, false, 'items', 'itemCount');
          $scope = angular.extend($scope, angular.copy(ListConfig.getConfig('consumer',ConsumerModel)));
          $scope.user = UserService.user();
          $scope.importConsumers = importConsumers
          $scope.openCreateConsumerModal = openCreateConsumerModal

          function importConsumers() {
              $uibModal.open({
                  animation: true,
                  ariaLabelledBy: 'modal-title',
                  ariaDescribedBy: 'modal-body',
                  templateUrl: 'js/app/consumers/import/modal-select-storage.html',
                  controller: 'ImportConsumersStorageController',
                  controllerAs: '$ctrl',
                  resolve : {
                      _adapters : function() {
                          return RemoteStorageService.loadAdapters();
                      }
                  }
              });
          }

          function openCreateConsumerModal() {
              $uibModal.open({
                  animation: true,
                  ariaLabelledBy: 'modal-title',
                  ariaDescribedBy: 'modal-body',
                  templateUrl: 'js/app/consumers/create-consumer-modal.html',
                  controller: function($scope,$rootScope,$log,$uibModalInstance,MessageService,ConsumerModel,ListConfig){

                      ConsumerModel.setScope($scope, false, 'items', 'itemCount');
                      $scope = angular.extend($scope, angular.copy(ListConfig.getConfig('consumer',ConsumerModel)));

                      $scope.consumer = {
                          username  : '',
                          custom_id : ''
                      }

                      $scope.close = close
                      $scope.submit = submit

                      function submit(){

                          $scope.errors = {}

                          ConsumerModel.create($scope.consumer)
                              .then(function(res){
                                  MessageService.success("Consumer created successfully!")
                                  $rootScope.$broadcast('consumer.created',res.data)
                                  close()
                              }).catch(function(err){
                                $log.error("Failed to create consumer", err)

                                $scope.handleErrors(err)

                          })
                      }

                      function close() {
                          $uibModalInstance.dismiss()
                      }
                  },
                  controllerAs: '$ctrl',
              });
          }

          function _fetchData() {

              $scope.loading = true;
              ConsumerModel.load({
                  size : $scope.itemsFetchSize
              }).then(function(response){
                  $scope.items = response;
                  $scope.loading= false;

              })
          }

          $scope.$on('consumer.created',function(ev,user){
              _fetchData()
          })

          $scope.$on('consumer.updated',function(ev,user){
              _fetchData()
          })

          $scope.$on('credentials.assigned',function(ev,user){
              _fetchData()
          })

          $scope.$on('search',function(ev,user){
              _fetchData()
          })

          $scope.$on('user.node.updated',function(ev,node){
              _fetchData()
          })

          _fetchData()

      }
    ])
}());
<commit_msg>Fix bug $scope overwrite<commit_after>/**
 * This file contains all necessary Angular controller definitions for 'frontend.admin.login-history' module.
 *
 * Note that this file should only contain controllers and nothing else.
 */
(function() {
  'use strict';

  angular.module('frontend.consumers')
    .controller('ConsumersController', [
      '_','$scope', '$log', '$state','ConsumerService','$q','MessageService',
        'RemoteStorageService','UserService','SocketHelperService',
        '$uibModal','DialogService','ListConfig','ConsumerModel',
      function controller(_,$scope, $log, $state, ConsumerService,$q,MessageService,
                          RemoteStorageService,UserService,SocketHelperService,
                          $uibModal,DialogService,ListConfig,ConsumerModel ) {

          ConsumerModel.setScope($scope, false, 'items', 'itemCount');
          $scope = angular.extend($scope, angular.copy(ListConfig.getConfig('consumer',ConsumerModel)));
          $scope.user = UserService.user();
          $scope.importConsumers = importConsumers
          $scope.openCreateConsumerModal = openCreateConsumerModal

          function importConsumers() {
              $uibModal.open({
                  animation: true,
                  ariaLabelledBy: 'modal-title',
                  ariaDescribedBy: 'modal-body',
                  templateUrl: 'js/app/consumers/import/modal-select-storage.html',
                  controller: 'ImportConsumersStorageController',
                  controllerAs: '$ctrl',
                  resolve : {
                      _adapters : function() {
                          return RemoteStorageService.loadAdapters();
                      }
                  }
              });
          }

          function openCreateConsumerModal() {
              $uibModal.open({
                  animation: true,
                  ariaLabelledBy: 'modal-title',
                  ariaDescribedBy: 'modal-body',
                  templateUrl: 'js/app/consumers/create-consumer-modal.html',
                  controller: function($scope,$rootScope,$log,$uibModalInstance,MessageService,ConsumerModel){

                      $scope.consumer = {
                          username  : '',
                          custom_id : ''
                      }

                      $scope.close = close
                      $scope.submit = submit

                      function submit(){

                          $scope.errors = {}

                          ConsumerModel.create($scope.consumer)
                              .then(function(res){
                                  MessageService.success("Consumer created successfully!")
                                  $rootScope.$broadcast('consumer.created',res.data)
                                  close()
                              }).catch(function(err){
                                $log.error("Failed to create consumer", err)

                                $scope.handleErrors(err)

                          })
                      }

                      function close() {
                          $uibModalInstance.dismiss()
                      }
                  },
                  controllerAs: '$ctrl',
              });
          }

          function _fetchData() {

              $scope.loading = true;
              ConsumerModel.load({
                  size : $scope.itemsFetchSize
              }).then(function(response){
                  $scope.items = response;
                  $scope.loading= false;

              })
          }

          $scope.$on('consumer.created',function(ev,user){
              _fetchData()
          })

          $scope.$on('consumer.updated',function(ev,user){
              _fetchData()
          })

          $scope.$on('credentials.assigned',function(ev,user){
              _fetchData()
          })

          $scope.$on('search',function(ev,user){
              _fetchData()
          })

          $scope.$on('user.node.updated',function(ev,node){
              _fetchData()
          })

          _fetchData()

      }
    ])
}());
<|endoftext|>


<commit_before>var dot_product_correct = (function() {

var origin = [150, 140],
  scale = 60,
  scatter = [],
  axis = [],
  expectedAxis = [],
  beta = 0, alpha = 0,

  startAngleX = Math.PI/8 * 2.65,
  startAngleY = -Math.PI/8,
  startAngleZ = Math.PI/8 * 0.6;

let  axis_len = 2,
  unit = axis_len/10;

var svg = d3.select("#svg_dot_product_correct");

var lib = space_plot_lib(
  svg,
  origin,
  scale,
  is_2d=false)

svg = svg.call(d3.drag()
         .on('start', drag_start)
         .on('drag', dragged)
         .on('end', drag_end))
         .append('g');

axis = lib.init_float_axis(axis_len=axis_len, unit=unit);

function plot(scatter, axis, tt){

  var lines = [], points = [];

  lib.plot_lines(axis);

  scatter.forEach(function(d){
    lines.push(...lib.create_segments(d));
  })

  basis = {
      ex: axis[1/unit - 1 + axis_len/unit * 0][1],
      ey: axis[1/unit - 1 + axis_len/unit * 1][1],
      ez: axis[1/unit - 1 + axis_len/unit * 2][1],
  };

  let u = Object.assign({}, scatter[0]),
      v = Object.assign({}, scatter[1]);
  let v_norm = Math.sqrt(v.x*v.x + v.y*v.y + v.z*v.z);

  let v_ = lib.normalize(v);
  v_.r = 7;
  v_.opacity = 0.5;
  v_.centroid_z = -1000;
  v_.text = '|v| = 1.00';
  v_.text_opacity = 0.5;

  let uTv = lib.dot_product(u, v);
  let uTvv = {x: v_.x * uTv,
              y: v_.y * uTv,
              z: v_.z * uTv};

  let uTvv_line = [
      {x: 0, y: 0, z: 0},
      {x: uTvv.x, y: uTvv.y, z: uTvv.z}
  ]
  uTvv_line.color = 0;
  uTvv_line.centroid_z = 1000;
  uTvv_line.text = 'u\u1d40v';
  uTvv_line.text_color = 0;
  uTvv_line.font_size = 14;
  uTvv_line.text_opacity = 1.0;

  let uTv_ = lib.dot_product(u, v_);
  let uTvv_ = {x: v_.x * uTv_,
              y: v_.y * uTv_,
              z: v_.z * uTv_};

  let uTvv__line = [
      {x: 0, y: 0, z: 0},
      {x: uTvv_.x, y: uTvv_.y, z: uTvv_.z}
  ]
  uTvv__line.color = 0;
  uTvv__line.stroke_width = 5;
  uTvv__line.opacity = 0.5;

  lines.push(uTvv_line);
  lines.push(uTvv__line);
  lines.push(...lib.create_dash_segments(u, uTvv_));

  u.text = 'u';
  v.text = '|v| = ' + v_norm.toFixed(2);
  points = [u, v, v_];

  lib.plot_lines(lines, tt, 'arrow');
  lib.plot_points(points, tt,
                  drag_point_fn=dragged_point,
                  drag_start_fn=drag_start,
                  drag_end_fn=drag_end);
  lib.sort();
}

function init(){

  let u = {
      x: 0.8,
      y: 0.8,
      z: -0.8,
      color: 4
  },
      v = {
      x: 1/Math.sqrt(14),
      y: -2/Math.sqrt(14),
      z: 3/Math.sqrt(14),
      color: 2,
  };

  scatter = [u, v];

  expectedScatter = lib.rotate_points(
      scatter, startAngleX, startAngleY, startAngleZ);
  expectedAxis = lib.rotate_lines(
      axis, startAngleX, startAngleY, startAngleZ);
  plot(expectedScatter,
       expectedAxis,
       1000);
  drag_end();
}

function drag_start(){
  lib.drag_start();
}

function dragged(){
  [angle_x, angle_y] = lib.get_drag_angles();

  expectedScatter = lib.rotate_points(scatter, angle_x, angle_y);
  expectedAxis = lib.rotate_lines(axis, angle_x, angle_y);

  plot(expectedScatter,
       expectedAxis,
       0);
}

function dragged_point_only(){
  [angle_x, angle_y] = lib.get_drag_angles();

  expectedScatter = lib.rotate_points(scatter, angle_x, angle_y);

  plot(expectedScatter,
       expectedAxis,
       0);
}
function stretch_point(d, i){
  let d_ = lib.normalize(d),
      d2d_ = lib.normalize({x: d.x, y: d.y, z:0}),
      m = lib.mouse_to_point_position();

  let d_Tm = lib.dot_product(d2d_, m);
  let p = {
    x: d_.x * d_Tm,
    y: d_.y * d_Tm,
    z: d_.z * d_Tm,
  }
  expectedScatter = [];
  scatter.forEach(function(d, j){
      if (j == i) {
        d.x = p.x;
        d.y = p.y;
        d.z = p.z;
      }
      expectedScatter.push(d);
  });

  plot(expectedScatter,
       expectedAxis,
       0);
}

function dragged_point(d, i){
  if (i == 1) {
    stretch_point(d, i);
    return;
  } else if (i == 2) {
    dragged_point_only();
    return;
  }
  [angle_x, angle_y] = lib.get_drag_angles();

  expectedScatter = [];
  scatter.forEach(function(d, j){
      if (j == i) {
        expectedScatter.push(lib.rotate_point(d, angle_x, angle_y));
      } else {
        expectedScatter.push(d);
      }
  });

  plot(expectedScatter,
       expectedAxis,
       0);
}

function drag_end(){
  scatter = expectedScatter;
  axis = expectedAxis;
  startAngleX = 0;
  startAngleY = 0;
  startAngleZ = 0;
}

init();

return {
  init: function(){init();}
};

})();

<commit_msg>correct stretch 3d point dot_prod_correct<commit_after>var dot_product_correct = (function() {

var origin = [150, 140],
  scale = 60,
  scatter = [],
  axis = [],
  expectedAxis = [],
  beta = 0, alpha = 0,

  startAngleX = Math.PI/8 * 2.65,
  startAngleY = -Math.PI/8,
  startAngleZ = Math.PI/8 * 0.6;

let  axis_len = 2,
  unit = axis_len/10;

var svg = d3.select("#svg_dot_product_correct");

var lib = space_plot_lib(
  svg,
  origin,
  scale,
  is_2d=false)

svg = svg.call(d3.drag()
         .on('start', drag_start)
         .on('drag', dragged)
         .on('end', drag_end))
         .append('g');

axis = lib.init_float_axis(axis_len=axis_len, unit=unit);

function plot(scatter, axis, tt){

  var lines = [], points = [];

  lib.plot_lines(axis);

  scatter.forEach(function(d){
    lines.push(...lib.create_segments(d));
  })

  basis = {
      ex: axis[1/unit - 1 + axis_len/unit * 0][1],
      ey: axis[1/unit - 1 + axis_len/unit * 1][1],
      ez: axis[1/unit - 1 + axis_len/unit * 2][1],
  };

  let u = Object.assign({}, scatter[0]),
      v = Object.assign({}, scatter[1]);
  let v_norm = Math.sqrt(v.x*v.x + v.y*v.y + v.z*v.z);

  let v_ = lib.normalize(v);
  v_.r = 7;
  v_.opacity = 0.5;
  v_.centroid_z = -1000;
  v_.text = '|v| = 1.00';
  v_.text_opacity = 0.5;

  let uTv = lib.dot_product(u, v);
  let uTvv = {x: v_.x * uTv,
              y: v_.y * uTv,
              z: v_.z * uTv};

  let uTvv_line = [
      {x: 0, y: 0, z: 0},
      {x: uTvv.x, y: uTvv.y, z: uTvv.z}
  ]
  uTvv_line.color = 0;
  uTvv_line.centroid_z = 1000;
  uTvv_line.text = 'u\u1d40v';
  uTvv_line.text_color = 0;
  uTvv_line.font_size = 14;
  uTvv_line.text_opacity = 1.0;

  let uTv_ = lib.dot_product(u, v_);
  let uTvv_ = {x: v_.x * uTv_,
               y: v_.y * uTv_,
               z: v_.z * uTv_};

  let uTvv__line = [
      {x: 0, y: 0, z: 0},
      {x: uTvv_.x, y: uTvv_.y, z: uTvv_.z}
  ]
  uTvv__line.color = 0;
  uTvv__line.stroke_width = 5;
  uTvv__line.opacity = 0.5;

  lines.push(uTvv_line);
  lines.push(uTvv__line);
  lines.push(...lib.create_dash_segments(u, uTvv_));

  u.text = 'u';
  v.text = '|v| = ' + v_norm.toFixed(2);
  points = [u, v, v_];

  lib.plot_lines(lines, tt, 'arrow');
  lib.plot_points(points, tt,
                  drag_point_fn=dragged_point,
                  drag_start_fn=drag_start,
                  drag_end_fn=drag_end);
  lib.sort();
}

function init(){

  let u = {
      x: 0.8,
      y: 0.8,
      z: -0.8,
      color: 4
  },
      v = {
      x: 1/Math.sqrt(14),
      y: -2/Math.sqrt(14),
      z: 3/Math.sqrt(14),
      color: 2,
  };

  scatter = [u, v];

  expectedScatter = lib.rotate_points(
      scatter, startAngleX, startAngleY, startAngleZ);
  expectedAxis = lib.rotate_lines(
      axis, startAngleX, startAngleY, startAngleZ);
  plot(expectedScatter,
       expectedAxis,
       1000);
  drag_end();
}

function drag_start(){
  lib.drag_start();
}

function dragged(){
  [angle_x, angle_y] = lib.get_drag_angles();

  expectedScatter = lib.rotate_points(scatter, angle_x, angle_y);
  expectedAxis = lib.rotate_lines(axis, angle_x, angle_y);

  plot(expectedScatter,
       expectedAxis,
       0);
}

function dragged_point_only(){
  [angle_x, angle_y] = lib.get_drag_angles();

  expectedScatter = lib.rotate_points(scatter, angle_x, angle_y);

  plot(expectedScatter,
       expectedAxis,
       0);
}

function stretch_point(d, i){
  let d_2d = {x: d.x, y: d.y, z: 0.},
      d_2d_ = lib.normalize(d_2d),
      m = lib.mouse_to_point_position(),
      d_2d_Tm = lib.dot_product(d_2d_, m),
      r = d_2d_Tm / lib.norm(d_2d);

  let p = {
    x: d.x * r,
    y: d.y * r,
    z: d.z * r,
  }
  expectedScatter = [];
  scatter.forEach(function(d, j){
      if (j == i) {
        d.x = p.x;
        d.y = p.y;
        d.z = p.z;
      }
      expectedScatter.push(d);
  });

  plot(expectedScatter,
       expectedAxis,
       0);
}

function dragged_point(d, i){
  if (i == 1) {
    stretch_point(d, i);
    return;
  } else if (i == 2) {
    dragged_point_only();
    return;
  }
  [angle_x, angle_y] = lib.get_drag_angles();

  expectedScatter = [];
  scatter.forEach(function(d, j){
      if (j == i) {
        expectedScatter.push(lib.rotate_point(d, angle_x, angle_y));
      } else {
        expectedScatter.push(d);
      }
  });

  plot(expectedScatter,
       expectedAxis,
       0);
}

function drag_end(){
  scatter = expectedScatter;
  axis = expectedAxis;
  startAngleX = 0;
  startAngleY = 0;
  startAngleZ = 0;
}

init();

return {
  init: function(){init();}
};

})();

<|endoftext|>