<commit_before>/*
Rabbitmq wrapper for promise based connection

 */
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

 */
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>!function(window, angular, undefined) {
  'use strict';
  angular.module('angular.password', [])
  .directive('matchPassword', function() {

    function link(scope, element, attrs, ctrls) {
      var formController = ctrls[1];
      var ngModel = ctrls[0];
      var otherPasswordModel = formController[attrs.matchPassword];

      ngModel.$parsers.push(function(value) {
        if (value === otherPasswordModel.$viewValue) {
          ngModel.$setValidity('passwordMatch', true);
        }
        else{
          ngModel.$setValidity('passwordMatch', false);
        }
        return value;
      });

      otherPasswordModel.$parsers.push(function(value) {
        ngModel.$setValidity('passwordMatch', value === ngModel.$viewValue);
        return value;
      });

    }
    var controllers = ['^ngModel', '^form'];

    return {
      restrict: 'A',
      require: controllers,
      link: link
    }; // end return
  });

}(window, window.angular);
<commit_msg>feat(matchPassword): $validators for 1.3<commit_after>!function(window, angular, undefined) {
  'use strict';
  angular.module('angular.password', [])
  .directive('matchPassword', function() {

    function link(scope, element, attrs, ctrls) {
      var formController = ctrls[1];
      var ngModel = ctrls[0];
      var otherPasswordModel = formController[attrs.matchPassword];

      // if ng1.3+
      if (ngModel.$validators) {
        ngModel.$validators.passwordMatch = function(modelValue, viewValue) {
         return (modelValue === otherPassword.$modelValue);
        };
      } else {
        ngModel.$parsers.push(function(value) {
          ngModel.$setValidity('passwordMatch', value === otherPasswordModel.$viewValue);
          return value;
        });

        otherPasswordModel.$parsers.push(function(value) {
          ngModel.$setValidity('passwordMatch', value === ngModel.$viewValue);
          return value;
        });
      }

    }
    var controllers = ['^ngModel', '^form'];

    return {
      restrict: 'A',
      require: controllers,
      link: link
    }; // end return
  });

}(window, window.angular);
<|endoftext|>


<commit_before><commit_msg>Fehler beim Auslesen der Optionen behoben<commit_after><|endoftext|>


<commit_before>import {React, Component, PropTypes} from '../imports';
import {WSWeekPickerCalendar} from './ws-week-picker-calendar';

/**
 * @class WSWeekPicker
 * @property {object} props               - properties
 * @property {number} props.selectedYear  - set a preselected year
 * @property {number} props.selectedWeek  - set a preselected week
 * @property {function} props.onChange    - handler which notifies about picked week
 *
 */
export class WSWeekPicker extends Component {
  static defaultProps = {
    selectedYear: null,
    selectedWeek: null,
    onChange: () => {}
  };

  static propTypes = {
    selectedYear: PropTypes.number,
    selectedWeek: PropTypes.number,
    onChange: PropTypes.func
  };

  /**
   * @param {Object} props React properties
   * @constructor
   */
  constructor(props) {
    super(props);

    this.state = {
      show: false,
      selectedYear: props.selectedYear,
      selectedWeek: props.selectedWeek
    };
  }

  /**
   * Initialize a listener to clicks outside of the calender to close it.
   * @returns {void}
   */
  componentDidMount() {
    this.outsideClickListener = document.body.addEventListener('click', e => {
      if (this.state.show && !isDescendant(this.elem, e.target)) {
        this.setState({show: false});
      }
    });
  }

  /**
   * Updates the internal state of the component if properties change.
   * @param {Object} newProps React properties
   * @returns {void}
   */
  componentWillReceiveProps(newProps) {
    this.setState({
      selectedYear: newProps.selectedYear === null ? newProps.selectedYear : this.state.selectedYear,
      selectedWeek: newProps.selectedWeek === null ? newProps.selectedWeek : this.state.selectedWeek,
      show: newProps.show === null ? newProps.show : this.state.show
    });
  }

  /**
   * Removes the click outside listener on deletion of this component.
   * @returns {void}
   */
  componentWillUnmount() {
    document.body.removeEventListener('click', this.outsideClickListener);
  }

  /**
   * Handler for new selections on the calendar
   * @param {String} week clicked on week
   * @param {String} year clicked on year
   * @returns {void}
   */
  onChange({week, year}) {
    if (this.state.selectedWeek !== week || this.state.selectedYear !== year) {
      this.setState({
        selectedYear: year,
        selectedWeek: week
      });
      if (this.props.onChange) {
        this.props.onChange({week, year});
      }
    }
  }

  /**
   * Open or closes the calendar.
   * @returns {void}
   */
  toggleCalendar() {
    this.setState({show: !this.state.show});
  }

  /**
   * Renders the input and the calendar.
   * @returns {Object} virtual dom
   */
  render() {
    return (

 { this.elem = elem; }}>
        <input
          value={this.state.selectedWeek !== null ? `Week ${this.state.selectedWeek}, ${this.state.selectedYear}` : ''}
          placeholder={'Please choose a week'}
          onClick={() => this.toggleCalendar()}
          readOnly
        />
        <span
          className={`icon icon-${this.state.show ? 'cross' : 'calendar'}`}
          onClick={() => this.toggleCalendar()}
        />
        {this.state.show &&
          <WSWeekPickerCalendar
            onChange={selection => this.onChange(selection)}
            selectedYear={this.state.selectedYear}
            selectedWeek={this.state.selectedWeek}
          />
        }

    );
  }
}

/**
 * Check if a child element is descendant of a parent element
 * @param {Element} parent parent element
 * @param {Element} child child element
 * @returns {boolean}
 */
function isDescendant(parent, child) {
  let node = child.parentNode;
  while (node !== null) {
    if (node === parent) {
      return true;
    }
    node = node.parentNode;
  }
  return false;
}
<commit_msg>added change event if no function callback defined<commit_after>import {React, Component, PropTypes} from '../imports';
import {WSWeekPickerCalendar} from './ws-week-picker-calendar';

/**
 * @class WSWeekPicker
 * @property {object} props               - properties
 * @property {number} props.selectedYear  - set a preselected year
 * @property {number} props.selectedWeek  - set a preselected week
 * @property {function} props.onChange    - handler which notifies about picked week
 *
 */
export class WSWeekPicker extends Component {
  static defaultProps = {
    selectedYear: null,
    selectedWeek: null,
    onChange: () => {}
  };

  static propTypes = {
    selectedYear: PropTypes.number,
    selectedWeek: PropTypes.number,
    onChange: PropTypes.func
  };

  /**
   * @param {Object} props React properties
   * @constructor
   */
  constructor(props) {
    super(props);

    this.element = null;
    this.state = {
      show: false,
      selectedYear: props.selectedYear,
      selectedWeek: props.selectedWeek
    };
  }

  /**
   * Initialize a listener to clicks outside of the calender to close it.
   * @returns {void}
   */
  componentDidMount() {
    this.outsideClickListener = document.body.addEventListener('click', e => {
      if (this.state.show && !isDescendant(this.element, e.target)) {
        this.setState({show: false});
      }
    });
  }

  /**
   * Updates the internal state of the component if properties change.
   * @param {Object} newProps React properties
   * @returns {void}
   */
  componentWillReceiveProps(newProps) {
    this.setState({
      selectedYear: newProps.selectedYear === null ? newProps.selectedYear : this.state.selectedYear,
      selectedWeek: newProps.selectedWeek === null ? newProps.selectedWeek : this.state.selectedWeek,
      show: newProps.show === null ? newProps.show : this.state.show
    });
  }

  /**
   * Removes the click outside listener on deletion of this component.
   * @returns {void}
   */
  componentWillUnmount() {
    document.body.removeEventListener('click', this.outsideClickListener);
  }

  /**
   * Handler for new selections on the calendar
   * @param {String} week clicked on week
   * @param {String} year clicked on year
   * @returns {void}
   */
  onChange({week, year}) {
    if (this.state.selectedWeek !== week || this.state.selectedYear !== year) {
      this.setState({
        selectedYear: year,
        selectedWeek: week
      });
      if (this.props.onChange) {
        this.props.onChange({week, year});
      } else {
        this.element.dispatchEvent(new CustomEvent('change', {week, year}, {bubbles: true}));
      }
    }
  }

  /**
   * Open or closes the calendar.
   * @returns {void}
   */
  toggleCalendar() {
    this.setState({show: !this.state.show});
  }

