<commit_before>/*
 *  FirebaseTransport.js
 *
 *  David Janes
 *  IOTDB.org
 *  2015-03-07
 *
 *  Copyright [2013-2015] [David P. Janes]
 *
 *  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.
 */

"use strict";

var iotdb = require('iotdb');
var _ = iotdb._;
var bunyan = iotdb.bunyan;

var firebase = require('firebase');

var util = require('util');
var url = require('url');

var logger = bunyan.createLogger({
    name: 'iotdb-transport-firebase',
    module: 'FirebaseTransport',
});

/* --- forward definitions --- */
var _encode;
var _decode;
var _unpack;
var _pack;
var _split;

/* --- constructor --- */

/**
 *  See {iotdb.transporter.Transport#Transport} for documentation.
 *
 *  @param {object} initd.firebase
 *  pass in a Firebase object (great for sharing connections)
 */
var FirebaseTransport = function (initd) {
    var self = this;

    self.initd = _.defaults(
        initd,
        iotdb.keystore().get("/transports/FirebaseTransport/initd"),
        {
            prefix: "/",
            host: null,
            firebase: null,
        }
    );

    self.initd.parts = _split(self.initd.prefix);

    if (self.initd.firebase) {
        self.native = self.initd.firebase;
    } else {
        self.native = new firebase(self.initd.host);
    }
};

FirebaseTransport.prototype = new iotdb.transporter.Transport();

/**
 *  See {iotdb.transporter.Transport#list} for documentation.
 *

 *  Note that this may not be memory efficient due
 *  to the way "value" works. This could be revisited
 *  in the future.
 */
FirebaseTransport.prototype.list = function (paramd, callback) {
    var self = this;

    if (arguments.length === 1) {
        paramd = {};
        callback = arguments[0];
    }

    self._validate_list(paramd, callback);

    var channel = self._channel();
    self.native
        .child(channel)
        .orderByKey()
        .on("value", function (parent_snapshot) {
            parent_snapshot.forEach(function (snapshot) {
                return callback({
                    id: _decode(snapshot.key()),
                });
            });
            callback({
                end: true
            });
        });
};

/**
 *  See {iotdb.transporter.Transport#added} for documentation.
 *

 *  NOT FINISHED
 */
FirebaseTransport.prototype.added = function (paramd, callback) {
    var self = this;

    if (arguments.length === 1) {
        paramd = {};
        callback = arguments[0];
    }

    self._validate_added(paramd, callback);
};

/**
 *  See {iotdb.transporter.Transport#about} for documentation.
 */
FirebaseTransport.prototype.about = function (paramd, callback) {
    var self = this;

    self._validate_about(paramd, callback);

    var channel = self._channel(paramd.id);
    self.native.child(channel).once("value", function (snapshot) {
        var keys = _.keys(snapshot.val());
        keys = _.map(keys, _decode);

        callback({
            id: paramd.id,
            bands: keys,
        });
    });
};

/**
 *  See {iotdb.transporter.Transport#get} for documentation.
 */
FirebaseTransport.prototype.get = function (paramd, callback) {
    var self = this;

    self._validate_get(paramd, callback);

    var channel = self._channel(paramd.id, paramd.band);
    self.native.child(channel).once("value", function (snapshot) {
        callback({
            id: paramd.id,
            band: paramd.band,
            value: _unpack(snapshot.val()),
        });
    });
};

/**
 *  See {iotdb.transporter.Transport#update} for documentation.
 */
FirebaseTransport.prototype.update = function (paramd, callback) {
    var self = this;

    self._validate_update(paramd, callback);

    var channel = self._channel(paramd.id, paramd.band);
    var d;
    if (self.initd.add_timestamp) {
        d = _pack(_.d.add_timestamp(paramd.value));
    } else {
        d = _pack(paramd.value);
    }

    self.native.child(channel).set(d);

    if (callback !== undefined) {
        callback({
            id: paramd.id,
            band: paramd.band,
            value: paramd.value,
        });
    }
};

/**
 *  See {iotdb.transporter.Transport#updated} for documentation.
 */
FirebaseTransport.prototype.updated = function (paramd, callback) {
    var self = this;

    if (arguments.length === 1) {
        paramd = {};
        callback = arguments[0];
    }

    self._validate_updated(paramd, callback);

    var channel = self._channel(paramd.id, paramd.band);
    self.native.child(channel).on("child_changed", function (snapshot, name) {
        var snapshot_url = snapshot.ref().toString();
        var snapshot_path = url.parse(snapshot_url).path;
        var snapshot_parts = _split(snapshot_path);
        for (var i in snapshot_parts) {
            snapshot_parts[i] = _decode(snapshot_parts[i]); // once for Firebase
            snapshot_parts[i] = _decode(snapshot_parts[i]); // once for IOTDB's encoding
        }
        var snapshot_id;
        var snapshot_band;
        var snapshot_value;

        var parts = self.initd.parts;
        var diff = snapshot_parts.length - parts.length;
        if (diff > 2) {
            snapshot_id = (snapshot_parts[parts.length]);
            snapshot_band = (snapshot_parts[parts.length + 1]);
            snapshot_value = undefined;
            callback({
                id: snapshot_id,
                band: snapshot_band,
                value: snapshot_value,
            });
        } else if (diff === 2) {
            snapshot_id = (snapshot_parts[parts.length]);
            snapshot_band = (snapshot_parts[parts.length + 1]);
            snapshot_value = _unpack(snapshot.val());
            callback({
                id: snapshot_id,
                band: snapshot_band,
                value: snapshot_value,
            });
        } else if (diff === 1) {
            snapshot_id = (snapshot_parts[parts.length]);
            var d = _unpack(snapshot.val());
            for (snapshot_band in d) {
                snapshot_value = d[snapshot_band];
                callback({
                    id: snapshot_id,
                    band: snapshot_band,
                    value: snapshot_value,
                });
            }
        } else {
            /* ignoring massive udpates */
        }
    });
};

/**
 *  See {iotdb.transporter.Transport#remove} for documentation.
 */
FirebaseTransport.prototype.remove = function (paramd, callback) {
    var self = this;

    self._validate_remove(paramd, callback);

    var channel = self._channel(paramd.id);
    self.native.child(channel).remove();
};

/* --- internals --- */
FirebaseTransport.prototype._channel = function (id, band) {
    var self = this;

    var parts = _.deepCopy(self.initd.parts);
    if (id) {
        parts.push(_encode(id));

        if (band) {
            parts.push(_encode(band));
        }
    }

    return parts.join("/");
};

var _encode = function (s) {
    return s.replace(/[\/$%#.\]\[]/g, function (c) {
        return '%' + c.charCodeAt(0).toString(16);
    });
};

var _decode = function (s) {
    return decodeURIComponent(s);
};

var _unpack = function (d) {
    return _.d.transform(d, {
        pre: _.ld_compact,
        key: _decode,
    });
};

var _pack = function (d) {
    return _.d.transform(d, {
        pre: _.ld_compact,
        key: _encode,
    });
};

var _split = function (path) {
    var nparts = [];
    var oparts = path.split("/");

    for (var pi in oparts) {
        var part = oparts[pi];
        if (part.length > 0) {
            nparts.push(part);
        }
    }

    return nparts;
};

/**
 *  API
 */
exports.FirebaseTransport = FirebaseTransport;
<commit_msg>iOS app<commit_after>/*
 *  FirebaseTransport.js
 *
 *  David Janes
 *  IOTDB.org
 *  2015-03-07
 *
 *  Copyright [2013-2015] [David P. Janes]
 *
 *  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.
 */

"use strict";

var iotdb = require('iotdb');
var _ = iotdb._;
var bunyan = iotdb.bunyan;

var firebase = require('firebase');

var util = require('util');
var url = require('url');

var logger = bunyan.createLogger({
    name: 'iotdb-transport-firebase',
    module: 'FirebaseTransport',
});

/* --- forward definitions --- */
var _encode;
var _decode;
var _unpack;
var _pack;
var _split;

/* --- constructor --- */

/**
 *  See {iotdb.transporter.Transport#Transport} for documentation.
 *
 *  @param {object} initd.firebase
 *  pass in a Firebase object (great for sharing connections)
 */
var FirebaseTransport = function (initd) {
    var self = this;

    self.initd = _.defaults(
        initd,
        iotdb.keystore().get("/transports/FirebaseTransport/initd"),
        {
            prefix: "/",
            host: null,
            firebase: null,
        }
    );

    self.initd.parts = _split(self.initd.prefix);

    if (self.initd.firebase) {
        self.native = self.initd.firebase;
    } else {
        self.native = new firebase(self.initd.host);
    }
};

FirebaseTransport.prototype = new iotdb.transporter.Transport();

/**
 *  See {iotdb.transporter.Transport#list} for documentation.
 *

 *  Note that this may not be memory efficient due
 *  to the way "value" works. This could be revisited
 *  in the future.
 */
FirebaseTransport.prototype.list = function (paramd, callback) {
    var self = this;

    if (arguments.length === 1) {
        paramd = {};
        callback = arguments[0];
    }

    self._validate_list(paramd, callback);

    var channel = self._channel();
    self.native
        .child(channel)
        .orderByKey()
        .on("value", function (parent_snapshot) {
            parent_snapshot.forEach(function (snapshot) {
                return callback({
                    id: _decode(snapshot.key()),
                });
            });
            callback({
                end: true
            });
        });
};

/**
 *  See {iotdb.transporter.Transport#added} for documentation.
 *

 *  NOT FINISHED
 */
FirebaseTransport.prototype.added = function (paramd, callback) {
    var self = this;

    if (arguments.length === 1) {
        paramd = {};
        callback = arguments[0];
    }

    self._validate_added(paramd, callback);
};

/**
 *  See {iotdb.transporter.Transport#about} for documentation.
 */
FirebaseTransport.prototype.about = function (paramd, callback) {
    var self = this;

    self._validate_about(paramd, callback);

    var channel = self._channel(paramd.id);
    self.native.child(channel).once("value", function (snapshot) {
        var keys = _.keys(snapshot.val());
        keys = _.map(keys, _decode);

        callback({
            id: paramd.id,
            bands: keys,
        });
    });
};

/**
 *  See {iotdb.transporter.Transport#get} for documentation.
 */
FirebaseTransport.prototype.get = function (paramd, callback) {
    var self = this;

    self._validate_get(paramd, callback);

    var channel = self._channel(paramd.id, paramd.band);
    self.native.child(channel).once("value", function (snapshot) {
        callback({
            id: paramd.id,
            band: paramd.band,
            value: _unpack(snapshot.val()),
        });
    });
};

/**
 *  See {iotdb.transporter.Transport#update} for documentation.
 */
FirebaseTransport.prototype.update = function (paramd, callback) {
    var self = this;

    self._validate_update(paramd, callback);

    var channel = self._channel(paramd.id, paramd.band);
    var d;
    if (self.initd.add_timestamp) {
        d = _pack(_.timestamp.add(paramd.value));
    } else {
        d = _pack(paramd.value);
    }

    self.native.child(channel).set(d);

    if (callback !== undefined) {
        callback({
            id: paramd.id,
            band: paramd.band,
            value: paramd.value,
        });
    }
};

/**
 *  See {iotdb.transporter.Transport#updated} for documentation.
 */
