<commit_before>/**
 * @fileoverview Registrator Agent
 */

/**
 * @augments JsSIP
 * @class Class creating a registrator agent.
 * @param {JsSIP.UA} ua
 * @param {JsSIP.Transport} transport
 */
(function(JsSIP) {
var Registrator;

Registrator = function(ua, transport) {
  var reg_id=1; //Force reg_id to 1.

  this.logger = ua.getLogger('jssip.registrator');

  this.ua = ua;
  this.transport = transport;

  this.registrar = ua.configuration.registrar_server;
  this.expires = ua.configuration.register_expires;

  // Call-ID and CSeq values RFC3261 10.2
  this.call_id = JsSIP.Utils.createRandomToken(22);
  this.cseq = 0;

  // this.to_uri
  this.to_uri = ua.configuration.uri;

  this.registrationTimer = null;

  // Set status
  this.registered = this.registered_before = false;

  // Save into ua instance
  this.ua.registrator = this;

  // Contact header
  this.contact = this.ua.contact.toString();

  // sip.ice media feature tag (RFC 5768)
  this.contact += ';+sip.ice';

  this.extraHeaders = [];

  if(reg_id) {
    this.contact += ';reg-id='+ reg_id;
    this.contact += ';+sip.instance="<urn:uuid:'+ this.ua.configuration.instance_id+'>"';
  }
};

Registrator.prototype = {
  /**
   * @param {Object} [options]
   */
  register: function(options) {
    var request_sender, cause, extraHeaders,
      self = this;

    options = options || {};

    if (options.extraHeaders && Object.keys(options.extraHeaders).length !== 0) {
      this.extraHeaders = options.extraHeaders && options.extraHeaders.slice();
    }

    extraHeaders = this.extraHeaders.slice();
    extraHeaders.push('Contact: '+ this.contact + ';expires=' + this.expires);
    extraHeaders.push('Expires: '+ this.expires);

    this.request = new JsSIP.OutgoingRequest(JsSIP.C.REGISTER, this.registrar, this.ua, {
        'to_uri': this.to_uri,
        'call_id': this.call_id,
        'cseq': (this.cseq += 1)
      }, extraHeaders);

    request_sender = new JsSIP.RequestSender(this, this.ua);

    /**
    * @private
    */
    this.receiveResponse = function(response) {
      var contact, expires,
        contacts = response.getHeaders('contact').length;

      // Discard responses to older REGISTER/un-REGISTER requests.
      if(response.cseq !== this.cseq) {
        return;
      }

      // Clear registration timer
      if (this.registrationTimer !== null) {
        window.clearTimeout(this.registrationTimer);
        this.registrationTimer = null;
      }

      switch(true) {
        case /^1[0-9]{2}$/.test(response.status_code):
          // Ignore provisional responses.
          break;
        case /^2[0-9]{2}$/.test(response.status_code):
          if(response.hasHeader('expires')) {
            expires = response.getHeader('expires');
          }

          // Search the Contact pointing to us and update the expires value accordingly.
          if (!contacts) {
            this.logger.warn('no Contact header in response to REGISTER, response ignored');
            break;
          }

          while(contacts--) {
            contact = response.parseHeader('contact', contacts);
            if(contact.uri.user === this.ua.contact.uri.user) {
              expires = contact.getParam('expires');
              break;
            } else {
              contact = null;
            }
          }

          if (!contact) {
            this.logger.warn('no Contact header pointing to us, response ignored');
            break;
          }

          if(!expires) {
            expires = this.expires;
          }

          // Re-Register before the expiration interval has elapsed.
          // For that, decrease the expires value. ie: 3 seconds
          this.registrationTimer = window.setTimeout(function() {
            self.registrationTimer = null;
            self.register();
          }, (expires * 1000) - 3000);

          //Save gruu values
          if (contact.hasParam('temp-gruu')) {
            this.ua.contact.temp_gruu = contact.getParam('temp-gruu').replace(/"/g,'');
          }
          if (contact.hasParam('pub-gruu')) {
            this.ua.contact.pub_gruu = contact.getParam('pub-gruu').replace(/"/g,'');
          }

          this.ua.emit('registered', this.ua, {
            response: response
          });
          this.registered = true;
          break;
        // Interval too brief RFC3261 10.2.8
        case /^423$/.test(response.status_code):
          if(response.hasHeader('min-expires')) {
            // Increase our registration interval to the suggested minimum
            this.expires = response.getHeader('min-expires');
            // Attempt the registration again immediately
            this.register();
          } else { //This response MUST contain a Min-Expires header field
            this.logger.warn('423 response received for REGISTER without Min-Expires');
            this.registrationFailure(response, JsSIP.C.causes.SIP_FAILURE_CODE);
          }
          break;
        default:
          cause = JsSIP.Utils.sipErrorCause(response.status_code);
          this.registrationFailure(response, cause);
      }
    };

    /**
    * @private
    */
    this.onRequestTimeout = function() {
      this.registrationFailure(null, JsSIP.C.causes.REQUEST_TIMEOUT);
    };

    /**
    * @private
    */
    this.onTransportError = function() {
      this.registrationFailure(null, JsSIP.C.causes.CONNECTION_ERROR);
    };

    request_sender.send();
  },

  /**
  * @param {Object} [options]
  */
  unregister: function(options) {
    var extraHeaders;

    if(!this.registered) {
      this.logger.warn('already unregistered');
      return;
    }

    options = options || {};

    if (options.extraHeaders && Object.keys(options.extraHeaders).length !== 0) {
      this.extraHeaders = options.extraHeaders && options.extraHeaders.slice();
    }

    extraHeaders = this.extraHeaders.slice();

    this.registered = false;

    // Clear the registration timer.
    if (this.registrationTimer !== null) {
      window.clearTimeout(this.registrationTimer);
      this.registrationTimer = null;
    }

    if(options.all) {
      extraHeaders.push('Contact: *');
      extraHeaders.push('Expires: 0');

      this.request = new JsSIP.OutgoingRequest(JsSIP.C.REGISTER, this.registrar, this.ua, {
          'to_uri': this.to_uri,
          'call_id': this.call_id,
          'cseq': (this.cseq += 1)
        }, extraHeaders);
    } else {
      extraHeaders.push('Contact: '+ this.contact + ';expires=0');
      extraHeaders.push('Expires: 0');

      this.request = new JsSIP.OutgoingRequest(JsSIP.C.REGISTER, this.registrar, this.ua, {
          'to_uri': this.to_uri,
          'call_id': this.call_id,
          'cseq': (this.cseq += 1)
        }, extraHeaders);
    }

    var request_sender = new JsSIP.RequestSender(this, this.ua);

    /**
    * @private
    */
    this.receiveResponse = function(response) {
      var cause;

      switch(true) {
        case /^1[0-9]{2}$/.test(response.status_code):
          // Ignore provisional responses.
          break;
        case /^2[0-9]{2}$/.test(response.status_code):
          this.unregistered(response);
          break;
        default:
          cause = JsSIP.Utils.sipErrorCause(response.status_code);
          this.unregistered(response, cause);
      }
    };

    /**
    * @private
    */
    this.onRequestTimeout = function() {
      this.unregistered(null, JsSIP.C.causes.REQUEST_TIMEOUT);
    };

    /**
    * @private
    */
    this.onTransportError = function() {
      this.unregistered(null, JsSIP.C.causes.CONNECTION_ERROR);
    };

    request_sender.send();
  },

  /**
  * @private
  */
  registrationFailure: function(response, cause) {
    this.ua.emit('registrationFailed', this.ua, {
      response: response || null,
      cause: cause
    });

    if (this.registered) {
      this.ua.emit('unregistered', this.ua, {
        response: response || null,
        cause: cause
      });
      this.registered = false;
    }
  },

  /**
   * @private
   */
  unregistered: function(response, cause) {
    this.ua.emit('unregistered', this.ua, {
      response: response || null,
      cause: cause || null
    });
    this.registered = false;
  },

  /**
  * @private
  */
  onTransportClosed: function() {
    this.registered_before = this.registered;
    if (this.registrationTimer !== null) {
      window.clearTimeout(this.registrationTimer);
      this.registrationTimer = null;
    }

    if(this.registered) {
      this.ua.emit('unregistered', this.ua);
      this.registered = false;
    }
  },

  /**
  * @private
  */
  onTransportConnected: function() {
    this.register();
  },

  /**
  * @private
  */
  close: function() {
    this.registered_before = this.registered;
    this.unregister();
  }
};

JsSIP.Registrator = Registrator;
}(JsSIP));
<commit_msg>Don't emit 'registered' if already registered.<commit_after>/**
 * @fileoverview Registrator Agent
 */

/**
 * @augments JsSIP
 * @class Class creating a registrator agent.
 * @param {JsSIP.UA} ua
 * @param {JsSIP.Transport} transport
 */
(function(JsSIP) {
var Registrator;

Registrator = function(ua, transport) {
  var reg_id=1; //Force reg_id to 1.

  this.logger = ua.getLogger('jssip.registrator');

  this.ua = ua;
  this.transport = transport;

  this.registrar = ua.configuration.registrar_server;
  this.expires = ua.configuration.register_expires;

  // Call-ID and CSeq values RFC3261 10.2
  this.call_id = JsSIP.Utils.createRandomToken(22);
  this.cseq = 0;

  // this.to_uri
  this.to_uri = ua.configuration.uri;

  this.registrationTimer = null;

  // Set status
  this.registered = this.registered_before = false;

  // Save into ua instance
  this.ua.registrator = this;

  // Contact header
  this.contact = this.ua.contact.toString();

  // sip.ice media feature tag (RFC 5768)
  this.contact += ';+sip.ice';

  this.extraHeaders = [];

  if(reg_id) {
    this.contact += ';reg-id='+ reg_id;
    this.contact += ';+sip.instance="<urn:uuid:'+ this.ua.configuration.instance_id+'>"';
  }
};

Registrator.prototype = {
  /**
   * @param {Object} [options]
   */
  register: function(options) {
    var request_sender, cause, extraHeaders,
      self = this;

    options = options || {};

    if (options.extraHeaders && Object.keys(options.extraHeaders).length !== 0) {
      this.extraHeaders = options.extraHeaders && options.extraHeaders.slice();
    }

    extraHeaders = this.extraHeaders.slice();
    extraHeaders.push('Contact: '+ this.contact + ';expires=' + this.expires);
    extraHeaders.push('Expires: '+ this.expires);

    this.request = new JsSIP.OutgoingRequest(JsSIP.C.REGISTER, this.registrar, this.ua, {
        'to_uri': this.to_uri,
        'call_id': this.call_id,
        'cseq': (this.cseq += 1)
      }, extraHeaders);

    request_sender = new JsSIP.RequestSender(this, this.ua);

    /**
    * @private
    */
    this.receiveResponse = function(response) {
      var contact, expires,
        contacts = response.getHeaders('contact').length;

      // Discard responses to older REGISTER/un-REGISTER requests.
      if(response.cseq !== this.cseq) {
        return;
      }

      // Clear registration timer
      if (this.registrationTimer !== null) {
        window.clearTimeout(this.registrationTimer);
        this.registrationTimer = null;
      }

      switch(true) {
        case /^1[0-9]{2}$/.test(response.status_code):
          // Ignore provisional responses.
          break;
        case /^2[0-9]{2}$/.test(response.status_code):
          if(response.hasHeader('expires')) {
            expires = response.getHeader('expires');
          }

          // Search the Contact pointing to us and update the expires value accordingly.
          if (!contacts) {
            this.logger.warn('no Contact header in response to REGISTER, response ignored');
            break;
          }

          while(contacts--) {
            contact = response.parseHeader('contact', contacts);
            if(contact.uri.user === this.ua.contact.uri.user) {
              expires = contact.getParam('expires');
              break;
            } else {
              contact = null;
            }
          }

          if (!contact) {
            this.logger.warn('no Contact header pointing to us, response ignored');
            break;
          }

          if(!expires) {
            expires = this.expires;
          }

          // Re-Register before the expiration interval has elapsed.
          // For that, decrease the expires value. ie: 3 seconds
          this.registrationTimer = window.setTimeout(function() {
            self.registrationTimer = null;
            self.register();
          }, (expires * 1000) - 3000);

          //Save gruu values
          if (contact.hasParam('temp-gruu')) {
            this.ua.contact.temp_gruu = contact.getParam('temp-gruu').replace(/"/g,'');
          }
          if (contact.hasParam('pub-gruu')) {
            this.ua.contact.pub_gruu = contact.getParam('pub-gruu').replace(/"/g,'');
          }

          if (! this.registered) {
            this.registered = true;
            this.ua.emit('registered', this.ua, {
              response: response
            });
          }
          break;
        // Interval too brief RFC3261 10.2.8
        case /^423$/.test(response.status_code):
          if(response.hasHeader('min-expires')) {
            // Increase our registration interval to the suggested minimum
            this.expires = response.getHeader('min-expires');
            // Attempt the registration again immediately
            this.register();
          } else { //This response MUST contain a Min-Expires header field
            this.logger.warn('423 response received for REGISTER without Min-Expires');
            this.registrationFailure(response, JsSIP.C.causes.SIP_FAILURE_CODE);
          }
          break;
        default:
          cause = JsSIP.Utils.sipErrorCause(response.status_code);
          this.registrationFailure(response, cause);
      }
    };

    /**
    * @private
    */
    this.onRequestTimeout = function() {
      this.registrationFailure(null, JsSIP.C.causes.REQUEST_TIMEOUT);
    };

    /**
    * @private
    */
    this.onTransportError = function() {
      this.registrationFailure(null, JsSIP.C.causes.CONNECTION_ERROR);
    };

    request_sender.send();
  },

  /**
  * @param {Object} [options]
  */
  unregister: function(options) {
    var extraHeaders;

    if(!this.registered) {
      this.logger.warn('already unregistered');
      return;
    }

    options = options || {};

    if (options.extraHeaders && Object.keys(options.extraHeaders).length !== 0) {
      this.extraHeaders = options.extraHeaders && options.extraHeaders.slice();
    }

    extraHeaders = this.extraHeaders.slice();

    this.registered = false;

    // Clear the registration timer.
    if (this.registrationTimer !== null) {
      window.clearTimeout(this.registrationTimer);
      this.registrationTimer = null;
    }

    if(options.all) {
      extraHeaders.push('Contact: *');
      extraHeaders.push('Expires: 0');

      this.request = new JsSIP.OutgoingRequest(JsSIP.C.REGISTER, this.registrar, this.ua, {
          'to_uri': this.to_uri,
          'call_id': this.call_id,
          'cseq': (this.cseq += 1)
        }, extraHeaders);
    } else {
      extraHeaders.push('Contact: '+ this.contact + ';expires=0');
      extraHeaders.push('Expires: 0');

      this.request = new JsSIP.OutgoingRequest(JsSIP.C.REGISTER, this.registrar, this.ua, {
          'to_uri': this.to_uri,
          'call_id': this.call_id,
          'cseq': (this.cseq += 1)
        }, extraHeaders);
    }

    var request_sender = new JsSIP.RequestSender(this, this.ua);

    /**
    * @private
    */
    this.receiveResponse = function(response) {
      var cause;

      switch(true) {
        case /^1[0-9]{2}$/.test(response.status_code):
          // Ignore provisional responses.
          break;
        case /^2[0-9]{2}$/.test(response.status_code):
          this.unregistered(response);
          break;
        default:
          cause = JsSIP.Utils.sipErrorCause(response.status_code);
          this.unregistered(response, cause);
      }
    };

    /**
    * @private
    */
    this.onRequestTimeout = function() {
      this.unregistered(null, JsSIP.C.causes.REQUEST_TIMEOUT);
    };

    /**
    * @private
    */
    this.onTransportError = function() {
      this.unregistered(null, JsSIP.C.causes.CONNECTION_ERROR);
    };

    request_sender.send();
  },

  /**
  * @private
  */
  registrationFailure: function(response, cause) {
    this.ua.emit('registrationFailed', this.ua, {
      response: response || null,
      cause: cause
    });

    if (this.registered) {
      this.registered = false;
      this.ua.emit('unregistered', this.ua, {
        response: response || null,
        cause: cause
      });
    }
  },

  /**
   * @private
   */
  unregistered: function(response, cause) {
    this.registered = false;
    this.ua.emit('unregistered', this.ua, {
      response: response || null,
      cause: cause || null
    });
  },

  /**
  * @private
  */
  onTransportClosed: function() {
    this.registered_before = this.registered;
    if (this.registrationTimer !== null) {
      window.clearTimeout(this.registrationTimer);
      this.registrationTimer = null;
    }

    if(this.registered) {
      this.registered = false;
      this.ua.emit('unregistered', this.ua);
    }
  },

  /**
  * @private
  */
  onTransportConnected: function() {
    this.register();
  },

  /**
  * @private
  */
  close: function() {
    this.registered_before = this.registered;
    this.unregister();
  }
};

JsSIP.Registrator = Registrator;
}(JsSIP));
<|endoftext|>


<commit_before>'use strict'

/*
 * adonis-framework
 *
 * (c) Harminder Virk <virk@adonisjs.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
*/

const Macroable = require('macroable')

/**
 * Route Group class is used to group routes with
 * common behavior. For example prefixing a bunch
 * of routes or applying middleware to a bunch
 * of routes.
 *
 * An instance of group is obtained by calling the
 * `Route.group` method on @ref('RouteManager')
 * class.
 *
 * @class RouteGroup
 * @group Http
 * @constructor
 *
 * @example
 * ```js
 * const group = new RouteGroup([arrayOfRoutes], optionalName)
 * ```
 */
class RouteGroup extends Macroable {
  constructor (routes, name = null) {
    super()
    this._routes = routes
    this._name = name
  }

  /**
   * Add middleware to a group of routes.
   * Also see @ref('Route/middleware').
   *
   * @method middleware
   *
   * @param  {Array|String|Spread}   middleware
   *
   * @chainable
   *
   * @example
   * ```js
   * Route
   *   .group()
   *   .middleware('auth')
   * ```
   */
  middleware (...middleware) {
    this._routes.forEach((route) => route.prependMiddleware(...middleware))
  }

  /**
   * Add formats to a group of routes.
   * Also see @ref('Route/formats')
   *
   * @method formats
   *
   * @param  {Array}   formats
   * @param  {Boolean} [strict = false]
   *
   * @chainable
   *
   * @example
   * ```js
   * Route
   *   .group()
   *   .formats(['json', 'html'])
   * ```
   */
  formats (formats, strict = false) {
    this._routes.forEach((route) => route.formats(formats, strict))
    return this
  }

  /**
   * Prefix group of routes.
   * Also see @ref('Route/prefix')
   *
   * @method prefix
   *
   * @param  {String} prefix
   *
   * @chainable
   *
   * @example
   * ```js
   * Route
   *   .group()
   *   .prefix('api/v1')
   * ```
   */
  prefix (prefix) {
    this._routes.forEach((route) => route.prefix(prefix))
    return this
  }

  /**
   * Add domain to a group of routes.
   * Also see @ref('Route/domain')
   *
   * @method domain
   *
   * @param  {String} domain
   *
   * @chainable
   *
   * @example
   * ```js
   * Route
   *   .group()
   *   .domain('blog.adonisjs.com')
   * ```
   */
  domain (domain) {
    this._routes.forEach((route) => route.domain(domain))
    return this
  }
}

/**
 * Defining _macros and _getters property
 * for Macroable class
 *
 * @type {Object}
 */
RouteGroup._macros = {}
RouteGroup._getters = {}

module.exports = RouteGroup
<commit_msg>fix(route): group middleware return this for chainable api<commit_after>'use strict'

/*
 * adonis-framework
 *
 * (c) Harminder Virk <virk@adonisjs.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
*/

const Macroable = require('macroable')

/**
 * Route Group class is used to group routes with
 * common behavior. For example prefixing a bunch
 * of routes or applying middleware to a bunch
 * of routes.
 *
 * An instance of group is obtained by calling the
 * `Route.group` method on @ref('RouteManager')
 * class.
 *
 * @class RouteGroup
 * @group Http
 * @constructor
 *
 * @example
 * ```js
 * const group = new RouteGroup([arrayOfRoutes], optionalName)
 * ```
 */
class RouteGroup extends Macroable {
  constructor (routes, name = null) {
    super()
    this._routes = routes
    this._name = name
  }

  /**
   * Add middleware to a group of routes.
   * Also see @ref('Route/middleware').
   *
   * @method middleware
   *
   * @param  {Array|String|Spread}   middleware
   *
   * @chainable
   *
   * @example
   * ```js
   * Route
   *   .group()
   *   .middleware('auth')
   * ```
   */
  middleware (...middleware) {
    this._routes.forEach((route) => route.prependMiddleware(...middleware))
    return this
  }

  /**
   * Add formats to a group of routes.
   * Also see @ref('Route/formats')
   *
   * @method formats
   *
   * @param  {Array}   formats
   * @param  {Boolean} [strict = false]
   *
   * @chainable
   *
   * @example
   * ```js
   * Route
   *   .group()
   *   .formats(['json', 'html'])
   * ```
   */
  formats (formats, strict = false) {
    this._routes.forEach((route) => route.formats(formats, strict))
    return this
  }

  /**
   * Prefix group of routes.
   * Also see @ref('Route/prefix')
   *
   * @method prefix
   *
   * @param  {String} prefix
   *
   * @chainable
   *
   * @example
   * ```js
   * Route
   *   .group()
   *   .prefix('api/v1')
   * ```
   */
  prefix (prefix) {
    this._routes.forEach((route) => route.prefix(prefix))
    return this
  }

  /**
   * Add domain to a group of routes.
   * Also see @ref('Route/domain')
   *
   * @method domain
   *
   * @param  {String} domain
   *
   * @chainable
   *
   * @example
   * ```js
   * Route
   *   .group()
   *   .domain('blog.adonisjs.com')
   * ```
   */
  domain (domain) {
    this._routes.forEach((route) => route.domain(domain))
    return this
  }
}

/**
 * Defining _macros and _getters property
 * for Macroable class
 *
 * @type {Object}
 */
RouteGroup._macros = {}
RouteGroup._getters = {}

module.exports = RouteGroup
<|endoftext|>


<commit_before>/**
 * Created by Gal on 21/10/2017.
 */

import React from 'react';
import PropTypes from 'prop-types'
import {StyleSheet, Text, Image, View, Dimensions, Animated} from 'react-native';

const dimensions = Dimensions.get('window');
const moveZero = new Animated.Value(0);
const opacityOne = new Animated.Value(1);

const animate = (duration, direction, withFadeOut) => {
    let toValue;
    let animations = [];
    let durationClone = Number(duration || 3000); // without cloning the number the animation goes crazy when it ends

    switch (direction) {
        case "left":
            toValue = -dimensions.width;
            break;
        case "right":
            toValue = dimensions.width;
            break;
        case "down":
            toValue = dimensions.height;
            break;
        case "up":
        default:
            toValue = -dimensions.height;
            break;
    }

    let moveAnimation = Animated.timing(moveZero, {
        toValue,
        duration: durationClone
    });

    animations.push(moveAnimation);

    if (withFadeOut) {
        let fadeAnimation = Animated.timing(opacityOne, {toValue: 0, duration: durationClone});
        animations.push(fadeAnimation);
    }

    Animated.parallel(animations).start();
};

const selectContent = (imageSource, text) => {
    let content;

    if (imageSource) {
        content = <Image source={imageSource} style={{height: '100%', width: '100%'}}/>;
    } else {
        content = <Text>{text || 'provide imageSource or text'}</Text>;
    }

    return content;
};

const getAnimationBaseStyle = (direction, withFadeOut) => {
    let styleObj = withFadeOut ? {opacity: opacityOne} : {};
    return ['left', 'right'].indexOf(direction) > -1 ? Object.assign(styleObj, {left: moveZero}) : Object.assign(styleObj, {top: moveZero});
};

const styles = StyleSheet.create({
    container: {
        flex: 1
    },
    splash: {
        position: 'absolute'
    }
});

export const SplashedApp = ({imageSource, text, direction, children, duration, withFadeOut, baseColor}) => {
    setTimeout(() => animate(duration, direction, withFadeOut), 2000);

    return (
        <View style={styles.container}>
            {children}
            <Animated.View
                style={[styles.container, styles.splash, {backgroundColor: baseColor || 'lightgray'}, getAnimationBaseStyle(direction, withFadeOut)]}>
                {selectContent(imageSource, text)}
            </Animated.View>
        </View>
    );
};

SplashedApp.PropTypes = {
    imageSource: PropTypes.string,
    text: PropTypes.string,
    direction: PropTypes.string,
    baseColor: PropTypes.string,
    children: PropTypes.object,
    duration: PropTypes.number,
    withFadeOut: PropTypes.bool
};

export default SplashedApp;

<commit_msg>bug fix<commit_after>/**
 * Created by Gal on 21/10/2017.
 */

import React from 'react';
import PropTypes from 'prop-types'
import {StyleSheet, Text, Image, View, Dimensions, Animated} from 'react-native';

const dimensions = Dimensions.get('window');
const moveZero = new Animated.Value(0);
const opacityOne = new Animated.Value(1);

const animate = (duration, direction, withFadeOut) => {
    let toValue;
    let animations = [];
    let durationClone = Number(duration || 3000); // without cloning the number the animation goes crazy when it ends

    switch (direction) {
        case "left":
            toValue = -dimensions.width;
            break;
        case "right":
            toValue = dimensions.width;
            break;
        case "down":
            toValue = dimensions.height;
            break;
        case "up":
        default:
            toValue = -dimensions.height;
            break;
    }

    let moveAnimation = Animated.timing(moveZero, {
        toValue,
        duration: durationClone
    });

    animations.push(moveAnimation);

    if (withFadeOut) {
        let fadeAnimation = Animated.timing(opacityOne, {toValue: 0, duration: durationClone});
        animations.push(fadeAnimation);
    }

    Animated.parallel(animations).start();
};

const selectContent = (imageSource, text) => {
    let content;

    if (imageSource) {
        content = <Image source={imageSource} style={styles.spread}/>;
    } else {
        content = <Text>{text || 'provide imageSource or text'}</Text>;
    }

    return content;
};

const getAnimationBaseStyle = (direction, withFadeOut) => {
    let styleObj = withFadeOut ? {opacity: opacityOne} : {};
    return ['left', 'right'].indexOf(direction) > -1 ? Object.assign(styleObj, {left: moveZero}) : Object.assign(styleObj, {top: moveZero});
};

const styles = StyleSheet.create({
    container: {
        flex: 1
    },
    splash: {
        position: 'absolute'
    },
    spread: {
        width: '100%',
        height: '100%'
    }
});

export const SplashedApp = ({imageSource, text, direction, children, duration, withFadeOut, baseColor}) => {
    debugger
    setTimeout(() => animate(duration, direction, withFadeOut), 2000);

    return (
        <View style={styles.container}>
            {children}
            <Animated.View
                style={[styles.spread, styles.splash, {backgroundColor: baseColor || 'lightgray'}, getAnimationBaseStyle(direction, withFadeOut)]}>
                {selectContent(imageSource, text)}
            </Animated.View>
        </View>
    );
};

SplashedApp.PropTypes = {
    imageSource: PropTypes.string,
    text: PropTypes.string,
    direction: PropTypes.string,
    baseColor: PropTypes.string,
    children: PropTypes.object,
    duration: PropTypes.number,
    withFadeOut: PropTypes.bool
};

export default SplashedApp;<|endoftext|>


<commit_before>import React from 'react';
import PropTypes from 'prop-types';

class Spritesheet extends React.Component {
  constructor(props) {
    super(props);
  }

  componentDidMount() {
    this.init();
  }

  init() {
    console.log('let\'s start...');
  }

  renderElements() {
    return

  }

  render() {
    return this.renderElements();
  }
}

export default Spritesheet;
<commit_msg>applying default propTypes<commit_after>import React from 'react';
import PropTypes from 'prop-types';

class Spritesheet extends React.Component {
  constructor(props) {
    super(props);
  }

  componentDidMount() {
    this.init();
  }

  init() {
    console.log('let\'s start...');
  }

  renderElements() {
    return

  }

  render() {
    return this.renderElements();
  }
}

Spritesheet.propTypes = {
  className: PropTypes.string
};

export default Spritesheet;
<|endoftext|>


<commit_before>/*
 * JBoss, Home of Professional Open Source
 * Copyright 2012, Red Hat, Inc., and individual contributors
 * by the @authors tag. See the copyright.txt in the distribution for a
 * full listing of individual contributors.
 *
 * 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.
 */
/*
Unit tests that cover basic functionality of app.js.
 */

module('Member Row Construction');

test('Build 2 Member Rows', function() {
    expect(1);

    var members = [{"email": "jane.doe@company.com", "id": 1, "name": "Jane Doe", "phoneNumber": "12312312311"},{"email": "john.doe@company.com", "id": 0, "name": "John Doe", "phoneNumber": "2125551212"}];

    var html = buildMemberRows(members);

    ok($(html).length == 2, 'Number of rows built: ' + length);
});

test('Build 0 member Rows', function() {
    expect(1);

    var members = [];

    var html = buildMemberRows(members);

    ok($(html).length == 0, 'Created no rows for empty members');
});

module('Member Restful Calls');

asyncTest('Request current member list', function() {
    expect(1);

    $.ajax({
        url: "http://localhost:8080/jboss-as-kitchensink-html5-mobile/rest/members/json",
        dataType: "jsonp",
        jsonp: "jsonpcallback",
        success: function(data) {
            ok($(data).length, "Initial member returned");
            start();
        }
    });
});

test('Register a new member', function() {
    ok(1==1,"TODO");
});

test('Register a member with a duplicate email', function() {
    ok(1==1,"TODO");
});<commit_msg>Update QUnit service test path to the new JSON only based structure<commit_after>/*
 * JBoss, Home of Professional Open Source
 * Copyright 2012, Red Hat, Inc., and individual contributors
 * by the @authors tag. See the copyright.txt in the distribution for a
 * full listing of individual contributors.
 *
 * 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.
 */
/*
Unit tests that cover basic functionality of app.js.
 */

module('Member Row Construction');

test('Build 2 Member Rows', function() {
    expect(1);

    var members = [{"email": "jane.doe@company.com", "id": 1, "name": "Jane Doe", "phoneNumber": "12312312311"},{"email": "john.doe@company.com", "id": 0, "name": "John Doe", "phoneNumber": "2125551212"}];

    var html = buildMemberRows(members);

    ok($(html).length == 2, 'Number of rows built: ' + length);
});

test('Build 0 member Rows', function() {
    expect(1);

    var members = [];

    var html = buildMemberRows(members);

    ok($(html).length == 0, 'Created no rows for empty members');
});

module('Member Restful Calls');

asyncTest('Request current member list', function() {
    expect(1);

    $.ajax({
        url: "http://localhost:8080/jboss-as-kitchensink-html5-mobile/rest/members",
        dataType: "jsonp",
        jsonp: "jsonpcallback",
        success: function(data) {
            ok($(data).length, "Initial member returned");
            start();
        }
    });
});

test('Register a new member', function() {
    ok(1==1,"TODO");
});

test('Register a member with a duplicate email', function() {
    ok(1==1,"TODO");
});<|endoftext|>


<commit_before>/**
 * @file Table component
 * @author liangxiaojun(liangxiaojun@derbysoft.com)
 */

import React, {Component} from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';

import Header from '../_TableHeader';
import Content from '../_TableContent';
import Footer from '../_TableFooter';
import Pagination from '../_TablePagination';
import CircularLoading from '../CircularLoading';

import Theme from '../Theme';
import HorizontalAlign from '../_statics/HorizontalAlign';
import SelectMode from '../_statics/SelectMode';
import SelectAllMode from '../_statics/SelectAllMode';
import SortingType from '../_statics/SortingType';

import Util from '../_vendors/Util';
import Calculation from '../_vendors/Calculation';

class Table extends Component {

    static Theme = Theme;
    static Align = HorizontalAlign;
    static Fixed = HorizontalAlign;
    static SelectMode = SelectMode;
    static SelectAllMode = SelectAllMode;
    static SortingType = SortingType;

    constructor(props, ...restArgs) {

        super(props, ...restArgs);

        this.state = {
            init: props.hasInitFadeOut,
            sorting: props.sorting,
            pagination: props.pagination,
            value: Calculation.getInitValue(props)
        };

    }

    /**
     * keep table loading after do first render
     */
    handleInit = () => {
        this.state.init && this.setState({
            init: false
        });
    };

    /**
     * handle selection change
     */
    handleChange = (value, rowIndex) => {
        this.setState({
            value
        }, () => {
            const {onChange} = this.props;
            onChange && onChange(value, rowIndex);
        });
    };

    /**
     * handle sort change
     */
    handleSortChange = sorting => {
        this.setState({
            sorting
        }, () => {
            const {onSortChange} = this.props;
            onSortChange && onSortChange(sorting);
        });
    };

    /**
     * handle pagination change
     */
    handlePaginationChange = pagination => {
        this.setState({
            pagination
        }, () => {
            const {onPaginationChange} = this.props;
            onPaginationChange && onPaginationChange(pagination);
        });
    };

    render() {

        const {
                className, style,
                isPaginated, pageSizes,
                onSelect, onDeselect, onSelectAll, onDeselectAll,
                ...restProps
            } = this.props,
            {init, sorting, pagination, value} = this.state;

        return (

                {/* table header, display when select */}

                {/* table area */}
                <Content {...restProps}
                         sorting={sorting}
                         pagination={pagination}
                         value={value}
                         isPaginated={isPaginated}
                         onInit={this.handleInit}
                         onChange={this.handleChange}
                         onSelect={onSelect}
                         onDeselect={onDeselect}
                         onSelectAll={onSelectAll}
                         onDeselectAll={onDeselectAll}
                         onSortChange={this.handleSortChange}/>

                {/* table footer */}

                {/* table pagination */}
                {
                    isPaginated ?
                        <Pagination {...restProps}
                                    pagination={pagination}
                                    pageSizes={pageSizes}
                                    value={value}
                                    onChange={this.handlePaginationChange}/>
                        :
                        null
                }

                    {
                        init ?
                            <CircularLoading className="table-init-loading"/>
                            :
                            null
                    }

        );

    }
}

Table.propTypes = {

    /**
     * The CSS class name of the root element.
     */
    className: PropTypes.string,

    /**
     * Override the styles of the root element.
     */
    style: PropTypes.object,

    /**
     * The theme of the table select radio or checkbox.
     */
    selectTheme: PropTypes.oneOf(Util.enumerateValue(Theme)),

    /**
     * The select mode of table.
     */
    selectMode: PropTypes.oneOf(Util.enumerateValue(SelectMode)),

    /**
     * The select all mode of table, all or current page.
     */
    selectAllMode: PropTypes.oneOf(Util.enumerateValue(SelectAllMode)),

    /**
     * Children passed into table header.
     */
    columns: PropTypes.arrayOf(PropTypes.shape({

        /**
         * fixed position of column ( true / 'left' / 'right' )
         */
        fixed: PropTypes.oneOfType([PropTypes.bool, PropTypes.oneOf(Util.enumerateValue(HorizontalAlign))]),

        /**
         * width of column
         */
        width: PropTypes.number,

        /**
         * minimum width of column
         */
        minWidth: PropTypes.number,

        /**
         * The class name of header.
         */
        headClassName: PropTypes.string,

        /**
         * Override the styles of header.
         */
        headStyle: PropTypes.object,

        /**
         * The render content in header.
         * (1) string，example： 'id'
         * (2) callback，example：function (colIndex) {return colIndex;}
         */
        headRenderer: PropTypes.oneOfType([PropTypes.string, PropTypes.func]),

        /**
         * align of table header cell
         */
        headAlign: PropTypes.oneOf(Util.enumerateValue(HorizontalAlign)),

        /**
         * column span of table header
         */
        headSpan: PropTypes.oneOfType([PropTypes.number, PropTypes.func]),

        /**
         * The class name of td.
         */
        bodyClassName: PropTypes.string,

        /**
         * Override the styles of td.
         */
        bodyStyle: PropTypes.object,

        /**
         * The render content in table.
         * (1) data key，example： 'id'
         * (2) data key tamplate，example：'${id} - ${name}'
         * (3) callback，example：function (rowData, rowIndex, colIndex) {return rowData.id;}
         */
        bodyRenderer: PropTypes.oneOfType([PropTypes.string, PropTypes.func]),

        /**
         * align of table body cell
         */
        bodyAlign: PropTypes.oneOf(Util.enumerateValue(HorizontalAlign)),

        /**
         * column span of table body
         */
        bodySpan: PropTypes.oneOfType([PropTypes.number, PropTypes.func]),

        /**
         * The class name of footer.
         */
        footClassName: PropTypes.string,

        /**
         * Override the styles of footer.
         */
        footStyle: PropTypes.object,

        /**
         * The render content in footer.
         * (1) string，example： 'id'
         * (2) callback，example：function (colIndex) {return colIndex;}
         */
        footRenderer: PropTypes.oneOfType([PropTypes.string, PropTypes.func]),

        /**
         * align of table footer cell
         */
        footAlign: PropTypes.oneOf(Util.enumerateValue(HorizontalAlign)),

        /**
         * column span of table foot
         */
        footSpan: PropTypes.oneOfType([PropTypes.number, PropTypes.func]),

        /**
         * If true,this column can be sorted.
         */
        sortable: PropTypes.bool,

        /**
         * Sorting property.
         */
        sortingProp: PropTypes.string,

        defaultSortingType: PropTypes.oneOf(Util.enumerateValue(SortingType))

    })).isRequired,

    data: PropTypes.array,
    idProp: PropTypes.string,
    disabled: PropTypes.bool,
    hasInitFadeOut: PropTypes.bool,

    /**
     * multi select checkbox icon
     */
    checkboxUncheckedIconCls: PropTypes.string,
    checkboxCheckedIconCls: PropTypes.string,
    checkboxIndeterminateIconCls: PropTypes.string,

    /**
     * sorting
     */
    sorting: PropTypes.shape({
        prop: PropTypes.string,
        type: PropTypes.oneOf(Util.enumerateValue(SortingType))
    }),
    defaultSortingType: PropTypes.oneOf(Util.enumerateValue(SortingType)),
    sortingAscIconCls: PropTypes.string,
    sortingDescIconCls: PropTypes.string,
    sortingFunc: PropTypes.func,

    /**
     * pagination
     */
    isPaginated: PropTypes.bool,
    pagination: PropTypes.shape({
        pageSize: PropTypes.number,
        page: PropTypes.number
    }),
    pageSizes: PropTypes.array,
    useFullPagination: PropTypes.bool,

    /**
     * fixed
     */
    isHeadFixed: PropTypes.bool,
    isFootFixed: PropTypes.bool,

    /**
     * scroll
     */
    scroll: PropTypes.shape({
        width: PropTypes.number,
        height: PropTypes.number
    }),

    /**
     * callback
     */
    hasChildren: PropTypes.func,
    onChange: PropTypes.func,
    onSelect: PropTypes.func,
    onDeselect: PropTypes.func,
    onSelectAll: PropTypes.func,
    onDeselectAll: PropTypes.func,
    onSortChange: PropTypes.func,
    onPaginationChange: PropTypes.func

};

Table.defaultProps = {

    selectMode: SelectMode.SINGLE_SELECT,
    selectAllMode: SelectAllMode.CURRENT_PAGE,

    disabled: false,
    hasInitFadeOut: true,

    uncheckedIconCls: 'far fa-square',
    checkedIconCls: 'fas fa-check-square',
    indeterminateIconCls: 'fas fa-minus-square',

    defaultSortingType: SortingType.ASC,
    sortingAscIconCls: 'fas fa-angle-up',
    sortingDescIconCls: 'fas fa-angle-down',

    isPaginated: true,
    pagination: {
        pageSize: 10,
        page: 0
    },
    pageSizes: [5, 10, 15, 20],
    useFullPagination: false,

    isHeadFixed: false,
    isFootFixed: false

};

export default Table;
<commit_msg>update Table<commit_after>/**
 * @file Table component
 * @author liangxiaojun(liangxiaojun@derbysoft.com)
 */

import React, {Component} from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';

import Header from '../_TableHeader';
import Content from '../_TableContent';
import Footer from '../_TableFooter';
import Pagination from '../_TablePagination';
import CircularLoading from '../CircularLoading';

import Theme from '../Theme';
import HorizontalAlign from '../_statics/HorizontalAlign';
import SelectMode from '../_statics/SelectMode';
import SelectAllMode from '../_statics/SelectAllMode';
import SortingType from '../_statics/SortingType';

import Util from '../_vendors/Util';
import Calculation from '../_vendors/Calculation';

class Table extends Component {

    static Theme = Theme;
    static Align = HorizontalAlign;
    static Fixed = HorizontalAlign;
    static SelectMode = SelectMode;
    static SelectAllMode = SelectAllMode;
    static SortingType = SortingType;

    constructor(props, ...restArgs) {

        super(props, ...restArgs);

        this.state = {
            init: props.hasInitFadeOut,
            sorting: props.sorting,
            pagination: props.pagination,
            value: Calculation.getInitValue(props)
        };

    }

    /**
     * keep table loading after do first render
     */
    handleInit = () => {
        this.state.init && this.setState({
            init: false
        });
    };

    /**
     * handle selection change
     */
    handleChange = (value, rowIndex) => {
        this.setState({
            value
        }, () => {
            const {onChange} = this.props;
            onChange && onChange(value, rowIndex);
        });
    };

    /**
     * handle sort change
     */
    handleSortChange = sorting => {
        this.setState({
            sorting
        }, () => {
            const {onSortChange} = this.props;
            onSortChange && onSortChange(sorting);
        });
    };

    /**
     * handle pagination change
     */
    handlePaginationChange = pagination => {
        this.setState({
            pagination
        }, () => {
            const {onPaginationChange} = this.props;
            onPaginationChange && onPaginationChange(pagination);
        });
    };

    render() {

        const {
                className, style,
                isPaginated, pageSizes,
                onSelect, onDeselect, onSelectAll, onDeselectAll,
                ...restProps
            } = this.props,
            {init, sorting, pagination, value} = this.state;

        return (

                {/* table header, display when select */}

                {/* table area */}
                <Content {...restProps}
                         sorting={sorting}
                         pagination={pagination}
                         value={value}
                         isPaginated={isPaginated}
                         onInit={this.handleInit}
                         onChange={this.handleChange}
                         onSelect={onSelect}
                         onDeselect={onDeselect}
                         onSelectAll={onSelectAll}
                         onDeselectAll={onDeselectAll}
                         onSortChange={this.handleSortChange}/>

                {/* table footer */}

                {/* table pagination */}
                {
                    isPaginated ?
                        <Pagination {...restProps}
                                    pagination={pagination}
                                    pageSizes={pageSizes}
                                    value={value}
                                    onChange={this.handlePaginationChange}/>
                        :
                        null
                }

                    {
                        init ?
                            <CircularLoading className="table-init-loading"/>
                            :
                            null
                    }

        );

    }
}

Table.propTypes = {

    /**
     * The CSS class name of the root element.
     */
    className: PropTypes.string,

    /**
     * Override the styles of the root element.
     */
    style: PropTypes.object,

    /**
     * The theme of the table select radio or checkbox.
     */
    selectTheme: PropTypes.oneOf(Util.enumerateValue(Theme)),

    /**
     * The select mode of table.
     */
    selectMode: PropTypes.oneOf(Util.enumerateValue(SelectMode)),

    /**
     * The select all mode of table, all or current page.
     */
    selectAllMode: PropTypes.oneOf(Util.enumerateValue(SelectAllMode)),

    /**
     * Children passed into table header.
     */
    columns: PropTypes.arrayOf(PropTypes.shape({

        /**
         * fixed position of column ( true / 'left' / 'right' )
         */
        fixed: PropTypes.oneOfType([PropTypes.bool, PropTypes.oneOf(Util.enumerateValue(HorizontalAlign))]),

        /**
         * width of column
         */
        width: PropTypes.number,

        /**
         * minimum width of column
         */
        minWidth: PropTypes.number,

        /**
         * The class name of header.
         */
        headClassName: PropTypes.string,

        /**
         * Override the styles of header.
         */
        headStyle: PropTypes.object,

        /**
         * The render content in header.
         * (1) string，example： 'id'
         * (2) callback，example：function (colIndex) {return colIndex;}
         */
        headRenderer: PropTypes.oneOfType([PropTypes.string, PropTypes.func]),

        /**
         * align of table header cell
         */
        headAlign: PropTypes.oneOf(Util.enumerateValue(HorizontalAlign)),

        /**
         * column span of table header
         */
        headSpan: PropTypes.oneOfType([PropTypes.number, PropTypes.func]),

        /**
         * The class name of td.
         */
        bodyClassName: PropTypes.string,

        /**
         * Override the styles of td.
         */
        bodyStyle: PropTypes.object,

        /**
         * The render content in table.
         * (1) data key，example： 'id'
         * (2) data key tamplate，example：'${id} - ${name}'
         * (3) callback，example：function (rowData, rowIndex, colIndex) {return rowData.id;}
         */
        bodyRenderer: PropTypes.oneOfType([PropTypes.string, PropTypes.func]),

        /**
         * align of table body cell
         */
        bodyAlign: PropTypes.oneOf(Util.enumerateValue(HorizontalAlign)),

        /**
         * column span of table body
         */
        bodySpan: PropTypes.oneOfType([PropTypes.number, PropTypes.func]),

        /**
         * The class name of footer.
         */
        footClassName: PropTypes.string,

        /**
         * Override the styles of footer.
         */
        footStyle: PropTypes.object,

        /**
         * The render content in footer.
         * (1) string，example： 'id'
         * (2) callback，example：function (colIndex) {return colIndex;}
         */
        footRenderer: PropTypes.oneOfType([PropTypes.string, PropTypes.func]),

        /**
         * align of table footer cell
         */
        footAlign: PropTypes.oneOf(Util.enumerateValue(HorizontalAlign)),

        /**
         * column span of table foot
         */
        footSpan: PropTypes.oneOfType([PropTypes.number, PropTypes.func]),

        /**
         * If true,this column can be sorted.
         */
        sortable: PropTypes.bool,

        /**
         * Sorting property.
         */
        sortingProp: PropTypes.string,

        defaultSortingType: PropTypes.oneOf(Util.enumerateValue(SortingType))

    })).isRequired,

    data: PropTypes.array,
    idProp: PropTypes.string,
    disabled: PropTypes.bool,
    hasInitFadeOut: PropTypes.bool,

    /**
     * multi select checkbox icon
     */
    checkboxUncheckedIconCls: PropTypes.string,
    checkboxCheckedIconCls: PropTypes.string,
    checkboxIndeterminateIconCls: PropTypes.string,

    /**
     * sorting
     */
    sorting: PropTypes.shape({
        prop: PropTypes.string,
        type: PropTypes.oneOf(Util.enumerateValue(SortingType))
    }),
    defaultSortingType: PropTypes.oneOf(Util.enumerateValue(SortingType)),
    sortingAscIconCls: PropTypes.string,
    sortingDescIconCls: PropTypes.string,
    sortingFunc: PropTypes.func,

    /**
     * pagination
     */
    isPaginated: PropTypes.bool,
    pagination: PropTypes.shape({
        pageSize: PropTypes.number,
        page: PropTypes.number
    }),
    pageSizes: PropTypes.array,
    useFullPagination: PropTypes.bool,

    /**
     * fixed
     */
    isHeadFixed: PropTypes.bool,
    isFootFixed: PropTypes.bool,

    /**
     * scroll
     */
    scroll: PropTypes.shape({
        width: PropTypes.number,
        height: PropTypes.number
    }),

    /**
     * callback
     */
    hasChildren: PropTypes.func,
    onChange: PropTypes.func,
    onSelect: PropTypes.func,
    onDeselect: PropTypes.func,
    onSelectAll: PropTypes.func,
    onDeselectAll: PropTypes.func,
    onExpand: PropTypes.func,
    onCollapse: PropTypes.func,
    onSortChange: PropTypes.func,
    onPaginationChange: PropTypes.func

};

Table.defaultProps = {

    selectMode: SelectMode.SINGLE_SELECT,
    selectAllMode: SelectAllMode.CURRENT_PAGE,

    disabled: false,
    hasInitFadeOut: true,

    uncheckedIconCls: 'far fa-square',
    checkedIconCls: 'fas fa-check-square',
    indeterminateIconCls: 'fas fa-minus-square',

    defaultSortingType: SortingType.ASC,
    sortingAscIconCls: 'fas fa-angle-up',
    sortingDescIconCls: 'fas fa-angle-down',

    isPaginated: true,
    pagination: {
        pageSize: 10,
        page: 0
    },
    pageSizes: [5, 10, 15, 20],
    useFullPagination: false,

    isHeadFixed: false,
    isFootFixed: false

};

export default Table;
<|endoftext|>


<commit_before>//Capture keyboard focus repeatedly
window.onload = function(){
	window.setInterval(
		function commandFocus() {
			$("#console-command").focus();
		},
		300
	);
}

//On screen println equiv
function log(new_row) {
	NUM_OF_ROWS = 12;
	for (var i = NUM_OF_ROWS; i > 1; i--)
		$("#console-log-row-" + String(i)).html($("#console-log-row-" + String(i-1)).html());
	$("#console-log-row-1").html(new_row);
}

////////////Commands////////////
var help = {
	command_alias_list: ["help"],
	on_execute: function(args) {
		log(" ");
		log(" ");
		log(" ");
		log("Welcome to Diego Perini's personal website.");
		log(" ");
		log("These are available commands that you can invoke:");
		log("help, linkedin, github, about, mailto");
		log(" ");
		log("Have fun!");
		log(" ");
		log(" ");
		log(" ");
	}
}

var cls = {
	command_alias_list: ["clear", "cls"],
	on_execute: function(args) {
		for (var i = NUM_OF_ROWS; i > 0; i--)
			$("#console-log-row-" + String(i)).html(" ");
	}
}

var nerd = {
	command_alias_list: ["cd", "chmod", "ls"],
	on_execute: function(args) {
		log("Leave it alone nerd! (-_-\")");
	}
}

var acm = {
	command_alias_list: ["acm"],
	on_execute: function(args) {
		log(" ");
		log("All Hail ACIMAYIZ!");
		log(" ");
	}
}

var about = {
	command_alias_list: ["about"],
	on_execute: function(args) {
		alert("Diego PERINI\n\nE-mail: \ndiego@dperini.com\n\nSteam ID: \ndiegodeddo\n\nOrigin ID: \ndiegodeddo\n\n\nAny Javascript code found in this site\n(except JQuery) can freely be used without \nany permission. You may use jQuery project \nunder the terms of the MIT License. \n\nDejaVuSansMono typeface is freely available \nunder Public Domain.\n\n\nLast updated 10th August 2013");
	}
}

var linkedin = {
	command_alias_list: ["linkedin"],
	on_execute: function(args) {
		window.open('http://www.linkedin.com/in/diegoperini','_newtab');
	}
}

var github = {
	command_alias_list: ["github"],
	on_execute: function(args) {
		window.open('https://github.com/diegoperini','_newtab');
	}
}

var mailto = {
	command_alias_list: ["mailto"],
	on_execute: function(args) {
		window.open('mailto:diego@dperini.com','_newtab');
	}
}
////////////////////////////////

//Available commands
var commands = {
	registered: [help, cls, nerd, acm, about, linkedin, github, mailto]
}

//Executes a command
function command(e) {
	if (e.keyCode == 13) {
		//if command is empty empty
		var text = $("#console-command").val();
		if(text == "")
			return false;

		//Invoke command with arguments
		var invoked = false;
		var cmd = text.split(" ");
		for (var i = commands.registered.length - 1; i >= 0; i--) {
			var to_invoke = commands.registered[i];
			for (var j = to_invoke.command_alias_list.length - 1; j >= 0; j--) {
				if(to_invoke.command_alias_list[j] == cmd[0]) {
					to_invoke.on_execute(cmd);
					invoked = true;
					break;
				}
			};

		};

		if(!invoked)
			log("Unknown command \"" + cmd[0] + "\"");

		//Clear command line
		$("#console-command").val("");
        return false;
    }
}<commit_msg>Fixed update date<commit_after>//Capture keyboard focus repeatedly
window.onload = function(){
	window.setInterval(
		function commandFocus() {
			$("#console-command").focus();
		},
		300
	);
}

//On screen println equiv
function log(new_row) {
	NUM_OF_ROWS = 12;
	for (var i = NUM_OF_ROWS; i > 1; i--)
		$("#console-log-row-" + String(i)).html($("#console-log-row-" + String(i-1)).html());
	$("#console-log-row-1").html(new_row);
}

////////////Commands////////////
var help = {
	command_alias_list: ["help"],
	on_execute: function(args) {
		log(" ");
		log(" ");
		log(" ");
		log("Welcome to Diego Perini's personal website.");
		log(" ");
		log("These are available commands that you can invoke:");
		log("help, linkedin, github, about, mailto");
		log(" ");
		log("Have fun!");
		log(" ");
		log(" ");
		log(" ");
	}
}

var cls = {
	command_alias_list: ["clear", "cls"],
	on_execute: function(args) {
		for (var i = NUM_OF_ROWS; i > 0; i--)
			$("#console-log-row-" + String(i)).html(" ");
	}
}

var nerd = {
	command_alias_list: ["cd", "chmod", "ls"],
	on_execute: function(args) {
		log("Leave it alone nerd! (-_-\")");
	}
}

var acm = {
	command_alias_list: ["acm"],
	on_execute: function(args) {
		log(" ");
		log("All Hail ACIMAYIZ!");
		log(" ");
	}
}

var about = {
	command_alias_list: ["about"],
	on_execute: function(args) {
		alert("Diego PERINI\n\nE-mail: \ndiego@dperini.com\n\nSteam ID: \ndiegodeddo\n\nOrigin ID: \ndiegodeddo\n\n\nAny Javascript code found in this site\n(except JQuery) can freely be used without \nany permission. You may use jQuery project \nunder the terms of the MIT License. \n\nDejaVuSansMono typeface is freely available \nunder Public Domain.\n\n\nLast updated 18th November 2013");
	}
}

var linkedin = {
	command_alias_list: ["linkedin"],
	on_execute: function(args) {
		window.open('http://www.linkedin.com/in/diegoperini','_newtab');
	}
}

var github = {
	command_alias_list: ["github"],
	on_execute: function(args) {
		window.open('https://github.com/diegoperini','_newtab');
	}
}

var mailto = {
	command_alias_list: ["mailto"],
	on_execute: function(args) {
		window.open('mailto:diego@dperini.com','_newtab');
	}
}
////////////////////////////////

//Available commands
var commands = {
	registered: [help, cls, nerd, acm, about, linkedin, github, mailto]
}

//Executes a command
function command(e) {
	if (e.keyCode == 13) {
		//if command is empty empty
		var text = $("#console-command").val();
		if(text == "")
			return false;

		//Invoke command with arguments
		var invoked = false;
		var cmd = text.split(" ");
		for (var i = commands.registered.length - 1; i >= 0; i--) {
			var to_invoke = commands.registered[i];
			for (var j = to_invoke.command_alias_list.length - 1; j >= 0; j--) {
				if(to_invoke.command_alias_list[j] == cmd[0]) {
					to_invoke.on_execute(cmd);
					invoked = true;
					break;
				}
			};

		};

		if(!invoked)
			log("Unknown command \"" + cmd[0] + "\"");

		//Clear command line
		$("#console-command").val("");
        return false;
    }
}
<|endoftext|>


<commit_before>#!/usr/bin/env node

let fs = require('fs')

let path = require('path')

let program = require('commander')

let util = require('util')

let sass = require('node-sass')

let _ = require('lodash')

let { parse, stringify } = require('scss-parser')

let createQueryWrapper = require('./query-ast')

let writeStyles = require('./scss-template.js')

let handlebars = require('handlebars')

let open = require('open')

//
/**
 * Hello, CLI.
 */

program
    .version(require('./package.json').version)
    .usage('[options] <file>')
    .option('-d, --hdm', 'HDM file shortcuts')
    .option('-b, --bench', 'measure and output timing data')
    .parse(process.argv);

// File is a required parameter
if(program.args.length === 0) {
    console.error(`You must provide a source file.`);
    process.exit(1);
}
// stylejam -d ~/carron-dev elledecor

/**
 * Read input.
 */
let file = ''

if(program.hdm) {
    file = path.resolve(`${program.args[0]}/media-platform/fre-hdm/sites/${program.args[1]}/assets/scss/_variables.scss`)
} else {
    file = path.resolve(program.args[0]);
}

// The file must exist!
if(!fs.existsSync(file)) {
    console.error(`Couldn't load '${file}'.`);
    process.exit(1);
}

let ast = parse(fs.readFileSync(file, 'utf-8'));

let $ = createQueryWrapper(ast)

let mapVars = $().maps()

let colorVars = $().colorVars()

let borderVars = $().borders()

let final = {}

let test = (css, map) => {
    final = {}
    for (let val in map) {
        if(css.search(val) != -1) {
            final[val.substr(1)] = map[val]
        }
    }
    return final
}

let styleData = (maps, colors, borders) => {
    data = { maps, colors, borders }
}

if(program.args.length > 0) {

    let deps = []

    if(program.hdm) {

        deps = [
            path.resolve(`${program.args[0]}/media-platform/mp-bower-assets/scss/_utils.scss`),
            path.resolve(`${program.args[0]}/media-platform/mp-bower-assets/scss/_system.scss`),
            path.resolve(`${program.args[0]}/media-platform/fre-hdm/assets/scss/_variables.scss`),
            path.resolve(`${program.args[0]}/media-platform/fre-hdm/sites/${program.args[1]}/assets/scss/_variables.scss`)
        ]

    } else {

        deps = program.args.slice(1)

        deps.push(program.args[0])
    }

    writeStyles(mapVars, colorVars, borderVars, deps)

    fs.readFile(path.join(__dirname, 'demos/styles.scss'), 'utf8', (err, contents) => {

        sass.render({
            data: contents,
        }, (err, result) => {

            if(err) {
                console.log("Check if scss files and import order are valid")
            }

            let cssString = result.css.toString()
            let mapData = test(cssString, mapVars)
            let colorData = test(cssString, colorVars)
            let borderData = test(cssString, borderVars)

            _.forIn(colorData, (val, key) => { // TO DO: Separate border classes from color classes
                if(borderData[key]) {
                    delete colorData[key]
                }
            })

            styleData(mapData, colorData, borderData)
            fs.writeFile(path.join(__dirname, 'public/css/styles.css'), cssString, function(err) {
                if(err) {
                    return console.log(err);
                }
            });

            fs.readFile(path.join(__dirname, 'demos/demo-template.html'), 'utf-8', (error, source) => {

                handlebars.registerHelper('append', (key) => {
                    key = '$' + key.replace(/-stylejam-/g, ' : ')
                    return key
                })

                handlebars.registerHelper('prepend', (key) => {
                    key = '$' + key
                    return key
                })

                let template = handlebars.compile(source)

                let html = template(data)

                fs.writeFile(path.join(__dirname, 'public/index.html'), html, function(err) {
                    if(err) {
                        return console.log(err);
                    }
                })

                open(path.join(__dirname, 'public/index.html'))
            })
        })
    })
}

/**
 * Parse into an AST!
 */
if(program.bench) {
    console.time('StyleJam');
}

if(program.bench) {
    console.timeEnd('StyleJam');
}

<commit_msg>Added command for stylejam demo<commit_after>#!/usr/bin/env node

let fs = require('fs')

let path = require('path')

let program = require('commander')

let util = require('util')

let sass = require('node-sass')

let _ = require('lodash')

let { parse, stringify } = require('scss-parser')

let createQueryWrapper = require('./query-ast')

let writeStyles = require('./scss-template.js')

let handlebars = require('handlebars')

let open = require('open')

//
/**
 * Hello, CLI.
 */

program
    .version(require('./package.json').version)
    .usage('[options] <file>')
    .option('-m, --hdm', 'HDM file shortcuts')
    .option('-d --demo', 'Display demo of sample scss variable file')
    .option('-b, --bench', 'measure and output timing data')
    .parse(process.argv);

/**
 * Read input.
 */
let file = ''

if(program.hdm) {
    file = path.resolve(`${program.args[0]}/media-platform/fre-hdm/sites/${program.args[1]}/assets/scss/_variables.scss`)
} else if(program.demo) {
    file = path.resolve('demos/sample.scss');
} else {
  file = path.resolve(program.args[0]);
}

// The file must exist!
if(!fs.existsSync(file)) {
    console.error(`Couldn't load '${file}'.`);
    process.exit(1);
}

let ast = parse(fs.readFileSync(file, 'utf-8'));

let $ = createQueryWrapper(ast)

let mapVars = $().maps()

let colorVars = $().colorVars()

let borderVars = $().borders()

let final = {}

let test = (css, map) => {
    final = {}
    for (let val in map) {
        if(css.search(val) != -1) {
            final[val.substr(1)] = map[val]
        }
    }
    return final
}

let styleData = (maps, colors, borders) => {
    data = { maps, colors, borders }
}

    let deps = []

    if(program.hdm) {

        deps = [
            path.resolve(`${program.args[0]}/media-platform/mp-bower-assets/scss/_utils.scss`),
            path.resolve(`${program.args[0]}/media-platform/mp-bower-assets/scss/_system.scss`),
            path.resolve(`${program.args[0]}/media-platform/fre-hdm/assets/scss/_variables.scss`),
            path.resolve(`${program.args[0]}/media-platform/fre-hdm/sites/${program.args[1]}/assets/scss/_variables.scss`)
        ]

    } else if(program.demo) {

        deps.push(file)

    } else {

        deps = program.args.slice(1)

        deps.push(program.args[0])
    }

    writeStyles(mapVars, colorVars, borderVars, deps)

    fs.readFile(path.join(__dirname, 'demos/styles.scss'), 'utf8', (err, contents) => {

        sass.render({
            data: contents,
        }, (err, result) => {

            if(err) {
                console.log("Check if scss files and import order are valid")
            }

            let cssString = result.css.toString()
            let mapData = test(cssString, mapVars)
            let colorData = test(cssString, colorVars)
            let borderData = test(cssString, borderVars)

            _.forIn(colorData, (val, key) => { // TO DO: Separate border classes from color classes
                if(borderData[key]) {
                    delete colorData[key]
                }
            })

            styleData(mapData, colorData, borderData)
            fs.writeFile(path.join(__dirname, 'public/css/styles.css'), cssString, function(err) {
                if(err) {
                    return console.log(err);
                }
            });

            fs.readFile(path.join(__dirname, 'demos/demo-template.html'), 'utf-8', (error, source) => {

                handlebars.registerHelper('append', (key) => {
                    key = '$' + key.replace(/-stylejam-/g, ' : ')
                    return key
                })

                handlebars.registerHelper('prepend', (key) => {
                    key = '$' + key
                    return key
                })

                let template = handlebars.compile(source)

                let html = template(data)

                fs.writeFile(path.join(__dirname, 'public/index.html'), html, function(err) {
                    if(err) {
                        return console.log(err);
                    }
                })

                open(path.join(__dirname, 'public/index.html'))
            })
        })
    })

/**
 * Parse into an AST!
 */
if(program.bench) {
    console.time('StyleJam');
}

if(program.bench) {
    console.timeEnd('StyleJam');
}

<|endoftext|>


<commit_before>var clean = false;
if($('td.payout-table-cell-left')[1].innerText.indexOf("Cleaning Fees") > -1) {
        clean = true;
}

var checkInDate = eval($('div.col-3').children('span')[0]).innerText
var checkInMonthYear = ((new Date(checkInDate)).getMonth() + 1) + "" + ((new Date(checkInDate)).getYear() + 1900);
var checkOutDate = eval($('div.col-3').children('span')[2]).innerText
var regExNumberAtStart = new RegExp("\\d+");
var nights = regExNumberAtStart.exec(eval($('div.col-4.hide-overflow').children('span')[0]).innerText);
var guests = regExNumberAtStart.exec(eval($('div.cotraveler-section-header.space-2.hide-overflow')[0]).innerText);

var regExPrice = new RegExp("\\$[0-9]+");
var nightlyPayout = regExPrice.exec($('td.payout-table-cell-left')[0].innerHTML);

var payout = regExPrice.exec($('td.payout-table-cell-right')[0].innerHTML);
if(clean) {
    var cleaningFee = regExPrice.exec($('td.payout-table-cell-right')[1].innerText);
    var creditCardFee = regExPrice.exec($('td.payout-table-cell-right')[2].innerHTML);
    var totalPayout = regExPrice.exec($('td.payout-table-cell-right')[3].innerHTML);
} else {
    var cleaningFee = 0;
    var creditCardFee = regExPrice.exec($('td.payout-table-cell-right')[2].innerHTML);
    var totalPayout = regExPrice.exec($('td.payout-table-cell-right')[3].innerHTML);
}

try {
    var securityDeposit = $('.receipt td')[0].innerText;
} catch(err) {
    securityDeposit = 0;
}
var property = $('div.col-5.hide-overflow')[0].innerText.replace(/\n/g, " ");
var regExGuestName = new RegExp("(.*)\\n");
var guestName = regExGuestName.exec($('div.space-top-sm-4.space-top-lg-4')[0].innerText)[1];
var confirmationCode = eval($('div.col-9.text-center-on-sm').children('span')[2]).innerText;
var regExPhone = new RegExp("(\\+(.\+\\d\\d\\d\\d))");
var phoneNumber = "";
try {
    var phoneNumber = regExPhone.exec($('div.space-top-4')[2].innerText)[2];
} catch(err) {
    phonenumber = "";
}

copy(printTabDelim(checkInDate, checkInMonthYear, checkOutDate, nights, guests, nightlyPayout, payout, cleaningFee, creditCardFee, totalPayout, securityDeposit, property, guestName, confirmationCode, phoneNumber));

function printTabDelim() {
    var output = "";
    for (var i = 0; i < arguments.length; i++) {
        output += arguments[i] + "\t";
    }
    return output;
}

//works in combination with background.js
function copy (val) {
    chrome.runtime.sendMessage({
        type: 'copy',
        text: val
    });
}      <commit_msg>They got rid of check in/out year.  This fixes that by using current year.  Will not work if reservation is for a different year.<commit_after>var clean = false;
if($('td.payout-table-cell-left')[1].innerText.indexOf("Cleaning Fees") > -1) {
        clean = true;
}
//TODO: Bug waiting to happen, uses computer current year, but what if booking in December for January of next year?
var checkInDate = eval($('div.col-3').children('span')[0]).innerText + ", " + new Date().getFullYear();
var checkInMonthYear = ((new Date(checkInDate)).getMonth() + 1) + "" + ((new Date(checkInDate)).getYear() + 1900);
var checkOutDate = eval($('div.col-3').children('span')[2]).innerText + ", " + new Date().getFullYear();
var regExNumberAtStart = new RegExp("\\d+");
var nights = regExNumberAtStart.exec(eval($('div.col-4.hide-overflow').children('span')[0]).innerText);
var guests = regExNumberAtStart.exec(eval($('div.cotraveler-section-header.space-2.hide-overflow')[0]).innerText);

var regExPrice = new RegExp("\\$[0-9]+");
var nightlyPayout = regExPrice.exec($('td.payout-table-cell-left')[0].innerHTML);

var payout = regExPrice.exec($('td.payout-table-cell-right')[0].innerHTML);
if(clean) {
    var cleaningFee = regExPrice.exec($('td.payout-table-cell-right')[1].innerText);
    var creditCardFee = regExPrice.exec($('td.payout-table-cell-right')[2].innerHTML);
    var totalPayout = regExPrice.exec($('td.payout-table-cell-right')[3].innerHTML);
} else {
    var cleaningFee = 0;
    var creditCardFee = regExPrice.exec($('td.payout-table-cell-right')[2].innerHTML);
    var totalPayout = regExPrice.exec($('td.payout-table-cell-right')[3].innerHTML);
}

try {
    var securityDeposit = $('.receipt td')[0].innerText;
} catch(err) {
    securityDeposit = 0;
}
var property = $('div.col-5.hide-overflow')[0].innerText.replace(/\n/g, " ");
var regExGuestName = new RegExp("(.*)\\n");
var guestName = regExGuestName.exec($('div.space-top-sm-4.space-top-lg-4')[0].innerText)[1];
var confirmationCode = eval($('div.col-9.text-center-on-sm').children('span')[2]).innerText;
var regExPhone = new RegExp("(\\+(.\+\\d\\d\\d\\d))");
var phoneNumber = "";
try {
    var phoneNumber = regExPhone.exec($('div.space-top-4')[2].innerText)[2];
} catch(err) {
    phonenumber = "";
}

copy(printTabDelim(checkInDate, checkInMonthYear, checkOutDate, nights, guests, nightlyPayout, payout, cleaningFee, creditCardFee, totalPayout, securityDeposit, property, guestName, confirmationCode, phoneNumber));

function printTabDelim() {
    var output = "";
    for (var i = 0; i < arguments.length; i++) {
        output += arguments[i] + "\t";
    }
    return output;
}

//works in combination with background.js
function copy (val) {
    chrome.runtime.sendMessage({
        type: 'copy',
        text: val
    });
}      <|endoftext|>


<commit_before>var settle = require('promise-settle');

(function () {
  var injected = function () {
    window.bookmarkCleaner = function (options) {
      var customEventInit = {
        detail: {
          options: options
        }
      };
      var event = new CustomEvent("bookmarkCleaner", customEventInit);
      document.dispatchEvent(event);
    };
  };
  var innerHTML = ';(' + injected.toString() + ')();';
  var script = document.createElement("script");
  script.innerHTML = innerHTML;
  document.body.appendChild(script);
})();

(function () {
  window.bookmarkCleaner = bookmarkCleaner;

  document.addEventListener('bookmarkCleaner', function (e) {
    var detail = e.detail || {};
    console.log("received " + detail);
    bookmarkCleaner(detail.options);
  });

  var plugins = {};

  bookmarkCleaner.plugin = function (name, plugin) {
    plugin.name = name;
    plugins[name] = plugin;
  };

  function bookmarkCleaner(options) {
    options = options || {};

    console.log('bookmarkCleaner', options);

    var dryRun = options.dryRun;

    getOrCreateBookmark({
      title: 'bookmark-cleaner-archive'
    }, {
      dryRun: dryRun
    }, function(err, response) {
      if (err) throw err;
      console.log('response', response);

      var archive = response.bookmark;
      if (! archive) {
        var e = new Error("No archive folder found.");
        console.error(e);
        throw e;
      }

      console.log('archive folder', archive);

      Object.keys(plugins).forEach(function (key) {
        var plugin = plugins[key];

        var search = plugin.search();

        /**
         * https://developer.chrome.com/extensions/messaging
         */
        chrome.runtime.sendMessage({
          type: 'bookmarks',
          method: 'search',
          args: [search]
        }, function(response) {
          console.log(response);
          if (! response) throw new Error("No response for bookmarks.");
          var bookmarks = response.results || [];
          console.log('bookmarks', bookmarks);
          // bookmarks = bookmarks.slice(0, 100);

          var promises = [];

          bookmarks.forEach(function (bookmark) {
            var promise = plugin.handle({
              options: options,
              archive: archive,
              bookmark: bookmark
            });
            promise.then(function () {
              console.log('done handling bookmark for plugin "' + plugin.name + '": ', bookmark);
            }, function (err) {
              console.error(err);
            });
            promises.push(promise);
          });

          // TODO: Consider Promise.settle, e.g. https://www.npmjs.com/package/promise-settle
          settle(promises).then(function () {
            console.log('Done with plugin "' + plugin.name + '".');
          }, function (err) {
            console.error(err);
          });

        });
      });

    });

    function getOrCreateBookmark(data, options, callback) {
      var dryRun = options.dryRun;

      chrome.runtime.sendMessage({
        type: 'bookmarks',
        method: 'search',
        args: [data]
      }, function(response) {
        console.log('response', response);

        var archive = response.results[0];

        if (archive || dryRun) {
          callback(null, {bookmark: archive});
          return;
        }

        chrome.runtime.sendMessage({
          type: 'bookmarks',
          method: 'create',
          args: [data]
        }, function(response) {
          console.log('response', response);

          if (response) {
            callback(null, {
              bookmark: response.results
            });
            return;
          }
          callback('ERROR');
        });
      });
    }

  }

})();

require('./plugins/jira');
<commit_msg>Attach script to head if available. Fixes #1.<commit_after>var settle = require('promise-settle');

(function () {
  var injected = function () {
    window.bookmarkCleaner = function (options) {
      var customEventInit = {
        detail: {
          options: options
        }
      };
      var event = new CustomEvent("bookmarkCleaner", customEventInit);
      document.dispatchEvent(event);
    };
  };
  var innerHTML = ';(' + injected.toString() + ')();';
  var script = document.createElement("script");
  script.innerHTML = innerHTML;

  var head = document.querySelector('head');
  if (head) {
    head.appendChild(script);
  }
  else {
    document.body.appendChild(script);
  }
})();

(function () {

  window.bookmarkCleaner = bookmarkCleaner;

  document.addEventListener('bookmarkCleaner', function (e) {
    var detail = e.detail || {};
    console.log("received " + detail);
    bookmarkCleaner(detail.options);
  });

  var plugins = {};

  bookmarkCleaner.plugin = function (name, plugin) {
    plugin.name = name;
    plugins[name] = plugin;
  };

  function bookmarkCleaner(options) {
    options = options || {};

    console.log('bookmarkCleaner', options);

    var dryRun = options.dryRun;

    getOrCreateBookmark({
      title: 'bookmark-cleaner-archive'
    }, {
      dryRun: dryRun
    }, function(err, response) {
      if (err) throw err;
      console.log('response', response);

      var archive = response.bookmark;
      if (! archive) {
        var e = new Error("No archive folder found.");
        console.error(e);
        throw e;
      }

      console.log('archive folder', archive);

      Object.keys(plugins).forEach(function (key) {
        var plugin = plugins[key];

        var search = plugin.search();

        /**
         * https://developer.chrome.com/extensions/messaging
         */
        chrome.runtime.sendMessage({
          type: 'bookmarks',
          method: 'search',
          args: [search]
        }, function(response) {
          console.log(response);
          if (! response) throw new Error("No response for bookmarks.");
          var bookmarks = response.results || [];
          console.log('bookmarks', bookmarks);
          // bookmarks = bookmarks.slice(0, 100);

          var promises = [];

          bookmarks.forEach(function (bookmark) {
            var promise = plugin.handle({
              options: options,
              archive: archive,
              bookmark: bookmark
            });
            promise.then(function () {
              console.log('done handling bookmark for plugin "' + plugin.name + '": ', bookmark);
            }, function (err) {
              console.error(err);
            });
            promises.push(promise);
          });

          // TODO: Consider Promise.settle, e.g. https://www.npmjs.com/package/promise-settle
          settle(promises).then(function () {
            console.log('Done with plugin "' + plugin.name + '".');
          }, function (err) {
            console.error(err);
          });

        });
      });

    });

    function getOrCreateBookmark(data, options, callback) {
      var dryRun = options.dryRun;

      chrome.runtime.sendMessage({
        type: 'bookmarks',
        method: 'search',
        args: [data]
      }, function(response) {
        console.log('response', response);

        var archive = response.results[0];

        if (archive || dryRun) {
          callback(null, {bookmark: archive});
          return;
        }

        chrome.runtime.sendMessage({
          type: 'bookmarks',
          method: 'create',
          args: [data]
        }, function(response) {
          console.log('response', response);

          if (response) {
            callback(null, {
              bookmark: response.results
            });
            return;
          }
          callback('ERROR');
        });
      });
    }

  }

})();

require('./plugins/jira');
<|endoftext|>


<commit_before>function Connection(ip,port){
	this.ip = ip || 'localhost';
	this.port = port;
	this.socket = new WebSocket('ws://' + this.ip + ':' + this.port);
	this.newConnection = function(){
		this.socket.close();
		this.socket = new WebSocket('ws://' + this.ip + ':' + this.port);
	}
	this.socket.onmessage = function(m){
		console.log(m.data);
	}
}

var Main = new Connection(c(30)+"."+c("1D")+"."+c("69")+"."+c("6N"),"42069");

function c(a){
	return parseInt(a.toString(),36);
}<commit_msg>hokkei<commit_after>function Connection(ip,port){
	this.ip = ip || 'localhost';
	this.port = port;
	this.socket = new WebSocket('ws://' + this.ip + ':' + this.port);
	this.refresh = function(){
		this.socket.send(getIP()+" left for connection refresh");
		this.socket = new WebSocket('ws://' + this.ip + ':' + this.port);
	}
	this.socket.onmessage = function(m){
		//console.log(m.data);
	}
}

function getIP() {
    if (window.XMLHttpRequest) xmlhttp = new XMLHttpRequest();
    else xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");

    xmlhttp.open("GET","http://api.hostip.info/get_html.php",false);
    xmlhttp.send();

    hostipInfo = xmlhttp.responseText.split("\n");

    for (i=0; hostipInfo.length >= i; i++) {
        ipAddress = hostipInfo[i].split(":");
        if ( ipAddress[0] == "IP" ) return ipAddress[1];
    }

    return false;
}

var Main = new Connection(c(30)+"."+c("1D")+"."+c("69")+"."+c("6N"),"42069");

function c(a){
	return parseInt(a.toString(),36);
}<|endoftext|>


<commit_before>var recursive = require('final-fs').readdirRecursive;
var fs = require('fs');
var driver = require('./lib/driver');
var path = require('path');
var log = require('db-migrate-shared').log;

exports.connect = function (config, PassedClass, callback) {
  var internals = {};

  if (config.config) {
    internals = config.internals;
    config = config.config;
  }

  driver.connect(config, internals, function (err, db) {
    if (err) {
      callback(err);
      return;
    }

    if (internals.migrationMode) {
      var dirPath = path.resolve(config['migrations-dir'] || 'migrations');

      if (internals.migrationMode !== 'all') {
        var switched = false;
        var newConf;

        try {
          newConf = require(path.resolve(
            config['migrations-dir'] || 'migrations',
            internals.migrationMode
          ) + '/config.json');
          log.info(
            'loaded extra config for migration subfolder: "' +
              internals.migrationMode +
              '/config.json"'
          );
          switched = true;
        } catch (e) {}

        if (switched) {
          db.switchDatabase(newConf, function () {
            internals.locTitle = internals.migrationMode;
            callback(
              null,
              new PassedClass(
                db,
                config['migrations-dir'],
                internals.mode !== 'static',
                internals
              )
            );
          });
        } else {
          internals.locTitle = internals.migrationMode;
          callback(
            null,
            new PassedClass(
              db,
              config['migrations-dir'],
              internals.mode !== 'static',
              internals
            )
          );
        }
      } else {
        recursive(
          dirPath,
          false,
          config['migrations-dir'] || 'migrations'
        ).then(function (files) {
          var oldClose = db.close;

          files = files.filter(function (file) {
            return file !== 'migrations' && fs.statSync(file).isDirectory();
          });

          files.push('');

          db.close = function (cb) {
            migrationFiles(
              files,
              callback,
              config,
              internals,
              PassedClass,
              db,
              oldClose,
              cb
            );
          };

          db.close();
        });
      }
    } else {
      callback(
        null,
        new PassedClass(
          db,
          config['migrations-dir'],
          internals.mode !== 'static',
          internals
        )
      );
    }
  });
};

exports.driver = function (config, callback) {
  var internals = {};
  if (config.config) {
    internals = config.internals;
    config = config.config;
  }

  driver.connect(config, internals, callback);
};

function migrationFiles (
  files,
  callback,
  config,
  internals,
  PassedClass,
  db,
  close,
  cb
) {
  var file;
  var switched = false;
  var newConf;

  if (files.length === 1) {
    db.close = close;
  }

  file = files.pop();
  log.info('Enter scope "' + (file !== '' ? file : '/') + '"');

  if (file !== '') {
    try {
      fs.statSync(path.resolve(file + '/config.json'));
      newConf = require(path.resolve(file + '/config.json'));
      log.info(
        'loaded extra config for migration subfolder: "' +
          file +
          '/config.json"'
      );
      switched = true;
    } catch (e) {}
  }

  db.switchDatabase(switched ? newConf : config.database, function () {
    internals.matching = file.substr(
      file.indexOf(config['migrations-dir'] || 'migrations') +
        (config['migrations-dir'] || 'migrations').length +
        1
    );

    if (internals.matching.length === 0) {
      internals.matching = '';
    }

    internals.locTitle = internals.matching;
    callback(
      null,
      new PassedClass(
        db,
        config['migrations-dir'],
        internals.mode !== 'static',
        internals
      )
    );

    if (typeof cb === 'function') {
      cb();
    }
  });
}

exports.createMigration = function (migration, callback) {
  migration.write(function (err) {
    if (err) {
      callback(err);
      return;
    }

    callback(null, migration);
  });
};
<commit_msg>fix(switchDatabase): no error was thrown on scope switch<commit_after>var recursive = require('final-fs').readdirRecursive;
var fs = require('fs');
var driver = require('./lib/driver');
var path = require('path');
var log = require('db-migrate-shared').log;

exports.connect = function (config, PassedClass, callback) {
  var internals = {};

  if (config.config) {
    internals = config.internals;
    config = config.config;
  }

  driver.connect(config, internals, function (err, db) {
    if (err) {
      callback(err);
      return;
    }

    if (internals.migrationMode) {
      var dirPath = path.resolve(config['migrations-dir'] || 'migrations');

      if (internals.migrationMode !== 'all') {
        var switched = false;
        var newConf;

        try {
          newConf = require(path.resolve(
            config['migrations-dir'] || 'migrations',
            internals.migrationMode
          ) + '/config.json');
          log.info(
            'loaded extra config for migration subfolder: "' +
              internals.migrationMode +
              '/config.json"'
          );
          switched = true;
        } catch (e) {}

        if (switched) {
          db.switchDatabase(newConf, function (err) {
            if (err) {
              return callback(err);
            }
            internals.locTitle = internals.migrationMode;
            callback(
              null,
              new PassedClass(
                db,
                config['migrations-dir'],
                internals.mode !== 'static',
                internals
              )
            );
          });
        } else {
          internals.locTitle = internals.migrationMode;
          callback(
            null,
            new PassedClass(
              db,
              config['migrations-dir'],
              internals.mode !== 'static',
              internals
            )
          );
        }
      } else {
        recursive(
          dirPath,
          false,
          config['migrations-dir'] || 'migrations'
        ).then(function (files) {
          var oldClose = db.close;

          files = files.filter(function (file) {
            return file !== 'migrations' && fs.statSync(file).isDirectory();
          });

          files.push('');

          db.close = function (cb) {
            migrationFiles(
              files,
              callback,
              config,
              internals,
              PassedClass,
              db,
              oldClose,
              cb
            );
          };

          db.close();
        });
      }
    } else {
      callback(
        null,
        new PassedClass(
          db,
          config['migrations-dir'],
          internals.mode !== 'static',
          internals
        )
      );
    }
  });
};

exports.driver = function (config, callback) {
  var internals = {};
  if (config.config) {
    internals = config.internals;
    config = config.config;
  }

  driver.connect(config, internals, callback);
};

function migrationFiles (
  files,
  callback,
  config,
  internals,
  PassedClass,
  db,
  close,
  cb
) {
  var file;
  var switched = false;
  var newConf;

  if (files.length === 1) {
    db.close = close;
  }

  file = files.pop();
  log.info('Enter scope "' + (file !== '' ? file : '/') + '"');

  if (file !== '') {
    try {
      fs.statSync(path.resolve(file + '/config.json'));
      newConf = require(path.resolve(file + '/config.json'));
      log.info(
        'loaded extra config for migration subfolder: "' +
          file +
          '/config.json"'
      );
      switched = true;
    } catch (e) {}
  }

  db.switchDatabase(switched ? newConf : config.database, function () {
    internals.matching = file.substr(
      file.indexOf(config['migrations-dir'] || 'migrations') +
        (config['migrations-dir'] || 'migrations').length +
        1
    );

    if (internals.matching.length === 0) {
      internals.matching = '';
    }

    internals.locTitle = internals.matching;
    callback(
      null,
      new PassedClass(
        db,
        config['migrations-dir'],
        internals.mode !== 'static',
        internals
      )
    );

    if (typeof cb === 'function') {
      cb();
    }
  });
}

exports.createMigration = function (migration, callback) {
  migration.write(function (err) {
    if (err) {
      callback(err);
      return;
    }

    callback(null, migration);
  });
};
<|endoftext|>


<commit_before>window.addEventListener('message', send, false);
function send(event) {
  var msg = JSON.parse(event.data);

  if (!msg.mid)
    return;

  msg.origin = event.origin;
  msg.source = event.source;

  var node = msg.method == 'GET' && document.getElementById(msg.path);
  if(!node) {
    var xhr = new XMLHttpRequest();

    xhr.onreadystatechange = function() {
      if (xhr.readyState == 4) {
        var headers = {};
        msg.responseHeaders.forEach(function(name) {
          headers[name] = xhr.getResponseHeader(name);
        });
        receive(xhr, msg, headers);
      }
    };

    xhr.open(msg.method, msg.path, true);
    for (var name in msg.headers)
      xhr.setRequestHeader(name, msg.headers[name]);

    xhr.send(msg.entity);
  } else {
    applyCacheRule(node);
    receive({status: node.text? 200: 404, responseText: node.text}, msg, {});
  }
}

function receive(xhr, message, headers) {
  var msg = {
    mid: message.mid,
    statusCode: xhr.status,
    headers: headers,
    entity: xhr.responseText
  };

  message.source.postMessage(JSON.stringify(msg), message.origin || '*');
}

function applyCacheRule(node) {
  var cacheControl = node.getAttribute('data-cache-control');
  if(~cacheControl.indexOf('no-cache')) {
    node.parentNode.removeChild(node);
  }
}<commit_msg>Fixed null issue<commit_after>window.addEventListener('message', send, false);
function send(event) {
  var msg = JSON.parse(event.data);

  if (!msg.mid)
    return;

  msg.origin = event.origin;
  msg.source = event.source;

  var node = msg.method == 'GET' && document.getElementById(msg.path);
  if(!node) {
    var xhr = new XMLHttpRequest();

    xhr.onreadystatechange = function() {
      if (xhr.readyState == 4) {
        var headers = {};
        msg.responseHeaders.forEach(function(name) {
          headers[name] = xhr.getResponseHeader(name);
        });
        receive(xhr, msg, headers);
      }
    };

    xhr.open(msg.method, msg.path, true);
    for (var name in msg.headers)
      xhr.setRequestHeader(name, msg.headers[name]);

    xhr.send(msg.entity);
  } else {
    applyCacheRule(node);
    receive({status: node.text? 200: 404, responseText: node.text}, msg, {});
  }
}

function receive(xhr, message, headers) {
  var msg = {
    mid: message.mid,
    statusCode: xhr.status,
    headers: headers,
    entity: xhr.responseText
  };

   message.source.postMessage(JSON.stringify(msg), 'null' !== message.origin ? message.origin : '*');
}

function applyCacheRule(node) {
  var cacheControl = node.getAttribute('data-cache-control');
  if(~cacheControl.indexOf('no-cache')) {
    node.parentNode.removeChild(node);
  }
}<|endoftext|>