  /**
   * Renders the input and the calendar.
   * @returns {Object} virtual dom
   */
  render() {
    return (

 { this.element = element; }}>
        <input
          value={this.state.selectedWeek !== null ? `Week ${this.state.selectedWeek}, ${this.state.selectedYear}` : ''}
          placeholder={'Please choose a week'}
          onClick={() => this.toggleCalendar()}
          readOnly
        />
        <span
          className={`icon icon-${this.state.show ? 'cross' : 'calendar'}`}
          onClick={() => this.toggleCalendar()}
        />
        {this.state.show &&
          <WSWeekPickerCalendar
            onChange={selection => this.onChange(selection)}
            selectedYear={this.state.selectedYear}
            selectedWeek={this.state.selectedWeek}
          />
        }

    );
  }
}

/**
 * Check if a child element is descendant of a parent element
 * @param {Element} parent parent element
 * @param {Element} child child element
 * @returns {boolean}
 */
function isDescendant(parent, child) {
  let node = child.parentNode;
  while (node !== null) {
    if (node === parent) {
      return true;
    }
    node = node.parentNode;
  }
  return false;
}
<|endoftext|>


<commit_before>function VersiculoDao(connection) {
    this._connection = connection;
}

VersiculoDao.prototype.buscaPorId = function (version, liv, cap, versIni, versFim, callback) {
    var query = " select ver_capitulo, ver_versiculo, ver_texto from versiculos where ver_vrs_id = ?  and ver_liv_id = ? and ver_capitulo = ? and ver_versiculo between ? and ? ";
    this._connection.query(query, [version, liv, cap, versIni, versFim], callback);
}

VersiculoDao.prototype.getQuantidadeCapitulos = function (liv, callback) {
    var query = " SELECT max(ver_capitulo) as qtde_capitulos from versiculos where ver_liv_id = ? ";
    this._connection.query(query, [liv], callback);
}

VersiculoDao.prototype.getQuantidadeVersiculos = function (liv, vers, callback) {
    var query = " SELECT max(ver_versiculo) as qtde_versiculos from versiculos where ver_liv_id = ? and ver_capitulo = ?";
    this._connection.query(query, [liv, vers], callback);
}

module.exports = function(){
    return VersiculoDao;
};

VersiculoDao.prototype.buscaPorPalavra = function (version, liv, cap, versIni, versFim, word, callback) {
    var query = " select count(ver_id) from versiculos where upper(ver_texto) like upper(?) and ver_vrs_id = ? ";
    if(liv != null) {
        query += " and ver_liv_id = " + liv;
    }
    if(cap != null) {
        query += " and ver_capitulo = " + cap;
    }
    if(versIni != null) {
        query += " and ver_versiculo > " + versIni;
    }
    if(versFim != null) {
        query += " and ver_versiculo < " + versFim;
    }
    this._connection.query(query, [word, version], callback);
}
<commit_msg>ajuste<commit_after>function VersiculoDao(connection) {
    this._connection = connection;
}

VersiculoDao.prototype.buscaPorId = function (version, liv, cap, versIni, versFim, callback) {
    var query = " select ver_capitulo, ver_versiculo, ver_texto from versiculos where ver_vrs_id = ?  and ver_liv_id = ? and ver_capitulo = ? and ver_versiculo between ? and ? ";
    this._connection.query(query, [version, liv, cap, versIni, versFim], callback);
}

VersiculoDao.prototype.getQuantidadeCapitulos = function (liv, callback) {
    var query = " SELECT max(ver_capitulo) as qtde_capitulos from versiculos where ver_liv_id = ? ";
    this._connection.query(query, [liv], callback);
}

VersiculoDao.prototype.getQuantidadeVersiculos = function (liv, vers, callback) {
    var query = " SELECT max(ver_versiculo) as qtde_versiculos from versiculos where ver_liv_id = ? and ver_capitulo = ?";
    this._connection.query(query, [liv, vers], callback);
}

module.exports = function(){
    return VersiculoDao;
};

VersiculoDao.prototype.buscaPorPalavra = function (version, liv, cap, versIni, versFim, word, callback) {
    var query = " select count(ver_id) from versiculos where upper(ver_texto) like upper(%?%) and ver_vrs_id = ? ";
    if(liv != null) {
        query += " and ver_liv_id = " + liv;
    }
    if(cap != null) {
        query += " and ver_capitulo = " + cap;
    }
    if(versIni != null) {
        query += " and ver_versiculo > " + versIni;
    }
    if(versFim != null) {
        query += " and ver_versiculo < " + versFim;
    }
    this._connection.query(query, [word, version], callback);
}
<|endoftext|>


<commit_before>//
// RUNTIME TYPE CHECKING
//

export {
  isArray,
  isArguments,
  isBoolean,
  isEventEmitter,
  isFunction,
  isPojo,
  isString,
  isTemplateLiteral,
  isNumber,
  isThisValue,
  isNull,
  isUnset,
  ArgTypeError,
  ObjTypeError
}

//
// isType
//

function isEventEmitter(obj) {
  return (
    isObject(obj) &&
    isFunction(obj.emit) &&
    (isFunction(obj.addListener) || isFunction(obj.on)) &&
    (isFunction(obj.removeListener) || isFunction(obj.off))
  )
}

isEventEmitter.displayName = 'isEventEmitter'

function isUnset(obj) {
  return obj === null || obj === undefined
}

isArray.displayName = 'isUnset'

function isArray(obj) {
  return Array.isArray(obj)
}

isArray.displayName = 'isArray'

function isArguments(obj) {
  if (!isObject(obj)) {
    return false
  }
  const hasMap = isFunction(obj.map)
  const hasLength = isNumber(obj.length)
  const hasObjectPrototype = obj.__proto__ === Object.prototype
  return hasObjectPrototype && hasLength && !hasMap
}

isArguments.displayName = 'isArguments'

function isBoolean(obj) {
  return obj === true || obj === false
}

isBoolean.displayName = 'isBoolean'

function isFunction(obj) {
  return typeof obj === 'function'
}

isFunction.displayName = 'isFunction'

function isString(obj) {
  return typeof obj === 'string'
}

isString.displayName = 'isString'

function isNull(obj) {
  return obj === null
}

isNull.displayName = 'isNull'

function isNumber(obj) {
  return typeof obj === 'number'
}

isNumber.displayName = 'isNumber'

function isObject(obj) {
  return typeof obj === 'object' && obj !== null
}

isObject.displayName = 'isObject'

function isPojo(obj) {
  if (obj === null || !isObject(obj)) {
    return false
  }
  return Object.getPrototypeOf(obj) === Object.prototype
}

isPojo.displayName = 'isPojo'

function isTemplateLiteral(obj) {
  if (isString(obj)) {
    return true
  }
  if (!isArray(obj)) {
    return false
  }
  return obj.every(isString)
}

isTemplateLiteral.displayName = 'isTemplateLiteral'

function isThisValue(value) {
  function inObject(obj) {
    return obj === value
  }
  inObject.displayName = `isThisValue(${value})`
  return inObject
}

//
// ArgTypeError
//

const typeErrorStringIfFnReturnsFalse = (argName, argTypeFn, arg) => {
  return argTypeFn(arg)
    ? undefined
    : (argTypeFn.displayName || argTypeFn.name) +
        `(${argName}) did not return true`
}

const typeErrorStringIfTypeOfFails = (argName, argType, arg) => {
  return typeof arg === argType
    ? undefined
    : `Argument "${argName}" should be a ${argType}`
}

const typeErrorStringFromArgument = argMap => (arg, index) => {
  if (index >= argMap.length) {
    return
  }

  const { argName, argType } = argMap[index]
  if (arg === undefined) {
    return `Argument undefined: "${argName}"`
  }

  const permittedArgTypes = Array.isArray(argType) ? argType : [argType]

  const errorDescs = permittedArgTypes
    .map(argType =>
      isFunction(argType)
        ? typeErrorStringIfFnReturnsFalse(argName, argType, arg)
        : typeErrorStringIfTypeOfFails(argName, argType, arg)
    )
    .filter(isString)

  const multipleTypesSpecified = permittedArgTypes.length > 1
  const shouldError = multipleTypesSpecified
    ? errorDescs.length > 1
    : errorDescs.length

  if (shouldError) {
    return (
      errorDescs.join('\n| ') +
      `\n> typeof ${argName} === ${typeof arg}(${JSON.stringify(arg)})`
    )
  }
}

/**
 * Helper for enforcing correct argument-types.
 *
 * @private
 * @param {string} namespace
 *
 * @example
 * const argTypeError = ArgTypeError('namespace#')
 *
 * function myFn (myArg1, myArg2) {
 *   const err = argTypeError({
 *     myArg1: isString,
 *     myArg2: isBoolean
 *   })('myFn')(myArg1, myArg2)
 *   if (err) {
 *     throw new TypeError(err)
 *   }
 * }
 */