FirebaseTransport.prototype.updated = function (paramd, callback) {
    var self = this;

    if (arguments.length === 1) {
        paramd = {};
        callback = arguments[0];
    }

    self._validate_updated(paramd, callback);

    var channel = self._channel(paramd.id, paramd.band);
    self.native.child(channel).on("child_changed", function (snapshot, name) {
        var snapshot_url = snapshot.ref().toString();
        var snapshot_path = url.parse(snapshot_url).path;
        var snapshot_parts = _split(snapshot_path);
        for (var i in snapshot_parts) {
            snapshot_parts[i] = _decode(snapshot_parts[i]); // once for Firebase
            snapshot_parts[i] = _decode(snapshot_parts[i]); // once for IOTDB's encoding
        }
        var snapshot_id;
        var snapshot_band;
        var snapshot_value;

        var parts = self.initd.parts;
        var diff = snapshot_parts.length - parts.length;
        if (diff > 2) {
            snapshot_id = (snapshot_parts[parts.length]);
            snapshot_band = (snapshot_parts[parts.length + 1]);
            snapshot_value = undefined;
            callback({
                id: snapshot_id,
                band: snapshot_band,
                value: snapshot_value,
            });
        } else if (diff === 2) {
            snapshot_id = (snapshot_parts[parts.length]);
            snapshot_band = (snapshot_parts[parts.length + 1]);
            snapshot_value = _unpack(snapshot.val());
            callback({
                id: snapshot_id,
                band: snapshot_band,
                value: snapshot_value,
            });
        } else if (diff === 1) {
            snapshot_id = (snapshot_parts[parts.length]);
            var d = _unpack(snapshot.val());
            for (snapshot_band in d) {
                snapshot_value = d[snapshot_band];
                callback({
                    id: snapshot_id,
                    band: snapshot_band,
                    value: snapshot_value,
                });
            }
        } else {
            /* ignoring massive udpates */
        }
    });
};

/**
 *  See {iotdb.transporter.Transport#remove} for documentation.
 */
FirebaseTransport.prototype.remove = function (paramd, callback) {
    var self = this;

    self._validate_remove(paramd, callback);

    var channel = self._channel(paramd.id);
    self.native.child(channel).remove();
};

/* --- internals --- */
FirebaseTransport.prototype._channel = function (id, band) {
    var self = this;

    var parts = _.deepCopy(self.initd.parts);
    if (id) {
        parts.push(_encode(id));

        if (band) {
            parts.push(_encode(band));
        }
    }

    return parts.join("/");
};

var _encode = function (s) {
    return s.replace(/[\/$%#.\]\[]/g, function (c) {
        return '%' + c.charCodeAt(0).toString(16);
    });
};

var _decode = function (s) {
    return decodeURIComponent(s);
};

var _unpack = function (d) {
    return _.d.transform(d, {
        pre: _.ld_compact,
        key: _decode,
    });
};

var _pack = function (d) {
    return _.d.transform(d, {
        pre: _.ld_compact,
        key: _encode,
    });
};

var _split = function (path) {
    var nparts = [];
    var oparts = path.split("/");

    for (var pi in oparts) {
        var part = oparts[pi];
        if (part.length > 0) {
            nparts.push(part);
        }
    }

    return nparts;
};

/**
 *  API
 */
exports.FirebaseTransport = FirebaseTransport;
<|endoftext|>


<commit_before>/*
Rabbitmq wrapper for promise based connection
Test
 */
const amqp = require('amqplib/callback_api');
let exchange = '';
let exchangeFanout = '';
let channel;
let connection;

/*const connect = (config) => {
    return new Promise(function (resolve, reject) {
        try {
            exchange = config.exchange;
            exchangeFanout = config.exchange + ".fanout";
            amqp.connect(config.url, function (err, conn) {
                connection = conn;
                if (err) {
                    console.error("[AMQP]", err);
                    reject(err);
                }
                console.log("[AMQP] connected");
                conn.createConfirmChannel(function (err, ch) {
                    console.log("Connected to rabbit");
                    channel = ch;
                    channel.assertExchange(exchange, 'direct', {durable: true});
                    channel.assertExchange(exchangeFanout, 'fanout', {durable: true});
                    resolve(conn);
                });
            });
        } catch (e) {
            reject(e.message);
            console.error("[AMQP] connect", e.message);
        }
    });
};*/
function connect(config,cb)
{

    exchange = config.exchange;
    exchangeFanout = config.exchange+".fanout";
    amqp.connect(config.url, function (err, conn) {
        connection = conn;
        if (err) {
            console.error("[AMQP]", err);
            return setTimeout(connect.bind(this,config,cb), 1000);
        }
        conn.on("error", function(err) {
            if (err.message !== "Connection closing") {
                console.error("[AMQP] conn error", err);
                return setTimeout(connect.bind(this,config,cb), 1000);
            }
        });
        conn.on("close", function(err) {
            if (err.message !== "Connection closing") {
                console.error("[AMQP] conn error", err);
                return setTimeout(connect.bind(this,config,cb), 1000);
            }
        });

        console.log("[AMQP] connected");
        conn.createConfirmChannel(function (err, ch) {
            console.log("Connected to rabbit");
            channel = ch;
            channel.assertExchange(exchange, 'direct', {durable: true});
            channel.assertExchange(exchangeFanout, 'fanout', {durable: true});
            if(cb)
                cb(ch);

        });

    });
}

const publish = (msg,key) => {
    return new Promise(function(resolve, reject) {
        try {

            channel.publish(exchange, key, new Buffer(msg), {persistent: true}, function (err, ok) {
                    if (err !== null) {
                        reject(err);
                        console.warn(' [*] Message nacked');
                    } else {
                        console.log(' [*] Message acked');
                        resolve("Message sendt");
                    }
                }
            );
        } catch (e) {
            reject(e.message);
            console.error("[AMQP] publish", e.message);
        }
    });
};
const fanout = (sendMsg,key) => {
    return new Promise(function(resolve, reject) {
        try {
            if (typeof sendMsg !== 'string') {
                sendMsg = JSON.stringify(sendMsg);
            }
            channel.publish(exchangeFanout, key, new Buffer(sendMsg), {persistent: true}, function (err, ok) {
                    if (err !== null) {
                        reject(err);
                        console.warn(' [*] Message nacked');
                    } else {
                        console.log(' [*] Message acked');
                        resolve("Message sendt");
                    }
                }
            );
        } catch (e) {
            reject(e.message);
            console.error("[AMQP] publish", e.message);
        }
    });
};

const RPC = (queue,service,sendMsg) =>{
    return new Promise(function(resolve, reject) {
        try {
            connection.createChannel((err, ch) => {
                ch.assertQueue('', {exclusive: true,autoDelete:true}, (err, q) => {
                    const corr = generateUuid();
                    ch.consume(q.queue, (msg) => {
                        if (msg.properties.correlationId === corr) {
                            resolve(msg.content.toString());
                            ch.close();
                        }
                    }, {noAck: true});

                    if (typeof sendMsg !== 'string') {
                        sendMsg = JSON.stringify(sendMsg);
                    }
                    ch.sendToQueue("RPC." + queue,
                        new Buffer(sendMsg),
                        {correlationId: corr, replyTo: q.queue, type: service}
                    );
                });
            })
        } catch(e) {
            console.error(e);
            reject(e.message);
        }
    });
};
const generateUuid = () => {
    return Math.random().toString() +
        Math.random().toString() +
        Math.random().toString();
};

function RPCListen(queue,cb, ...args) {
    const q = "RPC." + queue;
    channel.assertQueue(q, {durable: false});
    channel.prefetch(1);
    console.log(' [x] Awaiting RPC requests on queue:' + q);
    channel.consume(q, (msg) => {
        (function(msg){
            new Promise((resolve, reject) => {
                let services = cb();
                if (services[msg.properties.type] === undefined) {
                    channel.sendToQueue(msg.properties.replyTo,
                        new Buffer("Unknown service"),
                        {correlationId: msg.properties.correlationId});
                    channel.ack(msg);
                }
                else {
                    services[msg.properties.type](msg.content.toString(), resolve, args);
                }
            }).then((sendMsg) => {
                if (typeof sendMsg !== 'string') {
                    sendMsg = JSON.stringify(sendMsg);
                }

                channel.sendToQueue(msg.properties.replyTo,
                    new Buffer(sendMsg),
                    {correlationId: msg.properties.correlationId});
                channel.ack(msg);
            }).catch((msg) => {
                console.error(msg);
            });
        }(msg))
    });
}
function listen(queue,key,cb){
    channel.assertQueue(queue, {durable:true},function(err, q) {
        console.log(' [*] Waiting for data on'+q.queue);
        channel.bindQueue(q.queue, exchange, key);
        //  channel.bindQueue(q.queue, exchangeFanout, key);
        //Fetch 5 messages in a time and wait for ack on those
        channel.prefetch(5);
        channel.consume(q.queue, function(msg) {
            cb(function(channel,msg) {channel.ack(msg);}.bind(this,channel,msg),msg.content.toString());
        }, {noAck: false});
    });
}
function listenFanout(queue,key,cb){
    channel.assertQueue(queue, {durable:true},function(err, q) {
        console.log(' [*] Waiting for data on'+q.queue);

        channel.bindQueue(q.queue, exchangeFanout, key);
        //Fetch 5 messages in a time and wait for ack on those
        channel.prefetch(5);
        channel.consume(q.queue, function(msg) {
            cb(() => {channel.ack(msg)},msg.content.toString());
        }, {noAck: false});
    });
}

const use = (queue,services, ...params) => {
    const q = "RPC." + queue;
    channel.assertQueue(q, {durable: false});
    channel.prefetch(1);
    console.log(' [x] Awaiting RPC requests on queue:' + q);
    channel.consume(q, (msg) => {
        (function(msg){
            if (services[msg.properties.type] === undefined) {
                channel.sendToQueue(msg.properties.replyTo,
                    new Buffer("Unknown service"),
                    {correlationId: msg.properties.correlationId});
            }
            else {

                Promise.resolve(services[msg.properties.type].resolve(msg.content.toString(),...params))
                    .then((sendMsg) => {
                        if (typeof sendMsg !== 'string') {
                            sendMsg = JSON.stringify(sendMsg);
                        }
                        channel.sendToQueue(msg.properties.replyTo,
                            new Buffer(sendMsg),
                            {correlationId: msg.properties.correlationId});
                    })
                    .catch((err) => console.error(err));
            }
        }(msg))
        channel.ack(msg);
    });
};

/*test:

 var result = await rpc(microservice, service, |schema, externalSystemAPI, args);*/

module.exports = {
    connect:connect,
    publish:publish,
    listen:listen,
    RPCListen:RPCListen,
    RPC:RPC,
    fanout:fanout,
    listenFanout,listenFanout,
    disconnect: (cb) => {
        if(connection) {
            connection.close(() => {
                cb();
            })
        } else {cb();}},
    use:use
};<commit_msg>Promisified connect<commit_after>/*
Rabbitmq wrapper for promise based connection
Test
 */
const amqp = require('amqplib/callback_api');
let exchange = '';
let exchangeFanout = '';
let channel;
let connection;