function ArgTypeError(namespace) {
  return typeMap => {
    const argMap = Object.entries(typeMap).map(([argName, argType]) => ({
      argName,
      argType
    }))

    return fnName => (...args) => {
      const processedArgs = Array.from(args, x =>
        isArguments(x) ? Array.from(x) : x
      ).flat(1)

      const err = processedArgs
        .map(typeErrorStringFromArgument(argMap))
        .filter(isString)

      if (!err.length) {
        return
      }

      const signature = Object.keys(typeMap).join(', ')
      return (
        `\n${namespace || ''}${fnName}(${signature}):\n` +
        `${err.map(err => `| ${err}`).join('\n')}`
      )
    }
  }
}

function ObjTypeError(namespace) {
  return typeMap => {
    const keys = Object.keys(typeMap)
    const objTypeError = ArgTypeError(namespace)(typeMap)
    return fnName => obj => {
      const values = valuesOf(obj, { keys })
      const err = objTypeError(fnName)(...values)
      return err
    }
  }
}

function valuesOf(obj, options) {
  const { keys } = options
  if (!Array.isArray(keys)) {
    return Object.values(obj)
  }
  return keys.reduce((acc, key) => {
    return [...acc, obj[key]]
  }, [])
}
<commit_msg>Comments just for spacing<commit_after>//
// RUNTIME TYPE CHECKING
//

export {
  isArray,
  isArguments,
  isBoolean,
  isEventEmitter,
  isFunction,
  isPojo,
  isString,
  isTemplateLiteral,
  isNumber,
  isThisValue,
  isNull,
  isUnset,
  ArgTypeError,
  ObjTypeError
}

//
// isType
//

// isEventEmitter
//
function isEventEmitter(obj) {
  return (
    isObject(obj) &&
    isFunction(obj.emit) &&
    (isFunction(obj.addListener) || isFunction(obj.on)) &&
    (isFunction(obj.removeListener) || isFunction(obj.off))
  )
}

isEventEmitter.displayName = 'isEventEmitter'

// isUnset
//
function isUnset(obj) {
  return obj === null || obj === undefined
}

isArray.displayName = 'isUnset'

// isArray
//
function isArray(obj) {
  return Array.isArray(obj)
}

isArray.displayName = 'isArray'

// isArguments
//
function isArguments(obj) {
  if (!isObject(obj)) {
    return false
  }
  const hasMap = isFunction(obj.map)
  const hasLength = isNumber(obj.length)
  const hasObjectPrototype = obj.__proto__ === Object.prototype
  return hasObjectPrototype && hasLength && !hasMap
}

isArguments.displayName = 'isArguments'

// isBoolean
//
function isBoolean(obj) {
  return obj === true || obj === false
}

isBoolean.displayName = 'isBoolean'

// isFunction
//
function isFunction(obj) {
  return typeof obj === 'function'
}

isFunction.displayName = 'isFunction'

// isString
//
function isString(obj) {
  return typeof obj === 'string'
}

isString.displayName = 'isString'

// isNull
//
function isNull(obj) {
  return obj === null
}

isNull.displayName = 'isNull'

// isNumber
//
function isNumber(obj) {
  return typeof obj === 'number'
}

isNumber.displayName = 'isNumber'

// isObject
//
function isObject(obj) {
  return typeof obj === 'object' && obj !== null
}

isObject.displayName = 'isObject'

// isPojo
//
function isPojo(obj) {
  if (obj === null || !isObject(obj)) {
    return false
  }
  return Object.getPrototypeOf(obj) === Object.prototype
}

isPojo.displayName = 'isPojo'

// isTemplateLiteral
//
function isTemplateLiteral(obj) {
  if (isString(obj)) {
    return true
  }
  if (!isArray(obj)) {
    return false
  }
  return obj.every(isString)
}

isTemplateLiteral.displayName = 'isTemplateLiteral'

// isThisValue
//
function isThisValue(value) {
  function inObject(obj) {
    return obj === value
  }
  inObject.displayName = `isThisValue(${value})`
  return inObject
}

//
// ArgTypeError
//

const typeErrorStringIfFnReturnsFalse = (argName, argTypeFn, arg) => {
  return argTypeFn(arg)
    ? undefined
    : (argTypeFn.displayName || argTypeFn.name) +
        `(${argName}) did not return true`
}

const typeErrorStringIfTypeOfFails = (argName, argType, arg) => {
  return typeof arg === argType
    ? undefined
    : `Argument "${argName}" should be a ${argType}`
}

const typeErrorStringFromArgument = argMap => (arg, index) => {
  if (index >= argMap.length) {
    return
  }

  const { argName, argType } = argMap[index]
  if (arg === undefined) {
    return `Argument undefined: "${argName}"`
  }

  const permittedArgTypes = Array.isArray(argType) ? argType : [argType]

  const errorDescs = permittedArgTypes
    .map(argType =>
      isFunction(argType)
        ? typeErrorStringIfFnReturnsFalse(argName, argType, arg)
        : typeErrorStringIfTypeOfFails(argName, argType, arg)
    )
    .filter(isString)

  const multipleTypesSpecified = permittedArgTypes.length > 1
  const shouldError = multipleTypesSpecified
    ? errorDescs.length > 1
    : errorDescs.length

  if (shouldError) {
    return (
      errorDescs.join('\n| ') +
      `\n> typeof ${argName} === ${typeof arg}(${JSON.stringify(arg)})`
    )
  }
}

/**
 * Helper for enforcing correct argument-types.
 *
 * @private
 * @param {string} namespace
 *
 * @example
 * const argTypeError = ArgTypeError('namespace#')
 *
 * function myFn (myArg1, myArg2) {
 *   const err = argTypeError({
 *     myArg1: isString,
 *     myArg2: isBoolean
 *   })('myFn')(myArg1, myArg2)
 *   if (err) {
 *     throw new TypeError(err)
 *   }
 * }
 */

function ArgTypeError(namespace) {
  return typeMap => {
    const argMap = Object.entries(typeMap).map(([argName, argType]) => ({
      argName,
      argType
    }))

    return fnName => (...args) => {
      const processedArgs = Array.from(args, x =>
        isArguments(x) ? Array.from(x) : x
      ).flat(1)

      const err = processedArgs
        .map(typeErrorStringFromArgument(argMap))
        .filter(isString)

      if (!err.length) {
        return
      }

      const signature = Object.keys(typeMap).join(', ')
      return (
        `\n${namespace || ''}${fnName}(${signature}):\n` +
        `${err.map(err => `| ${err}`).join('\n')}`
      )
    }
  }
}

function ObjTypeError(namespace) {
  return typeMap => {
    const keys = Object.keys(typeMap)
    const objTypeError = ArgTypeError(namespace)(typeMap)
    return fnName => obj => {
      const values = valuesOf(obj, { keys })
      const err = objTypeError(fnName)(...values)
      return err
    }
  }
}

function valuesOf(obj, options) {
  const { keys } = options
  if (!Array.isArray(keys)) {
    return Object.values(obj)
  }
  return keys.reduce((acc, key) => {
    return [...acc, obj[key]]
  }, [])
}
<|endoftext|>


<commit_before>/*
 *  gridfs/put.js
 *
 *  David Janes
 *  IOTDB.org
 *  2018-11-06
 *
 *  Copyright [2013-2019] [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"

const _ = require("iotdb-helpers")

const assert = require("assert")

const logger = require("../logger")(__filename)

/**
 */
const put = _.promise((self, done) => {
    logger.trace({
        method: parse_path.method,
        bucket: self.bucket,
        filename: self.filename,
    }, "called")

    _.promise(self)
        .validate(put)
        .end(done, self)
})

put.method = "gridfs.put"
put.required = {
    bucket: [ _.is.String, null ],
    filename: _.is.String,
    mongodb: _.is.Object,
}

/**
 *  API
 */
exports.put = put
<commit_msg>put code<commit_after>/*
 *  gridfs/put.js
 *
 *  David Janes
 *  IOTDB.org
 *  2018-11-06
 *
 *  Copyright [2013-2019] [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"

const _ = require("iotdb-helpers")

const assert = require("assert")

const logger = require("../logger")(__filename)

/**
 */
const put = _.promise((self, done) => {
    const gridfs = require("gridfs")

    logger.trace({
        method: parse_path.method,
        bucket: self.bucket,
        filename: self.filename,
    }, "called")

    _.promise(self)
        .validate(put)
        .make((sd, sdone) => {
            let document = self.document
            if (_.is.String(document)) {
                document = Buffer.from(document, self.document_encoding || "utf8")
            }

            const initd = {
                filename: self.filename,
                metadata: {},
            }

            if (self.bucket) {
                initd.bucket = self.bucket
            }

            if (self.document_media_type) {
                initd.metadata.document_media_type = self.document_media_type
            }

            gridfs.writeFile(initd, document, (error, result) => {
                if (error) {
                    return sdone(error)
                }

                sdone(null, self)
            })
        })
        .end(done, self)
})

put.method = "gridfs.put"
put.required = {
    bucket: [ _.is.String, null ],
    filename: _.is.String,
    mongodb: _.is.Object,
    document: [ _.is.String, _.is.Buffer ],
}
put.accepts = {
    document_media_type: _.is.String,
    document_encoding: _.is.String,
}

/**
 */
const put_json = _.promise((self, done) => {
    _.promise(self)
        .validate(put)
        .add({
            document: JSON.stringify(self.json),
            document_media_type: "application/json",
            document_encoding: "utf8",
        })
        .end(done, self)
})

put_json.method = "gridfs.put.json"
put_json.required = {
    bucket: [ _.is.String, null ],
    filename: _.is.String,
    json: _.is.JSON,
    mongodb: _.is.Object,
}

/**
 *  API
 */
exports.put = put
exports.put.json = put_json
<|endoftext|>


<commit_before>/*
 * The MIT License (MIT)
 *
 * Copyright (c) 2015 - <Ali Ok> - <Collin Donahue-Oponski>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

// Gist https://gist.github.com/colllin/1a0c3a91cc641d8e578f
.directive('affixWithinContainer', function($document, $ionicScrollDelegate) {

    var transition = function(element, dy, executeImmediately) {
        element.style[ionic.CSS.TRANSFORM] == 'translate3d(0, -' + dy + 'px, 0)' ||
        executeImmediately ?
            element.style[ionic.CSS.TRANSFORM] = 'translate3d(0, -' + dy + 'px, 0)' :
            ionic.requestAnimationFrame(function() {
                element.style[ionic.CSS.TRANSFORM] = 'translate3d(0, -' + dy + 'px, 0)';
            });
    };

    return {
        restrict: 'A',
        require: '^$ionicScroll',
        link: function($scope, $element, $attr, $ionicScroll) {
            var $affixContainer = $element.closest($attr.affixWithinContainer) || $element.parent();

            var top = 0;
            var height = 0;
            var scrollMin = 0;
            var scrollMax = 0;
            var scrollTransition = 0;
            var affixedHeight = 0;
            var updateScrollLimits = _.throttle(function(scrollTop) {
                top = $affixContainer.offset().top;
                height = $affixContainer.outerHeight(false);
                affixedHeight = $element.outerHeight(false);
                scrollMin = scrollTop + top;
                scrollMax = scrollMin + height;
                scrollTransition = scrollMax - affixedHeight;
            }, 500, {
                trailing: false
            });

            var affix = null;
            var unaffix = null;
            var $affixedClone = null;
            var setupAffix = function() {
                unaffix = null;
                affix = function() {
                    $affixedClone = $element.clone().css({
                        position: 'fixed',
                        top: 0,
                        left: 0,
                        right: 0
                    });
                    $($ionicScroll.element).append($affixedClone);

                    setupUnaffix();
                };
            };
            var cleanupAffix = function() {
                $affixedClone && $affixedClone.remove();
                $affixedClone = null;
            };
            var setupUnaffix = function() {
                affix = null;
                unaffix = function() {
                    cleanupAffix();
                    setupAffix();
                };
            };
            $scope.$on('$destroy', cleanupAffix);
            setupAffix();

            var affixedJustNow;
            var scrollTop;
            $($ionicScroll.element).on('scroll', function(event) {
                scrollTop = (event.detail || event.originalEvent && event.originalEvent.detail).scrollTop;
                updateScrollLimits(scrollTop);
                if (scrollTop >= scrollMin && scrollTop <= scrollMax) {
                    affixedJustNow = affix ? affix() || true : false;
                    if (scrollTop > scrollTransition) {
                        transition($affixedClone[0], Math.floor(scrollTop-scrollTransition), affixedJustNow);
                    } else {
                        transition($affixedClone[0], 0, affixedJustNow);
                    }
                } else {
                    unaffix && unaffix();
                }
            });
        }
    }
});<commit_msg>Beautiful version of the directive<commit_after>/*
 * The MIT License (MIT)
 *
 * Copyright (c) 2015 - <Ali Ok> - <Collin Donahue-Oponski>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

angular.module('ion-affix', ['ionic'])
    .directive('ionAffix', ['$ionicPosition', function ($ionicPosition) {

        // keeping the Ionic specific stuff separated so that they can be changed and used within an other context

        // see https://api.jquery.com/closest/ and http://ionicframework.com/docs/api/utility/ionic.DomUtil/
        function getParentWithClass(elementSelector, parentClass) {
            return angular.element(ionic.DomUtil.getParentWithClass(elementSelector[0], parentClass));
        }

        // see http://underscorejs.org/#throttle
        function throttle(theFunction) {
            return ionic.Utils.throttle(theFunction);
        }

        // see http://www.paulirish.com/2011/requestanimationframe-for-smart-animating/
        // see http://ionicframework.com/docs/api/utility/ionic.DomUtil/
        function requestAnimationFrame(callback) {
            return ionic.requestAnimationFrame(callback);
        }

        // see https://api.jquery.com/offset/
        // see http://ionicframework.com/docs/api/service/$ionicPosition/
        function offset(elementSelector) {
            return $ionicPosition.offset(elementSelector);
        }

        // see https://api.jquery.com/position/
        // see http://ionicframework.com/docs/api/service/$ionicPosition/
        function position(elementSelector){
            return $ionicPosition.position(elementSelector);
        }

        function applyTransform(element, transformString) {
            // do not apply the transformation if it is already applied
            if (element.style[ionic.CSS.TRANSFORM] == transformString) {
            }
            else {
                element.style[ionic.CSS.TRANSFORM] = transformString;
            }
        }

        function translateUp(element, dy, executeImmediately) {
            var translateDyPixelsUp = dy == 0 ? 'translate3d(0px, 0px, 0px)' : 'translate3d(0px, -' + dy + 'px, 0px)';
            // if immediate execution is requested, then just execute immediately
            // if not, execute in the animation frame.
            if (executeImmediately) {
                applyTransform(element, translateDyPixelsUp);
            }
            else {
                // see http://www.paulirish.com/2011/requestanimationframe-for-smart-animating/
                // see http://ionicframework.com/docs/api/utility/ionic.DomUtil/
                requestAnimationFrame(function () {
                    applyTransform(element, translateDyPixelsUp);
                });
            }
        }

        var CALCULATION_THROTTLE_MS = 500;

        return {
            // only allow adding this directive to elements as an attribute
            restrict: 'A',
            // we need $ionicScroll for adding the clone of affix element to the scroll container
            // $ionicScroll.element gives us that
            require: '^$ionicScroll',
            link: function ($scope, $element, $attr, $ionicScroll) {
                // get the affix's container. element will be affix for that container.
                // affix's container will be matched by "affix-within-parent-with-class" attribute.
                // if it is not provided, parent element will be assumed as the container
                var $container;
                if ($attr.affixWithinParentWithClass) {
                    $container = getParentWithClass($element, $attr.affixWithinParentWithClass);
                    if (!$container) {
                        $container = $element.parent();
                    }
                }
                else {
                    $container = $element.parent();
                }

                var scrollMin = 0;
                var scrollMax = 0;
                var scrollTransition = 0;
                // calculate the scroll limits for the affix element and the affix's container
                var calculateScrollLimits = function (scrollTop) {
                    var containerPosition = position($container);
                    var elementOffset = offset($element);

                    var containerTop = containerPosition.top;
                    var containerHeight = containerPosition.height;

                    var affixHeight = elementOffset.height;

                    scrollMin = scrollTop + containerTop;
                    scrollMax = scrollMin + containerHeight;
                    scrollTransition = scrollMax - affixHeight;
                };
                // throttled version of the same calculation
                var throttledCalculateScrollLimits = throttle(
                    calculateScrollLimits,
                    CALCULATION_THROTTLE_MS,
                    {trailing: false}
                );

                var affixClone = null;

                // creates the affix clone and adds it to DOM. by default it is put to top
                var createAffixClone = function () {
                    var clone = $element.clone().css({
                        position: 'absolute',
                        top: 0,
                        left: 0,
                        right: 0
                    });

                    // if directive is given an additional CSS class to apply to the clone, then apply it
                    if ($attr.affixClass) {
                        clone.addClass($attr.affixClass);
                    }

                    angular.element($ionicScroll.element).append(clone);

                    return clone;
                };

                // removes the affix clone from DOM. also deletes the reference to it in the memory.
                var removeAffixClone = function () {
                    if (affixClone)
                        affixClone.remove();
                    affixClone = null;
                };

                $scope.$on('$destroy', removeAffixClone);

                angular.element($ionicScroll.element).on('scroll', function (event) {
                    var scrollTop = (event.detail || event.originalEvent && event.originalEvent.detail).scrollTop;
                    // when scroll to top, we should always execute the immediate calculation.
                    // this is because of some weird problem which is hard to describe.
                    // if you want to experiment, always use the throttled one and just click on the page
                    // you will see all affix elements stacked on top
                    if (scrollTop == 0) {
                        calculateScrollLimits(scrollTop);
                    }
                    else {
                        throttledCalculateScrollLimits(scrollTop);
                    }

                    // when we scrolled to the container, create the clone of element and place it on top
                    if (scrollTop >= scrollMin && scrollTop <= scrollMax) {

                        // we need to track if we created the clone just now
                        // that is important since normally we apply the transforms in the animation frame
                        // but, we need to apply the transform immediately when we add the element for the first time. otherwise it is too late!
                        var cloneCreatedJustNow = false;
                        if (!affixClone) {
                            affixClone = createAffixClone();
                            cloneCreatedJustNow = true;
                        }

                        // if we're reaching towards the end of the container, apply some nice translation to move up/down the clone
                        // but if we're reached already to the container and we're far away than the end, move clone to top
                        if (scrollTop > scrollTransition) {
                            translateUp(affixClone[0], Math.floor(scrollTop - scrollTransition), cloneCreatedJustNow);
                        } else {
                            translateUp(affixClone[0], 0, cloneCreatedJustNow);
                        }
                    } else {
                        removeAffixClone();
                    }
                });
            }
        }
    }]);<|endoftext|>


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

import { chart } from 'src/chart/chartReducer';
import { initSliceEntities } from 'src/dashboard/reducers/sliceEntities';
import { getInitialState as getInitialNativeFilterState } from 'src/dashboard/reducers/nativeFilters';
import { applyDefaultFormData } from 'src/explore/store';
import { buildActiveFilters } from 'src/dashboard/util/activeDashboardFilters';
import findPermission, {
  canUserEditDashboard,
} from 'src/dashboard/util/findPermission';
import {
  DASHBOARD_FILTER_SCOPE_GLOBAL,
  dashboardFilter,
} from 'src/dashboard/reducers/dashboardFilters';
import {
  DASHBOARD_HEADER_ID,
  GRID_DEFAULT_CHART_WIDTH,
  GRID_COLUMN_COUNT,
  DASHBOARD_ROOT_ID,
} from 'src/dashboard/util/constants';
import {
  DASHBOARD_HEADER_TYPE,
  CHART_TYPE,
  ROW_TYPE,
} from 'src/dashboard/util/componentTypes';
import findFirstParentContainerId from 'src/dashboard/util/findFirstParentContainer';
import getEmptyLayout from 'src/dashboard/util/getEmptyLayout';
import getFilterConfigsFromFormdata from 'src/dashboard/util/getFilterConfigsFromFormdata';
import getLocationHash from 'src/dashboard/util/getLocationHash';
import newComponentFactory from 'src/dashboard/util/newComponentFactory';
import { TIME_RANGE } from 'src/visualizations/FilterBox/FilterBox';
import { URL_PARAMS } from 'src/constants';
import { getUrlParam } from 'src/utils/urlUtils';
import { FeatureFlag, isFeatureEnabled } from '../../featureFlags';
import extractUrlParams from '../util/extractUrlParams';

export const HYDRATE_DASHBOARD = 'HYDRATE_DASHBOARD';

export const hydrateDashboard = (dashboardData, chartData) => (
  dispatch,
  getState,
) => {
  const { user, common } = getState();
  let { metadata } = dashboardData;
  const regularUrlParams = extractUrlParams('regular');
  const reservedUrlParams = extractUrlParams('reserved');
  const editMode = reservedUrlParams.edit === 'true';

  let preselectFilters = {};

  chartData.forEach(chart => {
    // eslint-disable-next-line no-param-reassign
    chart.slice_id = chart.form_data.slice_id;
  });
  try {
    // allow request parameter overwrite dashboard metadata
    preselectFilters =
      getUrlParam(URL_PARAMS.preselectFilters) ||
      JSON.parse(metadata.default_filters);
  } catch (e) {
    //
  }

  // Priming the color palette with user's label-color mapping provided in
  // the dashboard's JSON metadata
  if (metadata?.label_colors) {
    const scheme = metadata.color_scheme;
    const namespace = metadata.color_namespace;
    const colorMap = isString(metadata.label_colors)
      ? JSON.parse(metadata.label_colors)
      : metadata.label_colors;
    Object.keys(colorMap).forEach(label => {
      CategoricalColorNamespace.getScale(scheme, namespace).setColor(
        label,
        colorMap[label],
      );
    });
  }

  // dashboard layout
  const { position_data } = dashboardData;
  // new dash: position_json could be {} or null
  const layout =
    position_data && Object.keys(position_data).length > 0
      ? position_data
      : getEmptyLayout();

  // create a lookup to sync layout names with slice names
  const chartIdToLayoutId = {};
  Object.values(layout).forEach(layoutComponent => {
    if (layoutComponent.type === CHART_TYPE) {
      chartIdToLayoutId[layoutComponent.meta.chartId] = layoutComponent.id;
    }
  });

  // find root level chart container node for newly-added slices
  const parentId = findFirstParentContainerId(layout);
  const parent = layout[parentId];
  let newSlicesContainer;
  let newSlicesContainerWidth = 0;

  const filterScopes = metadata?.filter_scopes || {};

  const chartQueries = {};
  const dashboardFilters = {};
  const slices = {};
  const sliceIds = new Set();
  chartData.forEach(slice => {
    const key = slice.slice_id;
    const form_data = {
      ...slice.form_data,
      url_params: {
        ...slice.form_data.url_params,
        ...regularUrlParams,
      },
    };
    chartQueries[key] = {
      ...chart,
      id: key,
      form_data,
      formData: applyDefaultFormData(form_data),
    };

    slices[key] = {
      slice_id: key,
      slice_url: slice.slice_url,
      slice_name: slice.slice_name,
      form_data: slice.form_data,
      viz_type: slice.form_data.viz_type,
      datasource: slice.form_data.datasource,
      description: slice.description,
      description_markeddown: slice.description_markeddown,
      owners: slice.owners,
      modified: slice.modified,
      changed_on: new Date(slice.changed_on).getTime(),
    };

    sliceIds.add(key);

    // if there are newly added slices from explore view, fill slices into 1 or more rows
    if (!chartIdToLayoutId[key] && layout[parentId]) {
      if (
        newSlicesContainerWidth === 0 ||
        newSlicesContainerWidth + GRID_DEFAULT_CHART_WIDTH > GRID_COLUMN_COUNT
      ) {
        newSlicesContainer = newComponentFactory(
          ROW_TYPE,
          (parent.parents || []).slice(),
        );
        layout[newSlicesContainer.id] = newSlicesContainer;
        parent.children.push(newSlicesContainer.id);
        newSlicesContainerWidth = 0;
      }

      const chartHolder = newComponentFactory(
        CHART_TYPE,
        {
          chartId: slice.slice_id,
        },
        (newSlicesContainer.parents || []).slice(),
      );

      layout[chartHolder.id] = chartHolder;
      newSlicesContainer.children.push(chartHolder.id);
      chartIdToLayoutId[chartHolder.meta.chartId] = chartHolder.id;
      newSlicesContainerWidth += GRID_DEFAULT_CHART_WIDTH;
    }

    // build DashboardFilters for interactive filter features
    if (slice.form_data.viz_type === 'filter_box') {
      const configs = getFilterConfigsFromFormdata(slice.form_data);
      let { columns } = configs;
      const { labels } = configs;
      if (preselectFilters[key]) {
        Object.keys(columns).forEach(col => {
          if (preselectFilters[key][col]) {
            columns = {
              ...columns,
              [col]: preselectFilters[key][col],
            };
          }
        });
      }

      const scopesByChartId = Object.keys(columns).reduce((map, column) => {
        const scopeSettings = {
          ...filterScopes[key],
        };
        const { scope, immune } = {
          ...DASHBOARD_FILTER_SCOPE_GLOBAL,
          ...scopeSettings[column],
        };

        return {
          ...map,
          [column]: {
            scope,
            immune,
          },
        };
      }, {});

      const componentId = chartIdToLayoutId[key];
      const directPathToFilter = (layout[componentId].parents || []).slice();
      directPathToFilter.push(componentId);
      dashboardFilters[key] = {
        ...dashboardFilter,
        chartId: key,
        componentId,
        datasourceId: slice.form_data.datasource,
        filterName: slice.slice_name,
        directPathToFilter,
        columns,
        labels,
        scopes: scopesByChartId,
        isInstantFilter: !!slice.form_data.instant_filtering,
        isDateFilter: Object.keys(columns).includes(TIME_RANGE),
      };
    }

    // sync layout names with current slice names in case a slice was edited
    // in explore since the layout was updated. name updates go through layout for undo/redo
    // functionality and python updates slice names based on layout upon dashboard save
    const layoutId = chartIdToLayoutId[key];
    if (layoutId && layout[layoutId]) {
      layout[layoutId].meta.sliceName = slice.slice_name;
    }
  });
  buildActiveFilters({
    dashboardFilters,
    components: layout,
  });

  // store the header as a layout component so we can undo/redo changes
  layout[DASHBOARD_HEADER_ID] = {
    id: DASHBOARD_HEADER_ID,
    type: DASHBOARD_HEADER_TYPE,
    meta: {
      text: dashboardData.dashboard_title,
    },
  };

  const dashboardLayout = {
    past: [],
    present: layout,
    future: [],
  };

  // find direct link component and path from root
  const directLinkComponentId = getLocationHash();
  let directPathToChild = [];
  if (layout[directLinkComponentId]) {
    directPathToChild = (layout[directLinkComponentId].parents || []).slice();
    directPathToChild.push(directLinkComponentId);
  }

  const nativeFilters = getInitialNativeFilterState({
    filterConfig: metadata?.native_filter_configuration || [],
    filterSetsConfig: metadata?.filter_sets_configuration || [],
  });

  if (!metadata) {
    metadata = {};
  }

  metadata.show_native_filters =
    dashboardData?.metadata?.show_native_filters ??
    isFeatureEnabled(FeatureFlag.DASHBOARD_NATIVE_FILTERS);

  if (isFeatureEnabled(FeatureFlag.DASHBOARD_CROSS_FILTERS)) {
    // If user just added cross filter to dashboard it's not saving it scope on server,
    // so we tweak it until user will update scope and will save it in server
    Object.values(dashboardLayout.present).forEach(layoutItem => {
      const chartId = layoutItem.meta?.chartId;
      const behaviors =
        (
          getChartMetadataRegistry().get(
            chartQueries[chartId]?.formData?.viz_type,
          ) ?? {}
        )?.behaviors ?? [];

      if (!metadata.chart_configuration) {
        metadata.chart_configuration = {};
      }
      if (
        behaviors.includes(Behavior.INTERACTIVE_CHART) &&
        !metadata.chart_configuration[chartId]
      ) {
        metadata.chart_configuration[chartId] = {
          id: chartId,
          crossFilters: {
            scope: {
              rootPath: [DASHBOARD_ROOT_ID],
              excluded: [chartId], // By default it doesn't affects itself
            },
          },
        };
      }
    });
  }

  const { roles } = user;
  const canEdit = canUserEditDashboard(dashboardData, user);

  return dispatch({
    type: HYDRATE_DASHBOARD,
    data: {
      sliceEntities: { ...initSliceEntities, slices, isLoading: false },
      charts: chartQueries,
      // read-only data
      dashboardInfo: {
        ...dashboardData,
        metadata,
        userId: String(user.userId), // legacy, please use state.user instead
        dash_edit_perm: canEdit,
        dash_save_perm: findPermission('can_save_dash', 'Superset', roles),
        dash_share_perm: findPermission(
          'can_share_dashboard',
          'Superset',
          roles,
        ),
        superset_can_explore: findPermission('can_explore', 'Superset', roles),
        superset_can_share: findPermission(
          'can_share_chart',
          'Superset',
          roles,
        ),
        superset_can_csv: findPermission('can_csv', 'Superset', roles),
        slice_can_edit: findPermission('can_slice', 'Superset', roles),
        common: {
          // legacy, please use state.common instead
          flash_messages: common.flash_messages,
          conf: common.conf,
        },
      },
      dashboardFilters,
      nativeFilters,
      dashboardState: {
        preselectNativeFilters: getUrlParam(URL_PARAMS.nativeFilters),
        sliceIds: Array.from(sliceIds),
        directPathToChild,
        directPathLastUpdated: Date.now(),
        focusedFilterField: null,
        expandedSlices: metadata?.expanded_slices || {},
        refreshFrequency: metadata?.refresh_frequency || 0,
        // dashboard viewers can set refresh frequency for the current visit,
        // only persistent refreshFrequency will be saved to backend
        shouldPersistRefreshFrequency: false,
        css: dashboardData.css || '',
        colorNamespace: metadata?.color_namespace || null,
        colorScheme: metadata?.color_scheme || null,
        editMode: canEdit && editMode,
        isPublished: dashboardData.published,
        hasUnsavedChanges: false,
        maxUndoHistoryExceeded: false,
        lastModifiedTime: dashboardData.changed_on,
        isRefreshing: false,
        activeTabs: [],
      },
      dashboardLayout,
    },
  });
};
<commit_msg>fix(dashboard): user id can be null when there is an anonymous user (#15592)<commit_after>/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
/* eslint-disable camelcase */
import { isString } from 'lodash';
import {
  Behavior,
  CategoricalColorNamespace,
  getChartMetadataRegistry,
} from '@superset-ui/core';