const connect = (config) => {
    return new Promise(function (resolve, reject) {
        try {
            exchange = config.exchange;
            exchangeFanout = config.exchange + ".fanout";
            amqp.connect(config.url, function (err, conn) {
                connection = conn;
                if (err) {
                    console.error("[AMQP]", err);
                    reject(err);
                }
                console.log("[AMQP] connected");
                conn.createConfirmChannel(function (err, ch) {
                    console.log("Connected to rabbit");
                    channel = ch;
                    channel.assertExchange(exchange, 'direct', {durable: true});
                    channel.assertExchange(exchangeFanout, 'fanout', {durable: true});
                    resolve(conn);
                });
            });
        } catch (e) {
            reject(e.message);
            console.error("[AMQP] connect", e.message);
        }
    });
};
/*function connect(config,cb)
{

    exchange = config.exchange;
    exchangeFanout = config.exchange+".fanout";
    amqp.connect(config.url, function (err, conn) {
        connection = conn;
        if (err) {
            console.error("[AMQP]", err);
            return setTimeout(connect.bind(this,config,cb), 1000);
        }
        conn.on("error", function(err) {
            if (err.message !== "Connection closing") {
                console.error("[AMQP] conn error", err);
                return setTimeout(connect.bind(this,config,cb), 1000);
            }
        });
        conn.on("close", function(err) {
            if (err.message !== "Connection closing") {
                console.error("[AMQP] conn error", err);
                return setTimeout(connect.bind(this,config,cb), 1000);
            }
        });

        console.log("[AMQP] connected");
        conn.createConfirmChannel(function (err, ch) {
            console.log("Connected to rabbit");
            channel = ch;
            channel.assertExchange(exchange, 'direct', {durable: true});
            channel.assertExchange(exchangeFanout, 'fanout', {durable: true});
            if(cb)
                cb(ch);

        });

    });
}*/

const publish = (msg,key) => {
    return new Promise(function(resolve, reject) {
        try {

            channel.publish(exchange, key, new Buffer(msg), {persistent: true}, function (err, ok) {
                    if (err !== null) {
                        reject(err);
                        console.warn(' [*] Message nacked');
                    } else {
                        console.log(' [*] Message acked');
                        resolve("Message sendt");
                    }
                }
            );
        } catch (e) {
            reject(e.message);
            console.error("[AMQP] publish", e.message);
        }
    });
};
const fanout = (sendMsg,key) => {
    return new Promise(function(resolve, reject) {
        try {
            if (typeof sendMsg !== 'string') {
                sendMsg = JSON.stringify(sendMsg);
            }
            channel.publish(exchangeFanout, key, new Buffer(sendMsg), {persistent: true}, function (err, ok) {
                    if (err !== null) {
                        reject(err);
                        console.warn(' [*] Message nacked');
                    } else {
                        console.log(' [*] Message acked');
                        resolve("Message sendt");
                    }
                }
            );
        } catch (e) {
            reject(e.message);
            console.error("[AMQP] publish", e.message);
        }
    });
};

const RPC = (queue,service,sendMsg) =>{
    return new Promise(function(resolve, reject) {
        try {
            connection.createChannel((err, ch) => {
                ch.assertQueue('', {exclusive: true,autoDelete:true}, (err, q) => {
                    const corr = generateUuid();
                    ch.consume(q.queue, (msg) => {
                        if (msg.properties.correlationId === corr) {
                            resolve(msg.content.toString());
                            ch.close();
                        }
                    }, {noAck: true});

                    if (typeof sendMsg !== 'string') {
                        sendMsg = JSON.stringify(sendMsg);
                    }
                    ch.sendToQueue("RPC." + queue,
                        new Buffer(sendMsg),
                        {correlationId: corr, replyTo: q.queue, type: service}
                    );
                });
            })
        } catch(e) {
            console.error(e);
            reject(e.message);
        }
    });
};
const generateUuid = () => {
    return Math.random().toString() +
        Math.random().toString() +
        Math.random().toString();
};

function RPCListen(queue,cb, ...args) {
    const q = "RPC." + queue;
    channel.assertQueue(q, {durable: false});
    channel.prefetch(1);
    console.log(' [x] Awaiting RPC requests on queue:' + q);
    channel.consume(q, (msg) => {
        (function(msg){
            new Promise((resolve, reject) => {
                let services = cb();
                if (services[msg.properties.type] === undefined) {
                    channel.sendToQueue(msg.properties.replyTo,
                        new Buffer("Unknown service"),
                        {correlationId: msg.properties.correlationId});
                    channel.ack(msg);
                }
                else {
                    services[msg.properties.type](msg.content.toString(), resolve, args);
                }
            }).then((sendMsg) => {
                if (typeof sendMsg !== 'string') {
                    sendMsg = JSON.stringify(sendMsg);
                }

                channel.sendToQueue(msg.properties.replyTo,
                    new Buffer(sendMsg),
                    {correlationId: msg.properties.correlationId});
                channel.ack(msg);
            }).catch((msg) => {
                console.error(msg);
            });
        }(msg))
    });
}
function listen(queue,key,cb){
    channel.assertQueue(queue, {durable:true},function(err, q) {
        console.log(' [*] Waiting for data on'+q.queue);
        channel.bindQueue(q.queue, exchange, key);
        //  channel.bindQueue(q.queue, exchangeFanout, key);
        //Fetch 5 messages in a time and wait for ack on those
        channel.prefetch(5);
        channel.consume(q.queue, function(msg) {
            cb(function(channel,msg) {channel.ack(msg);}.bind(this,channel,msg),msg.content.toString());
        }, {noAck: false});
    });
}
function listenFanout(queue,key,cb){
    channel.assertQueue(queue, {durable:true},function(err, q) {
        console.log(' [*] Waiting for data on'+q.queue);

        channel.bindQueue(q.queue, exchangeFanout, key);
        //Fetch 5 messages in a time and wait for ack on those
        channel.prefetch(5);
        channel.consume(q.queue, function(msg) {
            cb(() => {channel.ack(msg)},msg.content.toString());
        }, {noAck: false});
    });
}

const use = (queue,services, ...params) => {
    const q = "RPC." + queue;
    channel.assertQueue(q, {durable: false});
    channel.prefetch(1);
    console.log(' [x] Awaiting RPC requests on queue:' + q);
    channel.consume(q, (msg) => {
        (function(msg){
            if (services[msg.properties.type] === undefined) {
                channel.sendToQueue(msg.properties.replyTo,
                    new Buffer("Unknown service"),
                    {correlationId: msg.properties.correlationId});
            }
            else {

                Promise.resolve(services[msg.properties.type].resolve(msg.content.toString(),...params))
                    .then((sendMsg) => {
                        if (typeof sendMsg !== 'string') {
                            sendMsg = JSON.stringify(sendMsg);
                        }
                        channel.sendToQueue(msg.properties.replyTo,
                            new Buffer(sendMsg),
                            {correlationId: msg.properties.correlationId});
                    })
                    .catch((err) => console.error(err));
            }
        }(msg))
        channel.ack(msg);
    });
};

/*test:

 var result = await rpc(microservice, service, |schema, externalSystemAPI, args);*/

module.exports = {
    connect:connect,
    publish:publish,
    listen:listen,
    RPCListen:RPCListen,
    RPC:RPC,
    fanout:fanout,
    listenFanout,listenFanout,
    disconnect: (cb) => {
        if(connection) {
            connection.close(() => {
                cb();
            })
        } else {cb();}},
    use:use
};<|endoftext|>


<commit_before>/*!
 * Copyright 2014 Apereo Foundation (AF) Licensed under the
 * Educational Community 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://opensource.org/licenses/ECL-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.
 */

/**
 * Bootstrap plugin that takes care of focusing the element that was clicked to launch the modal
 */

define(['jquery', 'bootstrap'], function($) {

    // Element that had focus when the modal was invoked
    var $focusedEl = null;

    // When the modal is shown, we store the focused element
    $('body').on('show.bs.modal', function() {
        $focusedEl = $(':focus');
    });

    // When the modal is hidden, we need to re-focus the modal trigger
    $('body').on('hidden.bs.modal', function() {
        if ($focusedEl) {
            $focusedEl.focus();
        }
    });

    /*!
     * Work-around Safari iOS 7 bug where Safari does not update the position of fixed elements when the
     * keyboard or other tool bars are displayed. This work-around sets the backdrop to the full height
     * of the page to ensure the keyboard does not expose the page behind the modal backdrop.
     *
     * https://github.com/twbs/bootstrap/issues/9023
     */
    if (navigator.userAgent.match(/iPhone|iPad|iPod/i)) {
        $('body').on('show.bs.modal', function() {

            // Position modal absolute and bump it down to the scrollPosition
            $(this)
                .css({
                    position: 'absolute',
                    marginTop: $(window).scrollTop() + 'px',
                    bottom: 'auto'
                });

            // Position backdrop absolute and make it span the entire page
            //
            // Also dirty, but we need to tap into the backdrop after Boostrap
            // positions it but before transitions finish.
            //
            setTimeout(function() {

                // Find the full height of the page
                var maxHeight = Math.max(
                    document.body.scrollHeight, document.documentElement.scrollHeight,
                    document.body.offsetHeight, document.documentElement.offsetHeight,
                    document.body.clientHeight, document.documentElement.clientHeight
                );

                // Resize the backdrop to be the full height of the page
                $('.modal-backdrop').css({
                    position: 'absolute',
                    top: 0,
                    left: 0,
                    width: '100%',
                    height: maxHeight + 'px'
                });
            }, 0);
        });
    }
});
<commit_msg>(Issue 3402) Remove body absolute positioning CSS<commit_after>/*!
 * Copyright 2014 Apereo Foundation (AF) Licensed under the
 * Educational Community 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://opensource.org/licenses/ECL-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.
 */

/**
 * Bootstrap plugin that takes care of focusing the element that was clicked to launch the modal
 */

define(['jquery', 'bootstrap'], function($) {

    // Element that had focus when the modal was invoked
    var $focusedEl = null;

    // When the modal is shown, we store the focused element
    $('body').on('show.bs.modal', function() {
        $focusedEl = $(':focus');
    });

    // When the modal is hidden, we need to re-focus the modal trigger
    $('body').on('hidden.bs.modal', function() {
        if ($focusedEl) {
            $focusedEl.focus();
        }
    });

    /*!
     * Work-around Safari iOS 7 bug where Safari does not update the position of fixed elements when the
     * keyboard or other tool bars are displayed. This work-around sets the backdrop to the full height
     * of the page to ensure the keyboard does not expose the page behind the modal backdrop.
     *
     * https://github.com/twbs/bootstrap/issues/9023
     */
    if (navigator.userAgent.match(/iPhone|iPad|iPod/i)) {
        $('body').on('show.bs.modal', function() {

            // Position backdrop absolute and make it span the entire page
            //
            // Also dirty, but we need to tap into the backdrop after Boostrap
            // positions it but before transitions finish.
            //
            setTimeout(function() {

                // Find the full height of the page
                var maxHeight = Math.max(
                    document.body.scrollHeight, document.documentElement.scrollHeight,
                    document.body.offsetHeight, document.documentElement.offsetHeight,
                    document.body.clientHeight, document.documentElement.clientHeight
                );

                // Resize the backdrop to be the full height of the page
                $('.modal-backdrop').css({
                    'position': 'absolute',
                    'top': 0,
                    'left': 0,
                    'width': '100%',
                    'height': maxHeight + 'px'
                });
            }, 0);
        });
    }
});
<|endoftext|>


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

  angular.module('app.components')
    .directive('headerNav', HeaderNavDirective);

  /** @ngInject */
  function HeaderNavDirective() {
    var directive = {
      restrict: 'AE',
      replace: true,
      scope: {},
      link: link,
      templateUrl: 'app/components/navigation/header-nav.html',
      controller: HeaderNavController,
      controllerAs: 'vm',
      bindToController: true
    };

    return directive;

    function link(scope, element, attrs, vm, transclude) {
      vm.activate();
    }

    /** @ngInject */
    function HeaderNavController(Navigation, Messages) {
      var vm = this;

      vm.activate = activate;
      vm.toggleNavigation = toggleNavigation;
      vm.clearMessages = clearMessages;

      function activate() {
        vm.messages = Messages.items;
      }

      function toggleNavigation() {
        if (!Navigation.state.isMobileNav) {
            Navigation.state.isCollapsed = !Navigation.state.isCollapsed;
            Navigation.state.forceCollapse = true;
          } else {
            Navigation.state.showMobileNav = !Navigation.state.showMobileNav;
          }
      }

      function clearMessages() {
        Messages.clear();
      }
    }
  }
})();
<commit_msg>styling updated<commit_after>(function() {
  'use strict';

  angular.module('app.components')
    .directive('headerNav', HeaderNavDirective);

  /** @ngInject */
  function HeaderNavDirective() {
    var directive = {
      restrict: 'AE',
      replace: true,
      scope: {},
      link: link,
      templateUrl: 'app/components/navigation/header-nav.html',
      controller: HeaderNavController,
      controllerAs: 'vm',
      bindToController: true
    };

    return directive;

    function link(scope, element, attrs, vm, transclude) {
      vm.activate();
    }

    /** @ngInject */
    function HeaderNavController(Navigation, Messages) {
      var vm = this;

      vm.activate = activate;
      vm.toggleNavigation = toggleNavigation;
      vm.clearMessages = clearMessages;

      function activate() {
        vm.messages = Messages.items;
      }

      function toggleNavigation() {
        if (!Navigation.state.isMobileNav) {
          Navigation.state.isCollapsed = !Navigation.state.isCollapsed;
          Navigation.state.forceCollapse = true;
        } else {
          Navigation.state.showMobileNav = !Navigation.state.showMobileNav;
        }
      }

      function clearMessages() {
        Messages.clear();
      }
    }
  }
})();
<|endoftext|>