import { chart } from 'src/chart/chartReducer';
import { initSliceEntities } from 'src/dashboard/reducers/sliceEntities';
import { getInitialState as getInitialNativeFilterState } from 'src/dashboard/reducers/nativeFilters';
import { applyDefaultFormData } from 'src/explore/store';
import { buildActiveFilters } from 'src/dashboard/util/activeDashboardFilters';
import findPermission, {
  canUserEditDashboard,
} from 'src/dashboard/util/findPermission';
import {
  DASHBOARD_FILTER_SCOPE_GLOBAL,
  dashboardFilter,
} from 'src/dashboard/reducers/dashboardFilters';
import {
  DASHBOARD_HEADER_ID,
  GRID_DEFAULT_CHART_WIDTH,
  GRID_COLUMN_COUNT,
  DASHBOARD_ROOT_ID,
} from 'src/dashboard/util/constants';
import {
  DASHBOARD_HEADER_TYPE,
  CHART_TYPE,
  ROW_TYPE,
} from 'src/dashboard/util/componentTypes';
import findFirstParentContainerId from 'src/dashboard/util/findFirstParentContainer';
import getEmptyLayout from 'src/dashboard/util/getEmptyLayout';
import getFilterConfigsFromFormdata from 'src/dashboard/util/getFilterConfigsFromFormdata';
import getLocationHash from 'src/dashboard/util/getLocationHash';
import newComponentFactory from 'src/dashboard/util/newComponentFactory';
import { TIME_RANGE } from 'src/visualizations/FilterBox/FilterBox';
import { URL_PARAMS } from 'src/constants';
import { getUrlParam } from 'src/utils/urlUtils';
import { FeatureFlag, isFeatureEnabled } from '../../featureFlags';
import extractUrlParams from '../util/extractUrlParams';

export const HYDRATE_DASHBOARD = 'HYDRATE_DASHBOARD';

export const hydrateDashboard = (dashboardData, chartData) => (
  dispatch,
  getState,
) => {
  const { user, common } = getState();
  let { metadata } = dashboardData;
  const regularUrlParams = extractUrlParams('regular');
  const reservedUrlParams = extractUrlParams('reserved');
  const editMode = reservedUrlParams.edit === 'true';

  let preselectFilters = {};

  chartData.forEach(chart => {
    // eslint-disable-next-line no-param-reassign
    chart.slice_id = chart.form_data.slice_id;
  });
  try {
    // allow request parameter overwrite dashboard metadata
    preselectFilters =
      getUrlParam(URL_PARAMS.preselectFilters) ||
      JSON.parse(metadata.default_filters);
  } catch (e) {
    //
  }

  // Priming the color palette with user's label-color mapping provided in
  // the dashboard's JSON metadata
  if (metadata?.label_colors) {
    const scheme = metadata.color_scheme;
    const namespace = metadata.color_namespace;
    const colorMap = isString(metadata.label_colors)
      ? JSON.parse(metadata.label_colors)
      : metadata.label_colors;
    Object.keys(colorMap).forEach(label => {
      CategoricalColorNamespace.getScale(scheme, namespace).setColor(
        label,
        colorMap[label],
      );
    });
  }

  // dashboard layout
  const { position_data } = dashboardData;
  // new dash: position_json could be {} or null
  const layout =
    position_data && Object.keys(position_data).length > 0
      ? position_data
      : getEmptyLayout();

  // create a lookup to sync layout names with slice names
  const chartIdToLayoutId = {};
  Object.values(layout).forEach(layoutComponent => {
    if (layoutComponent.type === CHART_TYPE) {
      chartIdToLayoutId[layoutComponent.meta.chartId] = layoutComponent.id;
    }
  });

  // find root level chart container node for newly-added slices
  const parentId = findFirstParentContainerId(layout);
  const parent = layout[parentId];
  let newSlicesContainer;
  let newSlicesContainerWidth = 0;

  const filterScopes = metadata?.filter_scopes || {};

  const chartQueries = {};
  const dashboardFilters = {};
  const slices = {};
  const sliceIds = new Set();
  chartData.forEach(slice => {
    const key = slice.slice_id;
    const form_data = {
      ...slice.form_data,
      url_params: {
        ...slice.form_data.url_params,
        ...regularUrlParams,
      },
    };
    chartQueries[key] = {
      ...chart,
      id: key,
      form_data,
      formData: applyDefaultFormData(form_data),
    };

    slices[key] = {
      slice_id: key,
      slice_url: slice.slice_url,
      slice_name: slice.slice_name,
      form_data: slice.form_data,
      viz_type: slice.form_data.viz_type,
      datasource: slice.form_data.datasource,
      description: slice.description,
      description_markeddown: slice.description_markeddown,
      owners: slice.owners,
      modified: slice.modified,
      changed_on: new Date(slice.changed_on).getTime(),
    };

    sliceIds.add(key);

    // if there are newly added slices from explore view, fill slices into 1 or more rows
    if (!chartIdToLayoutId[key] && layout[parentId]) {
      if (
        newSlicesContainerWidth === 0 ||
        newSlicesContainerWidth + GRID_DEFAULT_CHART_WIDTH > GRID_COLUMN_COUNT
      ) {
        newSlicesContainer = newComponentFactory(
          ROW_TYPE,
          (parent.parents || []).slice(),
        );
        layout[newSlicesContainer.id] = newSlicesContainer;
        parent.children.push(newSlicesContainer.id);
        newSlicesContainerWidth = 0;
      }

      const chartHolder = newComponentFactory(
        CHART_TYPE,
        {
          chartId: slice.slice_id,
        },
        (newSlicesContainer.parents || []).slice(),
      );

      layout[chartHolder.id] = chartHolder;
      newSlicesContainer.children.push(chartHolder.id);
      chartIdToLayoutId[chartHolder.meta.chartId] = chartHolder.id;
      newSlicesContainerWidth += GRID_DEFAULT_CHART_WIDTH;
    }

    // build DashboardFilters for interactive filter features
    if (slice.form_data.viz_type === 'filter_box') {
      const configs = getFilterConfigsFromFormdata(slice.form_data);
      let { columns } = configs;
      const { labels } = configs;
      if (preselectFilters[key]) {
        Object.keys(columns).forEach(col => {
          if (preselectFilters[key][col]) {
            columns = {
              ...columns,
              [col]: preselectFilters[key][col],
            };
          }
        });
      }

      const scopesByChartId = Object.keys(columns).reduce((map, column) => {
        const scopeSettings = {
          ...filterScopes[key],
        };
        const { scope, immune } = {
          ...DASHBOARD_FILTER_SCOPE_GLOBAL,
          ...scopeSettings[column],
        };

        return {
          ...map,
          [column]: {
            scope,
            immune,
          },
        };
      }, {});

      const componentId = chartIdToLayoutId[key];
      const directPathToFilter = (layout[componentId].parents || []).slice();
      directPathToFilter.push(componentId);
      dashboardFilters[key] = {
        ...dashboardFilter,
        chartId: key,
        componentId,
        datasourceId: slice.form_data.datasource,
        filterName: slice.slice_name,
        directPathToFilter,
        columns,
        labels,
        scopes: scopesByChartId,
        isInstantFilter: !!slice.form_data.instant_filtering,
        isDateFilter: Object.keys(columns).includes(TIME_RANGE),
      };
    }

    // sync layout names with current slice names in case a slice was edited
    // in explore since the layout was updated. name updates go through layout for undo/redo
    // functionality and python updates slice names based on layout upon dashboard save
    const layoutId = chartIdToLayoutId[key];
    if (layoutId && layout[layoutId]) {
      layout[layoutId].meta.sliceName = slice.slice_name;
    }
  });
  buildActiveFilters({
    dashboardFilters,
    components: layout,
  });

  // store the header as a layout component so we can undo/redo changes
  layout[DASHBOARD_HEADER_ID] = {
    id: DASHBOARD_HEADER_ID,
    type: DASHBOARD_HEADER_TYPE,
    meta: {
      text: dashboardData.dashboard_title,
    },
  };

  const dashboardLayout = {
    past: [],
    present: layout,
    future: [],
  };

  // find direct link component and path from root
  const directLinkComponentId = getLocationHash();
  let directPathToChild = [];
  if (layout[directLinkComponentId]) {
    directPathToChild = (layout[directLinkComponentId].parents || []).slice();
    directPathToChild.push(directLinkComponentId);
  }

  const nativeFilters = getInitialNativeFilterState({
    filterConfig: metadata?.native_filter_configuration || [],
    filterSetsConfig: metadata?.filter_sets_configuration || [],
  });

  if (!metadata) {
    metadata = {};
  }

  metadata.show_native_filters =
    dashboardData?.metadata?.show_native_filters ??
    isFeatureEnabled(FeatureFlag.DASHBOARD_NATIVE_FILTERS);

  if (isFeatureEnabled(FeatureFlag.DASHBOARD_CROSS_FILTERS)) {
    // If user just added cross filter to dashboard it's not saving it scope on server,
    // so we tweak it until user will update scope and will save it in server
    Object.values(dashboardLayout.present).forEach(layoutItem => {
      const chartId = layoutItem.meta?.chartId;
      const behaviors =
        (
          getChartMetadataRegistry().get(
            chartQueries[chartId]?.formData?.viz_type,
          ) ?? {}
        )?.behaviors ?? [];

      if (!metadata.chart_configuration) {
        metadata.chart_configuration = {};
      }
      if (
        behaviors.includes(Behavior.INTERACTIVE_CHART) &&
        !metadata.chart_configuration[chartId]
      ) {
        metadata.chart_configuration[chartId] = {
          id: chartId,
          crossFilters: {
            scope: {
              rootPath: [DASHBOARD_ROOT_ID],
              excluded: [chartId], // By default it doesn't affects itself
            },
          },
        };
      }
    });
  }

  const { roles } = user;
  const canEdit = canUserEditDashboard(dashboardData, user);

  return dispatch({
    type: HYDRATE_DASHBOARD,
    data: {
      sliceEntities: { ...initSliceEntities, slices, isLoading: false },
      charts: chartQueries,
      // read-only data
      dashboardInfo: {
        ...dashboardData,
        metadata,
        userId: user.userId ? String(user.userId) : null, // legacy, please use state.user instead
        dash_edit_perm: canEdit,
        dash_save_perm: findPermission('can_save_dash', 'Superset', roles),
        dash_share_perm: findPermission(
          'can_share_dashboard',
          'Superset',
          roles,
        ),
        superset_can_explore: findPermission('can_explore', 'Superset', roles),
        superset_can_share: findPermission(
          'can_share_chart',
          'Superset',
          roles,
        ),
        superset_can_csv: findPermission('can_csv', 'Superset', roles),
        slice_can_edit: findPermission('can_slice', 'Superset', roles),
        common: {
          // legacy, please use state.common instead
          flash_messages: common.flash_messages,
          conf: common.conf,
        },
      },
      dashboardFilters,
      nativeFilters,
      dashboardState: {
        preselectNativeFilters: getUrlParam(URL_PARAMS.nativeFilters),
        sliceIds: Array.from(sliceIds),
        directPathToChild,
        directPathLastUpdated: Date.now(),
        focusedFilterField: null,
        expandedSlices: metadata?.expanded_slices || {},
        refreshFrequency: metadata?.refresh_frequency || 0,
        // dashboard viewers can set refresh frequency for the current visit,
        // only persistent refreshFrequency will be saved to backend
        shouldPersistRefreshFrequency: false,
        css: dashboardData.css || '',
        colorNamespace: metadata?.color_namespace || null,
        colorScheme: metadata?.color_scheme || null,
        editMode: canEdit && editMode,
        isPublished: dashboardData.published,
        hasUnsavedChanges: false,
        maxUndoHistoryExceeded: false,
        lastModifiedTime: dashboardData.changed_on,
        isRefreshing: false,
        activeTabs: [],
      },
      dashboardLayout,
    },
  });
};
<|endoftext|>