<commit_before>'use strict'
const Telegraf = require('telegraf');
const webhook = require('./webhook.js');

const commandStatus = require('./commands/status.js');
const commandBenachrichtigung = require('./commands/benachrichtigung.js');

const middlewareAuthentication = require('./middlewares/authentication.js');
const middlewareHelpMessage = require('./middlewares/helpMessage.js');

module.exports = function () {
  const app = this; // eslint-disable-line no-unused-vars
  app.telegraf = new Telegraf(app.get('bot-token'))
  app.telegraf.startWebhook(app.get('bot-webhook'))

  app.configure(middlewareAuthentication)//always has to be first
  app.configure(webhook);
  app.configure(commandStatus);
  app.configure(commandBenachrichtigung);
  app.configure(middlewareHelpMessage)//always has to be last
  app.telegraf.startPolling();
};
<commit_msg>fix telegram webhook<commit_after>'use strict'
const Telegraf = require('telegraf');
const webhook = require('./webhook.js');

const commandStatus = require('./commands/status.js');
const commandBenachrichtigung = require('./commands/benachrichtigung.js');

const middlewareAuthentication = require('./middlewares/authentication.js');
const middlewareHelpMessage = require('./middlewares/helpMessage.js');

module.exports = function () {
  const app = this; // eslint-disable-line no-unused-vars
  app.telegraf = new Telegraf(app.get('bot-token'))

  app.telegraf.telegram.setWebhook(app.get(`bot-webhook`));
  app.use(app.telegraf.webhookCallback(app.get('bot-webhook')));

  app.configure(middlewareAuthentication)//always has to be first
  app.configure(webhook);
  app.configure(commandStatus);
  app.configure(commandBenachrichtigung);
  app.configure(middlewareHelpMessage)//always has to be last
  app.telegraf.startPolling();
};
<|endoftext|>


<commit_before>import svgCfg               from './cfg/svgCfg';
import addAttributes        from './addAttributes';
import extendUnitlessNumber from './extendUnitlessNumber';
import AttributeOps         from './AttributeOps';

export default {
    addAttributes,
    extendUnitlessNumber,
    AttributeOps,
    createElement: (tag, xmlns, is, parent) => {

            let element, namespace;

            if ( xmlns ) {

                if (is) {
                    element = document.createElementNS("http://www.w3.org/2000/svg", tag, is);
                } else {
                    element = document.createElementNS("http://www.w3.org/2000/svg", tag);
                }

			} if (svgCfg[tag]) { // xmlns, is...
                if (is) {
                    element = document.createElementNS("http://www.w3.org/2000/svg", tag, is);
                } else {
                    element = document.createElementNS("http://www.w3.org/2000/svg", tag);
                }
            } else if ( tag === 'math') {
				element = document.createElementNS('http://www.w3.org/1998/Math/MathML', tag);
			} else {
                if (is) {
                    element = document.createElement(tag, is);
                } else {
                    element = document.createElement(tag);
                }
            }

            return element;

        },
        createTextNode: text => document.createTextNode(text),
        createEmptyText: () => document.createTextNode('')
};<commit_msg>xmlns now works<commit_after>import svgCfg               from './cfg/svgCfg';
import addAttributes        from './addAttributes';
import extendUnitlessNumber from './extendUnitlessNumber';
import AttributeOps         from './AttributeOps';

export default {
    addAttributes,
    extendUnitlessNumber,
    AttributeOps,
    createElement: (tag, xmlns, is, parent) => {

            let element, namespace;

            if ( xmlns ) {
                element = document.createElementNS("http://www.w3.org/2000/svg", tag, is);
			} if (svgCfg[tag]) {
               element = document.createElementNS("http://www.w3.org/2000/svg", tag, is);
            } else if ( tag === 'math') {
				element = document.createElementNS('http://www.w3.org/1998/Math/MathML', tag);
			} else {
                    element = document.createElement(tag);
            }

            return element;

        },
        createTextNode: text => document.createTextNode(text),
        createEmptyText: () => document.createTextNode('')
};<|endoftext|>


<commit_before>import React from "react"
import { Link } from 'gatsby'
import Layout from "../components/layout"

const PostPage = (props) => (
  <Layout>

          Test

  </Layout>
)

export default PostPage
<commit_msg>Fix graphy ql in post<commit_after>import React from "react"
import { graphql, Link } from 'gatsby'
import Layout from "../components/layout"

export default ({ data }) => {
  const post = data.markdownRemark
    return (
      <Layout>

                <Link className="button is-primary is-rounded" to="/blog">  Back</Link>

{post.frontmatter.title}

{post.frontmatter.date}

      </Layout>
    )

}

export const query = graphql`
  query($slug: String!) {
    markdownRemark(fields: { slug: { eq: $slug } }) {
      html
      frontmatter {
        title
        date(formatString: "MMMM Do, YYYY")
      }
    }
  }
`<|endoftext|>


<commit_before>'use strict';

controllers.controller('OfficeCandidateListController',['$scope', '$routeParams', '$http', '$window', '$rootScope',
  function ($scope, $routeParams, $http, $window, $rootScope) {
    $scope.officeId = $routeParams.officeId;
    $scope.url = '/api/offices/' + $scope.officeId;
    $scope.option = 'candidate_total';

    $http.get('/api/offices/' + $routeParams.officeId).success(function(candidates) {

      $scope.office = candidates[0].office;
      $scope.candidate_name = '';
      $scope.candidate_value = '';
      $scope.candidate_contributions = '';
      $scope.candidate_match = '';
      $scope.detail_link = '';
      $scope.selectedCandidates = candidates.slice(0, 5);
      $scope.candidates = candidates.sort(function (a, b) {
        if(a.name < b.name) { return -1; }

        if(a.name > b.name) { return 1; }

        return 0;
      });

      nycCampaignFinanceApp.emitLoaded($rootScope);

      for(var i = 0, len = $scope.selectedCandidates.length; i < len; i++) {
        $('#can_' + $scope.selectedCandidates[i].id).addClass('active');
      }
  });

    $scope.byTotal = function byTotal($event) {
    nycCampaignFinanceApp.sort($event, 'candidate_total', $scope, 'barGraphRenderer', 'selectedCandidates');
  };

    $scope.byContributions = function byContributions($event) {
    nycCampaignFinanceApp.sort($event, 'candidate_contributions', $scope, 'barGraphRenderer', 'selectedCandidates');
  };

    $scope.byMatch = function byMatch($event) {
    nycCampaignFinanceApp.sort($event, 'candidate_match', $scope, 'barGraphRenderer', 'selectedCandidates');
  };

    $scope.byContributors = function byContributors($event) {
    nycCampaignFinanceApp.sort($event, 'count_contributors', $scope, 'barGraphRenderer', 'selectedCandidates');
  };

    $scope.barGraphRenderer = function (el, data) {
    if (!$scope.el) {
      $scope.el = el;
    }

    if(data && data.length > 0) {
      var countCandidates = data.length;
      var margin = {top: 20, right: 0, bottom: 0, left: 5}
      var width = 760 - margin.left - margin.right;
      var height = 600 - margin.top - margin.bottom;
      var barHeight = 35; //(width / countCandidates) > 20 ? width / countCandidates : 20;

      var domainMax = d3.max(data, function(obj) {
        return Math.round(obj[$scope.option]);
      });

      var domainMin = d3.min(data, function(obj) {
        return Math.round(obj[$scope.option]);
      });

      var maxName = d3.max(data, function(obj) {
        return (obj.name.trim().length < 27) ? obj.name.trim().length : 27;
      });

      var labelOffset = (maxName + .5) * 9;

      var totalScale = null;

      var setScaleRange = function(min, max) {
        totalScale = d3.scale.linear().domain([0, domainMax]);
        totalScale = totalScale.rangeRound([min, max]);
      };

      //Shrink the scale range down to fit a little padding and the labels.
      setScaleRange(10, width - 30 - labelOffset);

      //Setup the svg.
      if (!$scope.svg) {
        $scope.svg = el.attr('width', width)
            .attr('height', height + margin.top + margin.bottom)
            .append('g')
            .attr('transform','translate(0,' + margin.top + ')');

        $scope.svg.insert("g")
            .attr('class', 'x axis')
            .attr('transform','translate(' + (labelOffset- 10) + ', ' + (height - 30) + ')');;
      }

      var svg = $scope.svg;

      //Setup the X axis. Align to top.
      var xAxis =d3.svg.axis()
          .scale(totalScale.nice(5))
          .orient('top')
          .ticks(5)
          .tickSize(height - 30)
          .tickPadding(10);

      //count of contributors is not a currency.
      if($scope.option !== 'count_contributors') {
       xAxis.tickFormat(nycCampaignFinanceApp.currencyFormat);
      }

      var bar = svg.selectAll('.vertical-bar')
          .data(data, function(d) {
            return d.candidate_id;
          }).sort(function (a, b) {
            return b[$scope.option] - a[$scope.option];
          });

      //Add Horizontal Bars.
      var barEnter = bar.enter().append('g').attr('transform', function(d, i) {
        return 'translate(' + labelOffset + ',' + ((i * barHeight)+15) + ')';
      })
      .attr('class', 'vertical-bar');

      barEnter.append('rect')
      .attr('width', function(d) {
        return totalScale(d[$scope.option]);
      })
      .attr('height', barHeight - 5);

      //Add text labels on the left. Right align.
      barEnter.append('text')
      .attr('x', function (d) {
        return 0;
      })
      .attr('y', function (d) {
        return (barHeight/2) + 5;
      })
      .attr('text-anchor', 'end')
      .attr('dx', function () {
        return '-.5em';
      })
      .text(function (d) {
        return d.name.trim();
      });

      //Add event handlers.
      bar.on('mouseover', function(d, i) {
        $scope.$apply(function () {
          $scope.candidate_name = d.name.trim();
          $scope.candidate_value = $scope.value = nycCampaignFinanceApp.getValue(d[$scope.option], $scope.option);
          $scope.candidate_total = d.candidate_total;
          $scope.candidate_match = d.candidate_match;
          $scope.candidate_contributions = d.candidate_contributions;
          $scope.count_contributors = d.count_contributors.toLocaleString();
          $scope.detail_link = '/candidate/' + d.candidate_id;
        });
        nycCampaignFinanceApp.positionToolTip('candidate_info', '', d3.event);
      })
      .on('mouseleave', function() {
        nycCampaignFinanceApp.hideToolTip('candidate_info');
      })
      .on('mousemove', function () {
        nycCampaignFinanceApp.positionToolTip('candidate_info', '', d3.event);
      })
      .on('click', function(d, i) {
        $window.location.href = $scope.detail_link;
      });

      //Update Transition for bars.
      var barUpdate = bar.transition()
      .attr('transform', function(d, i) {
        return 'translate(' + labelOffset + ', ' + ((i * barHeight)+15) + ')';
      });

      barUpdate.select('rect')
      .attr('width', function(d) {
        return totalScale(d[$scope.option]);
      })
      .attr('height', function(d, i) {
        return barHeight - 5;
      });

      bar.exit().remove();

      //x axis update transition.
      d3.transition(svg).select('.x.axis').call(xAxis);
    }
  };

    $scope.toggleSelected = function ($event, i) {

    $(event.target).toggleClass('active');
    //var i = parseInt($event.target.id.replace('can_', ''), 10);
    var selectedIdx = $scope.selectedCandidates.indexOf($scope.candidates[i]);

    if (selectedIdx === -1) {
      //check if len is 15. //max that will fit.
      if($scope.selectedCandidates.length === 15) {
        $('#can_' + $scope.selectedCandidates[0].candidate_id).removeClass('active');
        $scope.selectedCandidates.splice(0, 1, $scope.candidates[i]);
      } else {
        $scope.selectedCandidates.push($scope.candidates[i]);
      }
    } else {
      $scope.selectedCandidates.splice(selectedIdx, 1);
    }

    $scope.setWindow();
    d3.transition().duration(550).each(function() { $scope.barGraphRenderer($scope.el, $scope.selectedCandidates); });
  };

    $scope.isSelected = function(candidate_id) {
    for(var i = 0, len = $scope.selectedCandidates.length; i < len; i++) {
      if($scope.selectedCandidates[i].candidate_id === candidate_id) {
        return true;
      }
    }
    return false;
  };

    $scope.removeActive = function($event, candidate_id, i) {
    candidate_id = parseInt(candidate_id, 10);

    $('#can_' + candidate_id).removeClass('active');

    if($scope.isSelected(candidate_id)) {
      $scope.selectedCandidates.splice(i, 1);
      $scope.setWindow();
    }
  };

    $scope.addActive = function(candidate_id) {
    candidate_id = parseInt(candidate_id, 10);

    if($scope.isSelected(candidate_id)) {
        $('#can_' + candidate_id).addClass('active');
    }
  };

    $scope.setWindow = function() {
    if ($scope.selectedCandidates.length === 0) {
      $('.candidates').addClass('hide');
    } else {
      $('.candidates').removeClass('hide');
    }
  };

}]);<commit_msg>fix event.<commit_after>'use strict';