<commit_before>import React, { Component, PropTypes } from "react";
import { Glyphicon } from "react-bootstrap";
import DateTimePickerMinutes from "./components/DateTimePickerMinutes";
import DateTimePickerHours from "./components/DateTimePickerHours";
import DateTimePickerHoursSide from './components/DateTimePickerHoursSide';
import Constants from "./constants/Constants.js";

export default class Timepicker extends Component {
  static propTypes = {
    setSelectedHour: PropTypes.func.isRequired,
    setSelectedMinute: PropTypes.func.isRequired,
    subtractHour: PropTypes.func.isRequired,
    addHour: PropTypes.func.isRequired,
    subtractMinute: PropTypes.func.isRequired,
    addMinute: PropTypes.func.isRequired,
    viewDate: PropTypes.object.isRequired,
    selectedDate: PropTypes.object.isRequired,
    togglePeriod: PropTypes.func.isRequired,
    mode: PropTypes.oneOf([
      Constants.MODE_DATE,
      Constants.MODE_DATETIME,
      Constants.MODE_TIME,
      Constants.MODE_DATETIME_SIDE
    ])
  }

  state = {
    minutesDisplayed: false,
    hoursDisplayed: false
  }

  goBack = () => {
    return this.setState({
      minutesDisplayed: false,
      hoursDisplayed: false
    });
  }