controllers.controller('OfficeCandidateListController',['$scope', '$routeParams', '$http', '$window', '$rootScope',
  function ($scope, $routeParams, $http, $window, $rootScope) {
    $scope.officeId = $routeParams.officeId;
    $scope.url = '/api/offices/' + $scope.officeId;
    $scope.option = 'candidate_total';

    $http.get('/api/offices/' + $routeParams.officeId).success(function(candidates) {

      $scope.office = candidates[0].office;
      $scope.candidate_name = '';
      $scope.candidate_value = '';
      $scope.candidate_contributions = '';
      $scope.candidate_match = '';
      $scope.detail_link = '';
      $scope.selectedCandidates = candidates.slice(0, 5);
      $scope.candidates = candidates.sort(function (a, b) {
        if(a.name < b.name) { return -1; }

        if(a.name > b.name) { return 1; }

        return 0;
      });

      nycCampaignFinanceApp.emitLoaded($rootScope);

      for(var i = 0, len = $scope.selectedCandidates.length; i < len; i++) {
        $('#can_' + $scope.selectedCandidates[i].id).addClass('active');
      }
  });

    $scope.byTotal = function byTotal($event) {
    nycCampaignFinanceApp.sort($event, 'candidate_total', $scope, 'barGraphRenderer', 'selectedCandidates');
  };

    $scope.byContributions = function byContributions($event) {
    nycCampaignFinanceApp.sort($event, 'candidate_contributions', $scope, 'barGraphRenderer', 'selectedCandidates');
  };

    $scope.byMatch = function byMatch($event) {
    nycCampaignFinanceApp.sort($event, 'candidate_match', $scope, 'barGraphRenderer', 'selectedCandidates');
  };

    $scope.byContributors = function byContributors($event) {
    nycCampaignFinanceApp.sort($event, 'count_contributors', $scope, 'barGraphRenderer', 'selectedCandidates');
  };

    $scope.barGraphRenderer = function (el, data) {
    if (!$scope.el) {
      $scope.el = el;
    }

    if(data && data.length > 0) {
      var countCandidates = data.length;
      var margin = {top: 20, right: 0, bottom: 0, left: 5}
      var width = 760 - margin.left - margin.right;
      var height = 600 - margin.top - margin.bottom;
      var barHeight = 35; //(width / countCandidates) > 20 ? width / countCandidates : 20;

      var domainMax = d3.max(data, function(obj) {
        return Math.round(obj[$scope.option]);
      });

      var domainMin = d3.min(data, function(obj) {
        return Math.round(obj[$scope.option]);
      });

      var maxName = d3.max(data, function(obj) {
        return (obj.name.trim().length < 27) ? obj.name.trim().length : 27;
      });

      var labelOffset = (maxName + .5) * 9;

      var totalScale = null;

      var setScaleRange = function(min, max) {
        totalScale = d3.scale.linear().domain([0, domainMax]);
        totalScale = totalScale.rangeRound([min, max]);
      };

      //Shrink the scale range down to fit a little padding and the labels.
      setScaleRange(10, width - 30 - labelOffset);

      //Setup the svg.
      if (!$scope.svg) {
        $scope.svg = el.attr('width', width)
            .attr('height', height + margin.top + margin.bottom)
            .append('g')
            .attr('transform','translate(0,' + margin.top + ')');

        $scope.svg.insert("g")
            .attr('class', 'x axis')
            .attr('transform','translate(' + (labelOffset- 10) + ', ' + (height - 30) + ')');;
      }

      var svg = $scope.svg;

      //Setup the X axis. Align to top.
      var xAxis =d3.svg.axis()
          .scale(totalScale.nice(5))
          .orient('top')
          .ticks(5)
          .tickSize(height - 30)
          .tickPadding(10);

      //count of contributors is not a currency.
      if($scope.option !== 'count_contributors') {
       xAxis.tickFormat(nycCampaignFinanceApp.currencyFormat);
      }

      var bar = svg.selectAll('.vertical-bar')
          .data(data, function(d) {
            return d.candidate_id;
          }).sort(function (a, b) {
            return b[$scope.option] - a[$scope.option];
          });

      //Add Horizontal Bars.
      var barEnter = bar.enter().append('g').attr('transform', function(d, i) {
        return 'translate(' + labelOffset + ',' + ((i * barHeight)+15) + ')';
      })
      .attr('class', 'vertical-bar');

      barEnter.append('rect')
      .attr('width', function(d) {
        return totalScale(d[$scope.option]);
      })
      .attr('height', barHeight - 5);

      //Add text labels on the left. Right align.
      barEnter.append('text')
      .attr('x', function (d) {
        return 0;
      })
      .attr('y', function (d) {
        return (barHeight/2) + 5;
      })
      .attr('text-anchor', 'end')
      .attr('dx', function () {
        return '-.5em';
      })
      .text(function (d) {
        return d.name.trim();
      });

      //Add event handlers.
      bar.on('mouseover', function(d, i) {
        $scope.$apply(function () {
          $scope.candidate_name = d.name.trim();
          $scope.candidate_value = $scope.value = nycCampaignFinanceApp.getValue(d[$scope.option], $scope.option);
          $scope.candidate_total = d.candidate_total;
          $scope.candidate_match = d.candidate_match;
          $scope.candidate_contributions = d.candidate_contributions;
          $scope.count_contributors = d.count_contributors.toLocaleString();
          $scope.detail_link = '/candidate/' + d.candidate_id;
        });
        nycCampaignFinanceApp.positionToolTip('candidate_info', '', d3.event);
      })
      .on('mouseleave', function() {
        nycCampaignFinanceApp.hideToolTip('candidate_info');
      })
      .on('mousemove', function () {
        nycCampaignFinanceApp.positionToolTip('candidate_info', '', d3.event);
      })
      .on('click', function(d, i) {
        $window.location.href = $scope.detail_link;
      });

      //Update Transition for bars.
      var barUpdate = bar.transition()
      .attr('transform', function(d, i) {
        return 'translate(' + labelOffset + ', ' + ((i * barHeight)+15) + ')';
      });

      barUpdate.select('rect')
      .attr('width', function(d) {
        return totalScale(d[$scope.option]);
      })
      .attr('height', function(d, i) {
        return barHeight - 5;
      });

      bar.exit().remove();

      //x axis update transition.
      d3.transition(svg).select('.x.axis').call(xAxis);
    }
  };

    $scope.toggleSelected = function ($event, i) {

    $(d3.event.target).toggleClass('active');
    //var i = parseInt($event.target.id.replace('can_', ''), 10);
    var selectedIdx = $scope.selectedCandidates.indexOf($scope.candidates[i]);

    if (selectedIdx === -1) {
      //check if len is 15. //max that will fit.
      if($scope.selectedCandidates.length === 15) {
        $('#can_' + $scope.selectedCandidates[0].candidate_id).removeClass('active');
        $scope.selectedCandidates.splice(0, 1, $scope.candidates[i]);
      } else {
        $scope.selectedCandidates.push($scope.candidates[i]);
      }
    } else {
      $scope.selectedCandidates.splice(selectedIdx, 1);
    }

    $scope.setWindow();
    d3.transition().duration(550).each(function() { $scope.barGraphRenderer($scope.el, $scope.selectedCandidates); });
  };

    $scope.isSelected = function(candidate_id) {
    for(var i = 0, len = $scope.selectedCandidates.length; i < len; i++) {
      if($scope.selectedCandidates[i].candidate_id === candidate_id) {
        return true;
      }
    }
    return false;
  };

    $scope.removeActive = function($event, candidate_id, i) {
    candidate_id = parseInt(candidate_id, 10);

    $('#can_' + candidate_id).removeClass('active');

    if($scope.isSelected(candidate_id)) {
      $scope.selectedCandidates.splice(i, 1);
      $scope.setWindow();
    }
  };

    $scope.addActive = function(candidate_id) {
    candidate_id = parseInt(candidate_id, 10);

    if($scope.isSelected(candidate_id)) {
        $('#can_' + candidate_id).addClass('active');
    }
  };

    $scope.setWindow = function() {
    if ($scope.selectedCandidates.length === 0) {
      $('.candidates').addClass('hide');
    } else {
      $('.candidates').removeClass('hide');
    }
  };

}]);<|endoftext|>


<commit_before>const readline = require('readline');

const utils = {
  clearLine() {
    readline.clearLine(process.stdout, 0);
    readline.cursorTo(process.stdout, 0, null);
  },
  writeLine(msg) {
    this.clearLine();
    process.stdout.write(`${msg}`);
  },
};

module.exports = utils;
<commit_msg>skip logging on CI In a CI env the logging on same line is not reported correctly in ui<commit_after>const readline = require('readline');

const isCI = !!process.env.CI;

const utils = {
  clearLine() {
    if (isCI) {
      return;
    }
    readline.clearLine(process.stdout, 0);
    readline.cursorTo(process.stdout, 0, null);
  },
  writeLine(msg) {
    if (isCI) {
      return;
    }
    this.clearLine();
    process.stdout.write(`${msg}`);
  },
};

module.exports = utils;
<|endoftext|>


<commit_before>/*
 * Paper.js
 *
 * This file is part of Paper.js, a JavaScript Vector Graphics Library,
 * based on Scriptographer.org and designed to be largely API compatible.
 * http://paperjs.org/
 * http://scriptographer.org/
 *
 * Distributed under the MIT license. See LICENSE file for details.
 *
 * Copyright (c) 2011, Juerg Lehni & Jonathan Puckey
 * http://lehni.org/ & http://jonathanpuckey.com/
 *
 * All rights reserved.
 */

var PointText = this.PointText = TextItem.extend({
	beans: true,

	initialize: function(point) {
		this.base();
		var point = Point.read(arguments);
		this.content = '';
		// TODO: Since we're exposing matrix, we actually need to extract _point
		// from it each time getPoint is called, as it could be modified other
		// than through PointText#transform().
		this._point = LinkedPoint.create(this, 'setPoint', point.x, point.y);
		this.matrix = new Matrix().translate(point);
	},

	clone: function() {
		var copy = this._clone(new PointText(this._point));
		copy.content = this.content;
		// Use Matrix#initialize to easily copy over values.
		copy.matrix.initialize(this.matrix);
		return copy;
	},

	getPoint: function() {
		return this._point;
	},

	setPoint: function(point) {
		this._transform(new Matrix().translate(
				Point.read(arguments).subtract(this._point)));
	},

	// TODO: position should be the center point of the bounds
	// but we currently don't support bounds for PointText.
	getPosition: function() {
		return this._point;
	},

	setPosition: function(point) {
		this.setPoint.apply(this, arguments);
	},

	_transform: function(matrix, flags) {
		this.matrix.preConcatenate(matrix);
		// We need to transform the LinkedPoint, passing true for dontNotify so
		// chaning it won't trigger calls of setPoint(), leading to an endless
		// recursion.
		matrix._transformPoint(this._point, this._point, true);
	},

	draw: function(ctx) {
		if (this.content == null)
			return;
		ctx.save();
		ctx.font = this._characterStyle.fontSize + 'pt ' +
				this._characterStyle.font;
		ctx.textAlign = this._paragraphStyle.justification;
		this.matrix.applyToContext(ctx);

		var fillColor = this.getFillColor();
		var strokeColor = this.getStrokeColor();
		if (!fillColor || !strokeColor)
			ctx.globalAlpha = this.opacity;
		if (fillColor) {
			ctx.fillStyle = fillColor.getCanvasStyle(ctx);
			ctx.fillText(this.content, 0, 0);
		}
		if (strokeColor) {
			ctx.strokeStyle = strokeColor.getCanvasStyle(ctx);
			ctx.strokeText(this.content, 0, 0);
		}
		ctx.restore();
	}
});
<commit_msg>Make PointText#matrix 'private' by renaming to _matrix.<commit_after>/*
 * Paper.js
 *
 * This file is part of Paper.js, a JavaScript Vector Graphics Library,
 * based on Scriptographer.org and designed to be largely API compatible.
 * http://paperjs.org/
 * http://scriptographer.org/
 *
 * Distributed under the MIT license. See LICENSE file for details.
 *
 * Copyright (c) 2011, Juerg Lehni & Jonathan Puckey
 * http://lehni.org/ & http://jonathanpuckey.com/
 *
 * All rights reserved.
 */

var PointText = this.PointText = TextItem.extend({
	beans: true,

	initialize: function(point) {
		this.base();
		var point = Point.read(arguments);
		this.content = '';
		this._point = LinkedPoint.create(this, 'setPoint', point.x, point.y);
		this._matrix = new Matrix().translate(point);
	},

	clone: function() {
		var copy = this._clone(new PointText(this._point));
		copy.content = this.content;
		// Use Matrix#initialize to easily copy over values.
		copy._matrix.initialize(this._matrix);
		return copy;
	},

	getPoint: function() {
		return this._point;
	},

	setPoint: function(point) {
		this._transform(new Matrix().translate(
				Point.read(arguments).subtract(this._point)));
	},

	// TODO: position should be the center point of the bounds
	// but we currently don't support bounds for PointText.
	getPosition: function() {
		return this._point;
	},

	setPosition: function(point) {
		this.setPoint.apply(this, arguments);
	},

	_transform: function(matrix, flags) {
		this._matrix.preConcatenate(matrix);
		// We need to transform the LinkedPoint, passing true for dontNotify so
		// chaning it won't trigger calls of setPoint(), leading to an endless
		// recursion.
		matrix._transformPoint(this._point, this._point, true);
	},

	draw: function(ctx) {
		if (this.content == null)
			return;
		ctx.save();
		ctx.font = this._characterStyle.fontSize + 'pt ' +
				this._characterStyle.font;
		ctx.textAlign = this._paragraphStyle.justification;
		this._matrix.applyToContext(ctx);

		var fillColor = this.getFillColor();
		var strokeColor = this.getStrokeColor();
		if (!fillColor || !strokeColor)
			ctx.globalAlpha = this.opacity;
		if (fillColor) {
			ctx.fillStyle = fillColor.getCanvasStyle(ctx);
			ctx.fillText(this.content, 0, 0);
		}
		if (strokeColor) {
			ctx.strokeStyle = strokeColor.getCanvasStyle(ctx);
			ctx.strokeText(this.content, 0, 0);
		}
		ctx.restore();
	}
});
<|endoftext|>


<commit_before>// -------------------------------------------------------------------------- \\
// File: NotificationView.js                                                  \\
// Module: View                                                               \\
// Requires: Core, Foundation, View.js                                        \\
// Author: Neil Jenkins                                                       \\
// License: © 2010–2013 Opera Software ASA. All rights reserved.              \\
// -------------------------------------------------------------------------- \\

"use strict";

( function ( NS, undefined ) {

var hiddenLayout = {
    top: 0
};

var NotificationView = NS.Class({

    Extends: NS.View,

    Mixin: NS.AnimatableView,

    animateLayerDuration: 200,

    className: function () {
        return 'NotificationView' +
            ( this.get( 'userMayClose' ) ? ' closable' : '' );
    }.property( 'userMayClose' ),

    destroyOnClose: true,

    isShowing: false,
    userMayClose: true,
    precedence: 0,
    timeout: 0,

    text: '',
    html: '',

    _timer: null,

    show: function ( notificationsContainer ) {
        notificationsContainer.insertView( this );
        this.set( 'layout', {
            top: this.get( 'pxHeight' )
        });
        var timeout = this.get( 'timeout' );
        if ( timeout ) {
            this._timer =
                NS.RunLoop.invokeAfterDelay( this.hide, timeout, this );
        }
        return this;
    },

    hide: function () {
        if ( this._timer ) {
            NS.RunLoop.cancel( this._timer );
            this._timer = null;
        }
        return this.set( 'layout', hiddenLayout );
    },

    didAnimate: function () {
        this.increment( 'animating', -1 );
        if ( !this.get( 'animating' ) &&
                this.get( 'layout' ) === hiddenLayout ) {
            this.get( 'parentView' )
                .removeView( this )
                .notificationDidHide( this );

            if ( this.get( 'destroyOnClose' ) ) {
                this.destroy();
            }
        }
    }.queue( 'render' ),

    zIndex: 10000,
    layout: hiddenLayout,

    draw: function ( layer ) {
        this.drawNotification( layer );
        if ( this.get( 'userMayClose' ) ) {
            layer.appendChild(
                NS.Element.create( 'a.close', [
                    NS.loc( 'Close' )
                ])
            );
        }
    },

    drawNotification: function ( layer ) {
        var text = this.get( 'text' ),
            html = this.get( 'html' );
        if ( text || html ) {
            layer.appendChild(
                NS.Element.create( 'span', {
                    text: text || undefined,
                    html: text ? undefined : html
                })
            );
        }
    },

    hideOnClick: function ( event ) {
        if ( event.target.className === 'close' ) {
            event.preventDefault();
            this.hide();
        }
    }.on( 'click' )
});

var NotificationContainerView = NS.Class({

    Extends: NS.View,

    showing: null,

    init: function ( mixin ) {
        this._waiting = [];
        NotificationContainerView.parent.init.call( this, mixin );
    },

    positioning: 'absolute',
    layout: {
        bottom: '100%',
        left: '50%'
    },

    willShow: function ( notification ) {
        var showing = this.get( 'showing' );
        if ( showing ) {
            if ( notification !== showing &&
                    notification.get( 'precedence' ) >=
                    showing.get( 'precedence' ) ) {
                this._waiting.push( notification );
                this.hide( showing );
            }
            return false;
        }
        return true;
    },

    show: function ( notification ) {
        if ( this.willShow( notification ) ) {
            this.set( 'showing', notification );
            notification.show( this );
        }
    },

    hide: function ( notification ) {
        var showing = this.get( 'showing' );
        if ( showing && ( !notification || notification === showing ) ) {
            showing.hide();
        }
    },

    notificationDidHide: function ( notification ) {
        this.set( 'showing', null );
        var nextNotification = this._waiting.pop();
        if ( nextNotification ) {
            this.show( nextNotification );
        }
    }
});

NS.NotificationContainerView = NotificationContainerView;
NS.NotificationView = NotificationView;

}( this.O ) );
<commit_msg>Redraw NotificationView when text changes.<commit_after>// -------------------------------------------------------------------------- \\
// File: NotificationView.js                                                  \\
// Module: View                                                               \\
// Requires: Core, Foundation, View.js                                        \\
// Author: Neil Jenkins                                                       \\
// License: © 2010–2013 Opera Software ASA. All rights reserved.              \\
// -------------------------------------------------------------------------- \\

"use strict";