  showMinutes = () => {
    return this.setState({
      minutesDisplayed: true
    });
  }

  showHours = () => {
    return this.setState({
      hoursDisplayed: true
    });
  }

  renderMinutes = () => {
    if (this.state.minutesDisplayed) {
      return <DateTimePickerMinutes {...this.props} onSwitch={this.goBack} />;
    } else {
      return null;
    }
  }

  renderHours = () => {
    if (this.state.hoursDisplayed) {
      return <DateTimePickerHours {...this.props} onSwitch={this.goBack} />;
    } else {
      return null;
    }
  }

  renderPicker = () => {
    if (!this.state.minutesDisplayed && !this.state.hoursDisplayed) {
      return (

              <Glyphicon glyph="chevron-up" />

              <Glyphicon glyph="chevron-up" />

              {this.props.selectedDate.format("h")}

              :

              {this.props.selectedDate.format("mm")}

              <button className="btn btn-primary" onClick={this.props.togglePeriod} type="button">{this.props.selectedDate.format("A")}</button>

              <Glyphicon glyph="chevron-down" />

              <Glyphicon glyph="chevron-down" />

      );
    } else {
      return "";
    }
  }

  render() {
    return (

          {this.renderPicker()}

          {this.renderHours()}

          {this.renderMinutes()}

    );
  }
}
<commit_msg>formatting<commit_after>import React, { Component, PropTypes } from "react";
import { Glyphicon } from "react-bootstrap";
import DateTimePickerMinutes from "./components/DateTimePickerMinutes";
import DateTimePickerHours from "./components/DateTimePickerHours";
import DateTimePickerHoursSide from './components/DateTimePickerHoursSide';
import Constants from "./constants/Constants.js";

export default class Timepicker extends Component {
  static propTypes = {
    setSelectedHour: PropTypes.func.isRequired,
    setSelectedMinute: PropTypes.func.isRequired,
    subtractHour: PropTypes.func.isRequired,
    addHour: PropTypes.func.isRequired,
    subtractMinute: PropTypes.func.isRequired,
    addMinute: PropTypes.func.isRequired,
    viewDate: PropTypes.object.isRequired,
    selectedDate: PropTypes.object.isRequired,
    togglePeriod: PropTypes.func.isRequired,
    mode: PropTypes.oneOf([
      Constants.MODE_DATE,
      Constants.MODE_DATETIME,
      Constants.MODE_TIME,
      Constants.MODE_DATETIME_SIDE
    ])
  }

  state = {
    minutesDisplayed: false,
    hoursDisplayed: false
  }

  goBack = () => {
    return this.setState({
      minutesDisplayed: false,
      hoursDisplayed: false
    });
  }

  showMinutes = () => {
    return this.setState({
      minutesDisplayed: true
    });
  }

  showHours = () => {
    return this.setState({
      hoursDisplayed: true
    });
  }

  renderMinutes = () => {
    if (this.state.minutesDisplayed) {
      return <DateTimePickerMinutes {...this.props} onSwitch={this.goBack} />;
    } else {
      return null;
    }
  }

  renderHours = () => {
    if (this.state.hoursDisplayed) {
      return <DateTimePickerHours {...this.props} onSwitch={this.goBack} />;
    } else {
      return null;
    }
  }

  renderPicker = () => {
    if (!this.state.minutesDisplayed && !this.state.hoursDisplayed) {
      return (

              <Glyphicon glyph="chevron-up" />

              <Glyphicon glyph="chevron-up" />

              {this.props.selectedDate.format("h")}
              :
              {this.props.selectedDate.format("mm")}

              <button className="btn btn-primary" onClick={this.props.togglePeriod} type="button">{this.props.selectedDate.format("A")}</button>

              <Glyphicon glyph="chevron-down" />

              <Glyphicon glyph="chevron-down" />

      );
    } else {
      return "";
    }
  }

  render() {
    return (

          {this.renderPicker()}
          {this.renderHours()}
          {this.renderMinutes()}

    );
  }
}
<|endoftext|>


<commit_before>var TwitterStrategy  = require('passport-twitter').Strategy;
//var User = require('../models/user');
var twitterConfig = require('../twitter.js');

module.exports = function(passport) {
    console.log("twitter - passport");
    passport.use('twitter', new TwitterStrategy({
        consumerKey     : twitterConfig.apikey,
        consumerSecret  : twitterConfig.apisecret,
        callbackURL     : twitterConfig.callbackURL
    },
    function(token, tokenSecret, profile, done) {

      // make the code asynchronous
      // User.findOne won't fire until we have all our data back from Twitter
      console.log("Here we are");

    	process.nextTick(function() {
        cognito.login(token, tokenSecret);
        /*
	        User.findOne({ 'twitter.id' : profile.id }, function(err, user) {

	       	 	// if there is an error, stop everything and return that
		        // ie an error connecting to the database
	            if (err)
	                return done(err);

				// if the user is found then log them in
	            if (user) {
	                return done(null, user); // user found, return that user
	            } else {
	                // if there is no user, create them
	                var newUser                 = new User();

					// set all of the user data that we need
	                newUser.twitter.id          = profile.id;
	                newUser.twitter.token       = token;
	                newUser.twitter.username = profile.username;
	                newUser.twitter.displayName = profile.displayName;
	                newUser.twitter.lastStatus = profile._json.status.text;

					// save our user into the database
	                newUser.save(function(err) {
	                    if (err)
	                        throw err;
	                    return done(null, newUser);
	                });
	            }
	        });
*/
		});

    }));

};
<commit_msg>Test7<commit_after>var TwitterStrategy  = require('passport-twitter').Strategy;
//var User = require('../models/user');
var twitterConfig = require('../twitter.js');
var cognito = require('../lib/cognito');

module.exports = function(passport) {
    console.log("twitter - passport");
    passport.use('twitter', new TwitterStrategy({
        consumerKey     : twitterConfig.apikey,
        consumerSecret  : twitterConfig.apisecret,
        callbackURL     : twitterConfig.callbackURL
    },
    function(token, tokenSecret, profile, done) {

      // make the code asynchronous
      // User.findOne won't fire until we have all our data back from Twitter
      console.log("Here we are");

    	process.nextTick(function() {
        cognito.login(token, tokenSecret);
        /*
	        User.findOne({ 'twitter.id' : profile.id }, function(err, user) {

	       	 	// if there is an error, stop everything and return that
		        // ie an error connecting to the database
	            if (err)
	                return done(err);

				// if the user is found then log them in
	            if (user) {
	                return done(null, user); // user found, return that user
	            } else {
	                // if there is no user, create them
	                var newUser                 = new User();

					// set all of the user data that we need
	                newUser.twitter.id          = profile.id;
	                newUser.twitter.token       = token;
	                newUser.twitter.username = profile.username;
	                newUser.twitter.displayName = profile.displayName;
	                newUser.twitter.lastStatus = profile._json.status.text;

					// save our user into the database
	                newUser.save(function(err) {
	                    if (err)
	                        throw err;
	                    return done(null, newUser);
	                });
	            }
	        });
*/
		});

    }));

};
<|endoftext|>


<commit_before><commit_msg>whitespace cleanup<commit_after><|endoftext|>