( function ( NS, undefined ) {

var hiddenLayout = {
    top: 0
};

var NotificationView = NS.Class({

    Extends: NS.View,

    Mixin: NS.AnimatableView,

    animateLayerDuration: 200,

    className: function () {
        return 'NotificationView' +
            ( this.get( 'userMayClose' ) ? ' closable' : '' );
    }.property( 'userMayClose' ),

    destroyOnClose: true,

    isShowing: false,
    userMayClose: true,
    precedence: 0,
    timeout: 0,

    text: '',
    html: '',

    _timer: null,

    show: function ( notificationsContainer ) {
        notificationsContainer.insertView( this );
        this.set( 'layout', {
            top: this.get( 'pxHeight' )
        });
        var timeout = this.get( 'timeout' );
        if ( timeout ) {
            this._timer =
                NS.RunLoop.invokeAfterDelay( this.hide, timeout, this );
        }
        return this;
    },

    hide: function () {
        if ( this._timer ) {
            NS.RunLoop.cancel( this._timer );
            this._timer = null;
        }
        return this.set( 'layout', hiddenLayout );
    },

    didAnimate: function () {
        this.increment( 'animating', -1 );
        if ( !this.get( 'animating' ) &&
                this.get( 'layout' ) === hiddenLayout ) {
            this.get( 'parentView' )
                .removeView( this )
                .notificationDidHide( this );

            if ( this.get( 'destroyOnClose' ) ) {
                this.destroy();
            }
        }
    }.queue( 'render' ),

    zIndex: 10000,
    layout: hiddenLayout,

    draw: function ( layer ) {
        this.drawNotification( layer );
        if ( this.get( 'userMayClose' ) ) {
            layer.appendChild(
                NS.Element.create( 'a.close', [
                    NS.loc( 'Close' )
                ])
            );
        }
    },

    drawNotification: function ( layer ) {
        var text = this.get( 'text' ),
            html = this.get( 'html' );
        if ( text || html ) {
            layer.appendChild(
                this._textNode = NS.Element.create( 'span', {
                    text: text || undefined,
                    html: text ? undefined : html
                })
            );
        }
    },

    propertyNeedsRedraw: function () {
        return NotificationView.parent
            .propertyNeedsRedraw.apply( this, arguments );
    }.observes( 'className', 'layerStyles', 'text', 'html' ),

    redrawText: function () {
        this.redrawHTML();
    },
    redrawHTML: function () {
        var text = this.get( 'text' ),
            html = this.get( 'html' );
        this._textNode.set( html ? 'html' : 'text', html || text );
    },

    hideOnClick: function ( event ) {
        if ( event.target.className === 'close' ) {
            event.preventDefault();
            this.hide();
        }
    }.on( 'click' )
});

var NotificationContainerView = NS.Class({

    Extends: NS.View,

    showing: null,

    init: function ( mixin ) {
        this._waiting = [];
        NotificationContainerView.parent.init.call( this, mixin );
    },

    positioning: 'absolute',
    layout: {
        bottom: '100%',
        left: '50%'
    },

    willShow: function ( notification ) {
        var showing = this.get( 'showing' );
        if ( showing ) {
            if ( notification !== showing &&
                    notification.get( 'precedence' ) >=
                    showing.get( 'precedence' ) ) {
                this._waiting.push( notification );
                this.hide( showing );
            }
            return false;
        }
        return true;
    },

    show: function ( notification ) {
        if ( this.willShow( notification ) ) {
            this.set( 'showing', notification );
            notification.show( this );
        }
    },

    hide: function ( notification ) {
        var showing = this.get( 'showing' );
        if ( showing && ( !notification || notification === showing ) ) {
            showing.hide();
        }
    },

    notificationDidHide: function ( notification ) {
        this.set( 'showing', null );
        var nextNotification = this._waiting.pop();
        if ( nextNotification ) {
            this.show( nextNotification );
        }
    }
});

NS.NotificationContainerView = NotificationContainerView;
NS.NotificationView = NotificationView;

}( this.O ) );
<|endoftext|>


<commit_before>var locastyle = locastyle || {};
locastyle.general = (function() {
  'use strict';

  var events = {
    '[data-toggle-class]|click' : _toggleClass,
    '[data-toggle-text]|click' : _toggleText,
    '.ls-link-smooth|click' : _smoothScroll
  }

  function init() {
    _loadEvents();
    showSidebar();
    subMenu();
    _locationHashTrigger();
    _elementDisabled();
    _linkPreventDefault();
    _btnGroupActivationToogle(dom_scope);
  }

  function _loadEvents () {
    $.each(events, function (eventDesc,fn) {
      var selectorEvent = eventDesc.split('|')
      $(selectorEvent[0]).on(selectorEvent[1], selectorEvent[2], function(evt){
        var $this = $(this);
        fn(evt, $this);
      });
    });
  }

  function _toggleClass(evt, $this) {
    evt.preventDefault();
    var $target = $this.data('target') ? $($this.data('target')) : $this,
        cssClass = $this.data('toggle-class');
    $target.toggleClass(cssClass);
  }

  function _toggleText(evt, $this) {
    evt.preventDefault();
    var $target = $this.data('target') ? $($this.data('target')) : $this,
        textChange = $this.data('toggle-text'),
        textOriginal = $target.text();
    $this.data('toggle-text', textOriginal);
    $target.text(textChange);
  }

  function _smoothScroll (evt, $this) {
    evt.preventDefault();
    var $target = $($this.attr('href'));
    if($target[0]){
      $('html,body').animate({
       scrollTop: $target.offset().top -70
      }, 1000);
    }
  }

  function _locationHashTrigger () {
    if(window.location.hash){
      $('a[class*="ls-"][href="'+window.location.hash+'"]').trigger('click');
    }
  }

  function showSidebar() {
    var $showHide = $('.show-sidebar');
    var $html = $('html');

    $showHide.on('touchstart click', function(evt){
      $html.toggleClass('sidebar-visible');
      evt.preventDefault();
    });
  }

  function subMenu() {
    $('.ls-submenu > a').on('click', function(evt){
      $(this).parent().toggleClass('active');
      evt.preventDefault();
    })
  }

  function _elementDisabled() {
    var $elementDisabled = $('.disabled') || [disabled='disabled'];
    $elementDisabled.on('click', function(evt){
      evt.preventDefault();
    });
  }

  function _linkPreventDefault(dom_scope) {
    $("a", dom_scope).on("click", function(e){
      if($(this).attr("href") === "" || $(this).attr("href") === "#"){
        e.preventDefault();
      }
    });
  }

  function _btnGroupActivationToogle(dom_scope) {
    $(".ls-group-active .ls-btn", dom_scope).on("click", function() {
      $(this).siblings().removeClass("active");
      $(this).addClass("active");
    });
  }

  return {
    init:init
  };

}());
<commit_msg>removing dom_scope on the function btnGroupActiovation<commit_after>var locastyle = locastyle || {};
locastyle.general = (function() {
  'use strict';

  var events = {
    '[data-toggle-class]|click' : _toggleClass,
    '[data-toggle-text]|click' : _toggleText,
    '.ls-link-smooth|click' : _smoothScroll
  }

  function init() {
    _loadEvents();
    showSidebar();
    subMenu();
    _locationHashTrigger();
    _elementDisabled();
    _linkPreventDefault();
    _btnGroupActivationToogle();
  }

  function _loadEvents () {
    $.each(events, function (eventDesc,fn) {
      var selectorEvent = eventDesc.split('|')
      $(selectorEvent[0]).on(selectorEvent[1], selectorEvent[2], function(evt){
        var $this = $(this);
        fn(evt, $this);
      });
    });
  }

  function _toggleClass(evt, $this) {
    evt.preventDefault();
    var $target = $this.data('target') ? $($this.data('target')) : $this,
        cssClass = $this.data('toggle-class');
    $target.toggleClass(cssClass);
  }

  function _toggleText(evt, $this) {
    evt.preventDefault();
    var $target = $this.data('target') ? $($this.data('target')) : $this,
        textChange = $this.data('toggle-text'),
        textOriginal = $target.text();
    $this.data('toggle-text', textOriginal);
    $target.text(textChange);
  }

  function _smoothScroll (evt, $this) {
    evt.preventDefault();
    var $target = $($this.attr('href'));
    if($target[0]){
      $('html,body').animate({
       scrollTop: $target.offset().top -70
      }, 1000);
    }
  }

  function _locationHashTrigger () {
    if(window.location.hash){
      $('a[class*="ls-"][href="'+window.location.hash+'"]').trigger('click');
    }
  }

  function showSidebar() {
    var $showHide = $('.show-sidebar');
    var $html = $('html');

    $showHide.on('touchstart click', function(evt){
      $html.toggleClass('sidebar-visible');
      evt.preventDefault();
    });
  }

  function subMenu() {
    $('.ls-submenu > a').on('click', function(evt){
      $(this).parent().toggleClass('active');
      evt.preventDefault();
    })
  }

  function _elementDisabled() {
    var $elementDisabled = $('.disabled') || [disabled='disabled'];
    $elementDisabled.on('click', function(evt){
      evt.preventDefault();
    });
  }

  function _linkPreventDefault(dom_scope) {
    $("a", dom_scope).on("click", function(e){
      if($(this).attr("href") === "" || $(this).attr("href") === "#"){
        e.preventDefault();
      }
    });
  }

  function _btnGroupActivationToogle(dom_scope) {
    $(".ls-group-active .ls-btn", dom_scope).on("click", function() {
      $(this).siblings().removeClass("active");
      $(this).addClass("active");
    });
  }

  return {
    init:init
  };

}());
<|endoftext|>


<commit_before>import Component from '../core/component.js';
import * as Tools from './_index.js';
export default class ToolBelt extends Component {
  constructor(SL, config) {
    super(SL, config);
    this.Belt = {};
    this.State = {
      activeTool: undefined
    };
    if (config.enable) {
      this.enableTool(config.enable);
    }
    this.checkActiveTool();
  }
  reset() {
    super.reset();
    for (let type in this.Belt) {
      this.Belt[type].destroy();
      this.Belt[type] = undefined;
    }
  }

  enableTool(type) {
    if (type.constructor === Array) {
      for (var i=0; i < type.length; i++) {
        this.enableTool(type[i]);
      }
    }
    else if (type && typeof type == 'string' && !this.Belt[type] && Tools[type]) {
      let config = this.config[type] || {};
      let newTool = new Tools[type](this.SL, config, this);
      this.Belt[type] = newTool;
      if (!newTool.name) {
        newTool.name = type;
      }
    }
  }
  disableTool(type) {
    if (type && this.Belt[type]) {
      if (this.State.ActiveTool == this.Belt[type]) {
        this.deactivateTool();
      }
      this.Belt[type].destroy();
      this.Belt[type] = undefined;
      delete this.Belt[type];
    }
  }
  activateTool(type) {
    if (this.Belt[type]) {
      let wasActive = this.State.ActiveTool;
      let activate = this.Belt[type];
      if (wasActive && activate != wasActive) {
        this.deactivateTool(false);
      }
      this.State.ActiveTool = activate;
      if (activate && !activate.isActive() && typeof activate.activate == 'function') {
        activate.activate();
      }
      if (activate != wasActive) {
        this.refreshUI();
      }
      return activate;
    }
  }
  deactivateTool(checkForActive=true, activeTool=null) {
    let deactivate = this.State.ActiveTool;
    if (activeTool && deactivate != activeTool) {
      return;
    }
    if (deactivate && typeof deactivate.deactivate == 'function') {
      deactivate.deactivate();
    }
    this.State.ActiveTool = undefined;
    if (deactivate) {
      this.refreshUI();
    }
    if (checkForActive) {
      this.checkActiveTool();
    }
    return deactivate;
  }
  checkActiveTool(enable=true) {
    let activate;
    for (let type in this.Belt) {
      let tool = this.Belt[type];
      let priority = tool.activationPriority;
      if (priority >= 0 && (!activate || priority >= activate.priority)) {
        if (!activate) {
          activate = {};
        }
        activate.type = type;
        activate.tool = tool;
        activate.priority = priority;
      }
    }
    if (activate && activate.type) {
      this.activateTool(activate.type);
    }
  }
  checkMouseTarget() {
    // @TODO: check SL.UI.Mouse.State.point
    // if targetChanged, this.refreshUI();
  }
  refreshUI() {
    this.runTools('refreshUI');
  }
  runTools(method, args, on=ToolBelt.RUN_ON.ALL) {
    for (let type in this.Belt) {
      let tool = this.Belt[type];
      if (!tool || typeof tool[method] != 'function') {
        continue;
      }
      if (on===ToolBelt.RUN_ON.ACTIVE) {
        if (tool.isActive()) {
          tool[method](args);
        }
      }
      else if (on===ToolBelt.RUN_ON.INACTIVE) {
        if (!tool.isActive()) {
          tool[method](args);
        }
      }
      else {
        tool[method](args);
      }
    }
  }

  onKeyDown(event) {
    this.runTools('onKeyDown', event);
  }
  onKeyUp(event) {
    this.runTools('onKeyUp', event);
  }
  onMouseMove(event) {
    this.checkMouseTarget();
    this.checkActiveTool();
    this.runTools('onMouseMove', event);
  }
  onMouseDown(event) {
    this.runTools('onMouseDown', event);
  }
  onMouseUp(event) {
    this.runTools('onMouseUp', event);
  }
  onMouseDrag(event) {
    this.runTools('onMouseDrag', event);
  }
  onClick(event) {
    this.runTools('onClick', event);
  }
  onDoubleClick(event) {
    this.runTools('onDoubleClick', event);
  }
  onSelectionChange(event) {
    this.runTools('onSelectionChange', event);
  }
}
ToolBelt.RUN_ON = {
  ALL: 0,
  ACTIVE: 1,
  INACTIVE: 2
};
<commit_msg>Implements ToolBelt.checkMouseTarget()<commit_after>import Component from '../core/component.js';
import * as Tools from './_index.js';
export default class ToolBelt extends Component {
  constructor(SL, config) {
    super(SL, config);
    this.Belt = {};
    this.State = {
      activeTool: undefined,
      Mouse: {
        Hover: {}
      }
    };
    if (config.enable) {
      this.enableTool(config.enable);
    }
    this.checkActiveTool();
  }
  reset() {
    super.reset();
    for (let type in this.Belt) {
      this.Belt[type].destroy();
      this.Belt[type] = undefined;
    }
    this.State.activeTool = undefined;
    this.State.Mouse.Hover = {};
  }

  enableTool(type) {
    if (type.constructor === Array) {
      for (var i=0; i < type.length; i++) {
        this.enableTool(type[i]);
      }
    }
    else if (type && typeof type == 'string' && !this.Belt[type] && Tools[type]) {
      let config = this.config[type] || {};
      let newTool = new Tools[type](this.SL, config, this);
      this.Belt[type] = newTool;
      if (!newTool.name) {
        newTool.name = type;
      }
    }
  }
  disableTool(type) {
    if (type && this.Belt[type]) {
      if (this.State.ActiveTool == this.Belt[type]) {
        this.deactivateTool();
      }
      this.Belt[type].destroy();
      this.Belt[type] = undefined;
      delete this.Belt[type];
    }
  }
  activateTool(type) {
    if (this.Belt[type]) {
      let wasActive = this.State.ActiveTool;
      let activate = this.Belt[type];
      if (wasActive && activate != wasActive) {
        this.deactivateTool(false);
      }
      this.State.ActiveTool = activate;
      if (activate && !activate.isActive() && typeof activate.activate == 'function') {
        activate.activate();
      }
      if (activate != wasActive) {
        this.checkMouseTarget();
        this.refreshUI();
      }
      return activate;
    }
  }
  deactivateTool(checkForActive=true, activeTool=null) {
    let deactivate = this.State.ActiveTool;
    if (activeTool && deactivate != activeTool) {
      return;
    }
    if (deactivate && typeof deactivate.deactivate == 'function') {
      deactivate.deactivate();
    }
    this.State.ActiveTool = undefined;
    if (deactivate) {
      this.refreshUI();
    }
    if (checkForActive) {
      this.checkActiveTool();
    }
    return deactivate;
  }
  checkActiveTool(enable=true) {
    let activate;
    for (let type in this.Belt) {
      let tool = this.Belt[type];
      let priority = tool.activationPriority;
      if (priority >= 0 && (!activate || priority >= activate.priority)) {
        if (!activate) {
          activate = {};
        }
        activate.type = type;
        activate.tool = tool;
        activate.priority = priority;
      }
    }
    if (activate && activate.type) {
      this.activateTool(activate.type);
    }
  }
  checkMouseTarget() {
    if (this.SL.UI.Mouse.State.active && this.SL.UI.Mouse.State.point) {
      var oldTarget = this.State.Mouse.Hover.target;
      var target = this.SL.Paper.project.hitTest(this.SL.UI.Mouse.State.point);
      this.State.Mouse.Hover.target = target;
      this.State.Mouse.Hover.targetItem = ((target && target.item) ? target.item : null);
      this.State.Mouse.Hover.targetLocked = (target && target.item && target.item.data && target.item.data.locked);
      if ( ((!target && oldTarget) || (target && !oldTarget)
        || (target && oldTarget && (target.item != oldTarget.item || target.segment != oldTarget.segment)))) {
        this.runTools('onMouseHoverTargetChange', {target: target, oldTarget: oldTarget});
        this.refreshUI();
      }
    }
  }
  refreshUI() {
    this.runTools('refreshUI');
  }
  runTools(method, args, on=ToolBelt.RUN_ON.ALL) {
    for (let type in this.Belt) {
      let tool = this.Belt[type];
      if (!tool || typeof tool[method] != 'function') {
        continue;
      }
      if (on===ToolBelt.RUN_ON.ACTIVE) {
        if (tool.isActive()) {
          tool[method](args);
        }
      }
      else if (on===ToolBelt.RUN_ON.INACTIVE) {
        if (!tool.isActive()) {
          tool[method](args);
        }
      }
      else {
        tool[method](args);
      }
    }
  }

  onKeyDown(event) {
    this.runTools('onKeyDown', event);
  }
  onKeyUp(event) {
    this.runTools('onKeyUp', event);
  }
  onMouseMove(event) {
    this.checkMouseTarget();
    this.checkActiveTool();
    this.runTools('onMouseMove', event);
  }
  onMouseDown(event) {
    this.runTools('onMouseDown', event);
  }
  onMouseUp(event) {
    this.runTools('onMouseUp', event);
  }
  onMouseDrag(event) {
    this.runTools('onMouseDrag', event);
  }
  onClick(event) {
    this.runTools('onClick', event);
  }
  onDoubleClick(event) {
    this.runTools('onDoubleClick', event);
  }
  onSelectionChange(event) {
    this.runTools('onSelectionChange', event);
  }
}
ToolBelt.RUN_ON = {
  ALL: 0,
  ACTIVE: 1,
  INACTIVE: 2
};
<|endoftext|>


<commit_before>const AWS = require("aws-sdk");
const uuidv4 = require("uuid/v4");
const logError = require("./log-error.js");

AWS.config.update({ region: process.env.AWS_REGION });

function uploadToAWS(base64String) {
  const newFileName = uuidv4();
  const s3 = new AWS.S3({ apiVersion: "2006-03-01" });
  const base64Data = Buffer.from(
    base64String.split(";")[1].split(",")[1],
    "base64"
  );

  const contentType = base64String.split(":")[1].split(";")[0];

  const uploadParams = {
    Bucket: `${process.env.AWS_S3_BUCKET}`,
    Key: newFileName,
    Body: base64Data,
    ContentEncoding: "base64",
    ContentType: contentType,
    ACL: "public-read",
  };

  s3.upload(uploadParams, (err, data) => {
    if (err) {
      logError(err);
    }
  });

  return `${process.env.AWS_UPLOADS_URL}${newFileName}`;
}

module.exports = uploadToAWS;
<commit_msg>Using pure variable, no need to translate<commit_after>const AWS = require("aws-sdk");
const uuidv4 = require("uuid/v4");
const logError = require("./log-error.js");

AWS.config.update({ region: process.env.AWS_REGION });

function uploadToAWS(base64String) {
  const newFileName = uuidv4();
  const s3 = new AWS.S3({ apiVersion: "2006-03-01" });
  const base64Data = Buffer.from(
    base64String.split(";")[1].split(",")[1],
    "base64"
  );

  const contentType = base64String.split(":")[1].split(";")[0];

  const uploadParams = {
    Bucket: process.env.AWS_S3_BUCKET,
    Key: newFileName,
    Body: base64Data,
    ContentEncoding: "base64",
    ContentType: contentType,
    ACL: "public-read",
  };

  s3.upload(uploadParams, (err, data) => {
    if (err) {
      logError(err);
    }
  });

  return `${process.env.AWS_UPLOADS_URL}${newFileName}`;
}

module.exports = uploadToAWS;
<|endoftext|>


<commit_before>var util = require('util');

var classes = {};
var observables = {};

exports.handlers = {

  newDoclet: function(e) {
    var doclet = e.doclet;
    if (doclet.kind == 'class') {
      classes[doclet.longname] = doclet;
    }
  },

  parseComplete: function(e) {
    var doclets = e.doclets;
    var cls, doclet, i, ii, observable;
    for (i = 0, ii = doclets.length - 1; i < ii; ++i) {
      doclet = doclets[i];
      cls = classes[doclet.longname.split('#')[0]];
      if (typeof doclet.observable == 'string' && cls) {
        var name = doclet.name.replace(/^[sg]et/, '');
        name = name.substr(0, 1).toLowerCase() + name.substr(1);
        var key = doclet.longname.split('#')[0] + '#' + name;
        doclet.observable = key;
        if (!observables[key]) {
          observables[key] = {};
        }
        observable = observables[key];
        observable.name = name;
        observable.readonly = typeof observable.readonly == 'boolean' ?
            observable.readonly : true;
        if (doclet.name.indexOf('get') === 0) {
          observable.type = doclet.returns[0].type;
          observable.description = doclet.returns[0].description;
        } else if (doclet.name.indexOf('set') === 0) {
          observable.readonly = false;
        }
        if (!cls.observables) {
          cls.observables = [];
        }
        observable = observables[doclet.observable];
        if (cls.observables.indexOf(observable) == -1) {
          cls.observables.push(observable);
        }
        if (!cls.fires) {
          cls.fires = [];
        }
        if (cls.fires.indexOf('ol.ObjectEvent') === -1) {
          cls.fires.push('ol.ObjectEvent');
        }
      }
    }
  }

};

exports.defineTags = function(dictionary) {
  dictionary.defineTag('observable', {
    mustNotHaveValue: true,
    canHaveType: false,
    canHaveName: false,
    onTagged: function(doclet, tag) {
      doclet.observable = '';
    }
  });
};
<commit_msg>Remove unused require<commit_after>var classes = {};
var observables = {};

exports.handlers = {

  newDoclet: function(e) {
    var doclet = e.doclet;
    if (doclet.kind == 'class') {
      classes[doclet.longname] = doclet;
    }
  },

  parseComplete: function(e) {
    var doclets = e.doclets;
    var cls, doclet, i, ii, observable;
    for (i = 0, ii = doclets.length - 1; i < ii; ++i) {
      doclet = doclets[i];
      cls = classes[doclet.longname.split('#')[0]];
      if (typeof doclet.observable == 'string' && cls) {
        var name = doclet.name.replace(/^[sg]et/, '');
        name = name.substr(0, 1).toLowerCase() + name.substr(1);
        var key = doclet.longname.split('#')[0] + '#' + name;
        doclet.observable = key;
        if (!observables[key]) {
          observables[key] = {};
        }
        observable = observables[key];
        observable.name = name;
        observable.readonly = typeof observable.readonly == 'boolean' ?
            observable.readonly : true;
        if (doclet.name.indexOf('get') === 0) {
          observable.type = doclet.returns[0].type;
          observable.description = doclet.returns[0].description;
        } else if (doclet.name.indexOf('set') === 0) {
          observable.readonly = false;
        }
        if (!cls.observables) {
          cls.observables = [];
        }
        observable = observables[doclet.observable];
        if (cls.observables.indexOf(observable) == -1) {
          cls.observables.push(observable);
        }
        if (!cls.fires) {
          cls.fires = [];
        }
        if (cls.fires.indexOf('ol.ObjectEvent') === -1) {
          cls.fires.push('ol.ObjectEvent');
        }
      }
    }
  }

};

exports.defineTags = function(dictionary) {
  dictionary.defineTag('observable', {
    mustNotHaveValue: true,
    canHaveType: false,
    canHaveName: false,
    onTagged: function(doclet, tag) {
      doclet.observable = '';
    }
  });
};
<|endoftext|>