<commit_before>var aws4 = exports,
    url = require('url'),
    querystring = require('querystring'),
    crypto = require('crypto'),
    lru = require('lru-cache'),
    credentialsCache = lru(1000)

// http://docs.amazonwebservices.com/general/latest/gr/signature-version-4.html

function hmac(key, string, encoding) {
  return crypto.createHmac('sha256', key).update(string, 'utf8').digest(encoding)
}

function hash(string, encoding) {
  return crypto.createHash('sha256').update(string, 'utf8').digest(encoding)
}

// request: { path | body, [host], [method], [headers], [service], [region] }
// credentials: { accessKeyId, secretAccessKey, [sessionToken] }
function RequestSigner(request, credentials) {

  if (typeof request === 'string') request = url.parse(request)

  var headers = request.headers = (request.headers || {}),
      hostParts = this.matchHost(request.hostname || request.host || headers.Host || headers.host)

  this.request = request
  this.credentials = credentials || this.defaultCredentials()

  // ES's hostParts are sometimes the other way round, if the value that is expected
  // to be region equals ‘es’ switch them back
  // e.g. search-cluster-name-aaaa00aaaa0aaa0aaaaaaa0aaa.us-east-1.es.amazonaws.com
  if (hostParts[1] === 'es')
    hostParts = hostParts.reverse()

  this.service = request.service || hostParts[0] || ''
  this.region = request.region || hostParts[1] || 'us-east-1'

  // SES uses a different domain from the service name
  if (this.service === 'email') this.service = 'ses'

  if (!request.method && request.body)
    request.method = 'POST'

  if (!headers.Host && !headers.host)
    headers.Host = request.hostname || request.host || this.createHost()
  if (!request.hostname && !request.host)
    request.hostname = headers.Host || headers.host
}

RequestSigner.prototype.matchHost = function(host) {
  var match = (host || '').match(/([^\.]+)\.(?:([^\.]*)\.)?amazonaws\.com$/)
  return (match || []).slice(1, 3)
}

// http://docs.aws.amazon.com/general/latest/gr/rande.html
RequestSigner.prototype.isSingleRegion = function() {
  // Special case for S3 and SimpleDB in us-east-1
  if (['s3', 'sdb'].indexOf(this.service) >= 0 && this.region === 'us-east-1') return true

  return ['cloudfront', 'ls', 'route53', 'iam', 'importexport', 'sts']
    .indexOf(this.service) >= 0
}

RequestSigner.prototype.createHost = function() {
  var region = this.isSingleRegion() ? '' :
        (this.service === 's3' && this.region !== 'us-east-1' ? '-' : '.') + this.region,
      service = this.service === 'ses' ? 'email' : this.service
  return service + region + '.amazonaws.com'
}

RequestSigner.prototype.sign = function() {
  var request = this.request, headers = request.headers, parsedUrl, query

  if (request.signQuery) {
    parsedUrl = url.parse(request.path || '/', true)
    query = parsedUrl.query

    if (this.credentials.sessionToken)
      query['X-Amz-Security-Token'] = this.credentials.sessionToken

    if (this.service === 's3' && !query['X-Amz-Expires'])
      query['X-Amz-Expires'] = 86400

    if (query['X-Amz-Date'])
      this.datetime = query['X-Amz-Date']
    else
      query['X-Amz-Date'] = this.getDateTime()

    query['X-Amz-Algorithm'] = 'AWS4-HMAC-SHA256'
    query['X-Amz-Credential'] = this.credentials.accessKeyId + '/' + this.credentialString()
    query['X-Amz-SignedHeaders'] = this.signedHeaders()

    delete parsedUrl.search
    request.path = url.format(parsedUrl)

    request.path += '&X-Amz-Signature=' + this.signature()

  } else {

    if (!request.doNotModifyHeaders) {
      if (request.body && !headers['Content-Type'] && !headers['content-type'])
        headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=utf-8'

      if (request.body && !headers['Content-Length'] && !headers['content-length'])
        headers['Content-Length'] = Buffer.byteLength(request.body)

      if (this.credentials.sessionToken)
        headers['X-Amz-Security-Token'] = this.credentials.sessionToken

      if (this.service === 's3')
        headers['X-Amz-Content-Sha256'] = hash(this.request.body || '', 'hex')

      if (headers['X-Amz-Date'])
        this.datetime = headers['X-Amz-Date']
      else
        headers['X-Amz-Date'] = this.getDateTime()
    }

    delete headers.Authorization
    delete headers.authorization
    headers.Authorization = this.authHeader()
  }

  return request
}

RequestSigner.prototype.getDateTime = function() {
  if (!this.datetime) {
    var headers = this.request.headers,
      date = new Date(headers.Date || headers.date || new Date)

    this.datetime = date.toISOString().replace(/[:\-]|\.\d{3}/g, '')
  }
  return this.datetime
}

RequestSigner.prototype.getDate = function() {
  return this.getDateTime().substr(0, 8)
}

RequestSigner.prototype.authHeader = function() {
  return [
    'AWS4-HMAC-SHA256 Credential=' + this.credentials.accessKeyId + '/' + this.credentialString(),
    'SignedHeaders=' + this.signedHeaders(),
    'Signature=' + this.signature()
  ].join(', ')
}

RequestSigner.prototype.signature = function() {
  var date = this.getDate(),
      cacheKey = [this.credentials.secretAccessKey, date, this.region, this.service].join(),
      kDate, kRegion, kService, kCredentials = credentialsCache.get(cacheKey)
  if (!kCredentials) {
    kDate = hmac('AWS4' + this.credentials.secretAccessKey, date)
    kRegion = hmac(kDate, this.region)
    kService = hmac(kRegion, this.service)
    kCredentials = hmac(kService, 'aws4_request')
    credentialsCache.set(cacheKey, kCredentials)
  }
  return hmac(kCredentials, this.stringToSign(), 'hex')
}

RequestSigner.prototype.stringToSign = function() {
  return [
    'AWS4-HMAC-SHA256',
    this.getDateTime(),
    this.credentialString(),
    hash(this.canonicalString(), 'hex')
  ].join('\n')
}

RequestSigner.prototype.canonicalString = function() {
  var pathStr = this.request.path || '/',
      queryIx = pathStr.indexOf('?'),
      queryStr = '',
      bodyHash = this.service === 's3' && this.request.signQuery ?
        'UNSIGNED-PAYLOAD' : hash(this.request.body || '', 'hex')
  if (queryIx >= 0) {
    var query = querystring.parse(pathStr.slice(queryIx + 1))
    pathStr = pathStr.slice(0, queryIx)
    queryStr = querystring.stringify(Object.keys(query).sort().reduce(function(obj, key) {
      obj[key] = Array.isArray(query[key]) ? query[key].sort() : query[key]
      return obj
    }, {})).replace(/[!'()*]/g, function(c) { return '%' + c.charCodeAt(0).toString(16).toUpperCase() })
  }
  return [
    this.request.method || 'GET',
    url.resolve('/', pathStr.replace(/\/{2,}/g, '/')) || '/',
    queryStr,
    this.canonicalHeaders() + '\n',
    this.signedHeaders(),
    bodyHash,
  ].join('\n')
}

RequestSigner.prototype.canonicalHeaders = function() {
  var headers = this.request.headers
  function trimAll(header) {
    return header.toString().trim().replace(/\s+/g, ' ')
  }
  return Object.keys(headers)
    .sort(function(a, b) { return a.toLowerCase() < b.toLowerCase() ? -1 : 1 })
    .map(function(key) { return key.toLowerCase() + ':' + trimAll(headers[key]) })
    .join('\n')
}

RequestSigner.prototype.signedHeaders = function() {
  return Object.keys(this.request.headers)
    .map(function(key) { return key.toLowerCase() })
    .sort()
    .join(';')
}

RequestSigner.prototype.credentialString = function() {
  return [
    this.getDate(),
    this.region,
    this.service,
    'aws4_request'
  ].join('/')
}

RequestSigner.prototype.defaultCredentials = function() {
  var env = process.env
  return {
    accessKeyId:     env.AWS_ACCESS_KEY_ID     || env.AWS_ACCESS_KEY,
    secretAccessKey: env.AWS_SECRET_ACCESS_KEY || env.AWS_SECRET_KEY,
    sessionToken:    env.AWS_SESSION_TOKEN
  }
}

aws4.RequestSigner = RequestSigner

aws4.sign = function(request, credentials) {
  return new RequestSigner(request, credentials).sign()
}
<commit_msg>Minor reformatting<commit_after>var aws4 = exports,
    url = require('url'),
    querystring = require('querystring'),
    crypto = require('crypto'),
    lru = require('lru-cache'),
    credentialsCache = lru(1000)

// http://docs.amazonwebservices.com/general/latest/gr/signature-version-4.html

function hmac(key, string, encoding) {
  return crypto.createHmac('sha256', key).update(string, 'utf8').digest(encoding)
}

function hash(string, encoding) {
  return crypto.createHash('sha256').update(string, 'utf8').digest(encoding)
}

// request: { path | body, [host], [method], [headers], [service], [region] }
// credentials: { accessKeyId, secretAccessKey, [sessionToken] }
function RequestSigner(request, credentials) {

  if (typeof request === 'string') request = url.parse(request)

  var headers = request.headers = (request.headers || {}),
      hostParts = this.matchHost(request.hostname || request.host || headers.Host || headers.host)

  this.request = request
  this.credentials = credentials || this.defaultCredentials()

  this.service = request.service || hostParts[0] || ''
  this.region = request.region || hostParts[1] || 'us-east-1'

  // SES uses a different domain from the service name
  if (this.service === 'email') this.service = 'ses'

  if (!request.method && request.body)
    request.method = 'POST'

  if (!headers.Host && !headers.host)
    headers.Host = request.hostname || request.host || this.createHost()
  if (!request.hostname && !request.host)
    request.hostname = headers.Host || headers.host
}

RequestSigner.prototype.matchHost = function(host) {
  var match = (host || '').match(/([^\.]+)\.(?:([^\.]*)\.)?amazonaws\.com$/)
  var hostParts = (match || []).slice(1, 3)

  // ES's hostParts are sometimes the other way round, if the value that is expected
  // to be region equals ‘es’ switch them back
  // e.g. search-cluster-name-aaaa00aaaa0aaa0aaaaaaa0aaa.us-east-1.es.amazonaws.com
  if (hostParts[1] === 'es')
    hostParts = hostParts.reverse()

  return hostParts
}

// http://docs.aws.amazon.com/general/latest/gr/rande.html
RequestSigner.prototype.isSingleRegion = function() {
  // Special case for S3 and SimpleDB in us-east-1
  if (['s3', 'sdb'].indexOf(this.service) >= 0 && this.region === 'us-east-1') return true

  return ['cloudfront', 'ls', 'route53', 'iam', 'importexport', 'sts']
    .indexOf(this.service) >= 0
}

RequestSigner.prototype.createHost = function() {
  var region = this.isSingleRegion() ? '' :
        (this.service === 's3' && this.region !== 'us-east-1' ? '-' : '.') + this.region,
      service = this.service === 'ses' ? 'email' : this.service
  return service + region + '.amazonaws.com'
}

RequestSigner.prototype.sign = function() {
  var request = this.request, headers = request.headers, parsedUrl, query

  if (request.signQuery) {
    parsedUrl = url.parse(request.path || '/', true)
    query = parsedUrl.query

    if (this.credentials.sessionToken)
      query['X-Amz-Security-Token'] = this.credentials.sessionToken

    if (this.service === 's3' && !query['X-Amz-Expires'])
      query['X-Amz-Expires'] = 86400

    if (query['X-Amz-Date'])
      this.datetime = query['X-Amz-Date']
    else
      query['X-Amz-Date'] = this.getDateTime()

    query['X-Amz-Algorithm'] = 'AWS4-HMAC-SHA256'
    query['X-Amz-Credential'] = this.credentials.accessKeyId + '/' + this.credentialString()
    query['X-Amz-SignedHeaders'] = this.signedHeaders()

    delete parsedUrl.search
    request.path = url.format(parsedUrl)

    request.path += '&X-Amz-Signature=' + this.signature()

  } else {

    if (!request.doNotModifyHeaders) {
      if (request.body && !headers['Content-Type'] && !headers['content-type'])
        headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=utf-8'

      if (request.body && !headers['Content-Length'] && !headers['content-length'])
        headers['Content-Length'] = Buffer.byteLength(request.body)

      if (this.credentials.sessionToken)
        headers['X-Amz-Security-Token'] = this.credentials.sessionToken

      if (this.service === 's3')
        headers['X-Amz-Content-Sha256'] = hash(this.request.body || '', 'hex')

      if (headers['X-Amz-Date'])
        this.datetime = headers['X-Amz-Date']
      else
        headers['X-Amz-Date'] = this.getDateTime()
    }

    delete headers.Authorization
    delete headers.authorization
    headers.Authorization = this.authHeader()
  }

  return request
}

RequestSigner.prototype.getDateTime = function() {
  if (!this.datetime) {
    var headers = this.request.headers,
      date = new Date(headers.Date || headers.date || new Date)

    this.datetime = date.toISOString().replace(/[:\-]|\.\d{3}/g, '')
  }
  return this.datetime
}

RequestSigner.prototype.getDate = function() {
  return this.getDateTime().substr(0, 8)
}

RequestSigner.prototype.authHeader = function() {
  return [
    'AWS4-HMAC-SHA256 Credential=' + this.credentials.accessKeyId + '/' + this.credentialString(),
    'SignedHeaders=' + this.signedHeaders(),
    'Signature=' + this.signature(),
  ].join(', ')
}

RequestSigner.prototype.signature = function() {
  var date = this.getDate(),
      cacheKey = [this.credentials.secretAccessKey, date, this.region, this.service].join(),
      kDate, kRegion, kService, kCredentials = credentialsCache.get(cacheKey)
  if (!kCredentials) {
    kDate = hmac('AWS4' + this.credentials.secretAccessKey, date)
    kRegion = hmac(kDate, this.region)
    kService = hmac(kRegion, this.service)
    kCredentials = hmac(kService, 'aws4_request')
    credentialsCache.set(cacheKey, kCredentials)
  }
  return hmac(kCredentials, this.stringToSign(), 'hex')
}

RequestSigner.prototype.stringToSign = function() {
  return [
    'AWS4-HMAC-SHA256',
    this.getDateTime(),
    this.credentialString(),
    hash(this.canonicalString(), 'hex'),
  ].join('\n')
}

RequestSigner.prototype.canonicalString = function() {
  var pathStr = this.request.path || '/',
      queryIx = pathStr.indexOf('?'),
      queryStr = '',
      bodyHash = this.service === 's3' && this.request.signQuery ?
        'UNSIGNED-PAYLOAD' : hash(this.request.body || '', 'hex')
  if (queryIx >= 0) {
    var query = querystring.parse(pathStr.slice(queryIx + 1))
    pathStr = pathStr.slice(0, queryIx)
    queryStr = querystring.stringify(Object.keys(query).sort().reduce(function(obj, key) {
      obj[key] = Array.isArray(query[key]) ? query[key].sort() : query[key]
      return obj
    }, {})).replace(/[!'()*]/g, function(c) { return '%' + c.charCodeAt(0).toString(16).toUpperCase() })
  }
  return [
    this.request.method || 'GET',
    url.resolve('/', pathStr.replace(/\/{2,}/g, '/')) || '/',
    queryStr,
    this.canonicalHeaders() + '\n',
    this.signedHeaders(),
    bodyHash,
  ].join('\n')
}

RequestSigner.prototype.canonicalHeaders = function() {
  var headers = this.request.headers
  function trimAll(header) {
    return header.toString().trim().replace(/\s+/g, ' ')
  }
  return Object.keys(headers)
    .sort(function(a, b) { return a.toLowerCase() < b.toLowerCase() ? -1 : 1 })
    .map(function(key) { return key.toLowerCase() + ':' + trimAll(headers[key]) })
    .join('\n')
}

RequestSigner.prototype.signedHeaders = function() {
  return Object.keys(this.request.headers)
    .map(function(key) { return key.toLowerCase() })
    .sort()
    .join(';')
}

RequestSigner.prototype.credentialString = function() {
  return [
    this.getDate(),
    this.region,
    this.service,
    'aws4_request',
  ].join('/')
}

RequestSigner.prototype.defaultCredentials = function() {
  var env = process.env
  return {
    accessKeyId: env.AWS_ACCESS_KEY_ID || env.AWS_ACCESS_KEY,
    secretAccessKey: env.AWS_SECRET_ACCESS_KEY || env.AWS_SECRET_KEY,
    sessionToken: env.AWS_SESSION_TOKEN,
  }
}

aws4.RequestSigner = RequestSigner

aws4.sign = function(request, credentials) {
  return new RequestSigner(request, credentials).sign()
}
<|endoftext|>


<commit_before>import React from 'react';
// This is to add non contract binding data into Dapp.
// May be replaced with IPFS at some point.

let Data = [
  {
    name: 'Ethereum London September 2017',
    address: null,
    date:'Wednesday, September 13, 2017 6:45 PM to 9:00 PM(UTC+1)',
    map_url: 'https://maps.google.com/maps?f=q&hl=en&q=Huxley+Building%2C+Imperial+College+%2C+London+SW7+2AZ%2C+gb',
    location_text: 'Clore Lecture Theatre, Huxley Building, Imperial College, London (SW7 2AZ)',
    description_text: ''
  },
  {
    name: 'CodeUp #22',
    address: '0x03738b2fd7ab1d8b3003c3e4d83864eef636bed2',
    date:'Sep 7th (Thur) 6:30 PM(UTC+1)',
    map_url: 'https://www.google.co.uk/maps/place/Simply+Business/@51.51528,-0.0904011,15z/data=!4m5!3m4!1s0x0:0x70f23f24baccffdc!8m2!3d51.51528!4d-0.0904011',
    location_text: 'Simply Business (99 Gresham St, London EC2V 7NG)',
    description_text: ''
  },
  {
    name: 'CodeUp #21',
    address: '0x97a6ec1ea5810388b6cb513b087e55a65c4bf417',
    date:'Jun 22nd (Thur) 6:30 PM(UTC+1)',
    map_url: 'https://www.google.co.uk/maps/place/Simply+Business/@51.51528,-0.0904011,15z/data=!4m5!3m4!1s0x0:0x70f23f24baccffdc!8m2!3d51.51528!4d-0.0904011',
    location_text: 'Simply Business (99 Gresham St, London EC2V 7NG)',
    description_text: ''
  },
  {
    name: 'Edcon Post conference lunch',
    address: '0x7b249881af36cccd1ab2e4325a8eed2a7848b263',
    date:'Feb 19th (Sun) 12:30(UTC+1)',
    map_url: 'https://www.google.co.uk/maps/place/Mama+Shelter+Paris/@48.8597157,2.4006691,17z/data=!4m5!3m4!1s0x47e66d8670ddcb91:0xb81d5c1e065c8167!8m2!3d48.8597122!4d2.4028631',
    location_text: 'Mama Shelter Paris (109 Rue de Bagnolet, 75020 Paris)',
    description_text: "Mama Shelter Paris is a restaurant of the hotel all the Edcon speakers stay. Their brunch buffet(42€) is a bit pricy but very high quality and quantity, according to @jdetychey"
  },
  {
    name: 'DevCon2 Pre conference dinner',
    address: '0x7473a821fffc1e75524f9b99d6d4e9a2f9c7b12e',
    date: 'Sep 18th (Sun) 7pm(UTC+8)',
    map_url: 'https://goo.gl/maps/Uty16SUcxd42',
    location_text: 'The lobby at Hyatt On the bund (199 Huangpu Road, Shanghai)',
    description_text: "After meeting at the lobby, we will head to  Lost Heaven(17 Yan An Dong Lu, Huangpu District). The table of 10 is booked under Makoto"
  },
]
export default Data;
<commit_msg>Update Ethereum London data<commit_after>import React from 'react';
// This is to add non contract binding data into Dapp.
// May be replaced with IPFS at some point.

let Data = [
  {
    name: 'Ethereum London October 2017',
    address: null,
    date:'Wednesday, October 11, 2017 6:25 PM to 9:00 PM(UTC+1)',
    map_url: 'https://www.google.com/maps/place/Imperial+College+London/@51.4987997,-0.1770659,17z/data=!3m1!4b1!4m5!3m4!1s0x48760567da220a01:0x31911b371c692e86!8m2!3d51.4987997!4d-0.1748772?hl=en',
    location_text: 'Sir Alexander Fleming Building (SAF) LT1 G16',
    description_text: ''
  },
  {
    name: 'Ethereum London September 2017',
    address: '0x56812b5b1c3594af9e0b8a22d07025f5ee3debcd',
    date:'Wednesday, September 13, 2017 6:45 PM to 9:00 PM(UTC+1)',
    map_url: 'https://maps.google.com/maps?f=q&hl=en&q=Huxley+Building%2C+Imperial+College+%2C+London+SW7+2AZ%2C+gb',
    location_text: 'Clore Lecture Theatre, Huxley Building, Imperial College, London (SW7 2AZ)',
    description_text: ''
  },
  {
    name: 'CodeUp #22',
    address: '0x03738b2fd7ab1d8b3003c3e4d83864eef636bed2',
    date:'Sep 7th (Thur) 6:30 PM(UTC+1)',
    map_url: 'https://www.google.co.uk/maps/place/Simply+Business/@51.51528,-0.0904011,15z/data=!4m5!3m4!1s0x0:0x70f23f24baccffdc!8m2!3d51.51528!4d-0.0904011',
    location_text: 'Simply Business (99 Gresham St, London EC2V 7NG)',
    description_text: ''
  },
  {
    name: 'CodeUp #21',
    address: '0x97a6ec1ea5810388b6cb513b087e55a65c4bf417',
    date:'Jun 22nd (Thur) 6:30 PM(UTC+1)',
    map_url: 'https://www.google.co.uk/maps/place/Simply+Business/@51.51528,-0.0904011,15z/data=!4m5!3m4!1s0x0:0x70f23f24baccffdc!8m2!3d51.51528!4d-0.0904011',
    location_text: 'Simply Business (99 Gresham St, London EC2V 7NG)',
    description_text: ''
  },
  {
    name: 'Edcon Post conference lunch',
    address: '0x7b249881af36cccd1ab2e4325a8eed2a7848b263',
    date:'Feb 19th (Sun) 12:30(UTC+1)',
    map_url: 'https://www.google.co.uk/maps/place/Mama+Shelter+Paris/@48.8597157,2.4006691,17z/data=!4m5!3m4!1s0x47e66d8670ddcb91:0xb81d5c1e065c8167!8m2!3d48.8597122!4d2.4028631',
    location_text: 'Mama Shelter Paris (109 Rue de Bagnolet, 75020 Paris)',
    description_text: "Mama Shelter Paris is a restaurant of the hotel all the Edcon speakers stay. Their brunch buffet(42€) is a bit pricy but very high quality and quantity, according to @jdetychey"
  },
  {
    name: 'DevCon2 Pre conference dinner',
    address: '0x7473a821fffc1e75524f9b99d6d4e9a2f9c7b12e',
    date: 'Sep 18th (Sun) 7pm(UTC+8)',
    map_url: 'https://goo.gl/maps/Uty16SUcxd42',
    location_text: 'The lobby at Hyatt On the bund (199 Huangpu Road, Shanghai)',
    description_text: "After meeting at the lobby, we will head to  Lost Heaven(17 Yan An Dong Lu, Huangpu District). The table of 10 is booked under Makoto"
  },
]
export default Data;
<|endoftext|>


<commit_before>// --
// Core.UI.IE7Fixes.js - provides IE7 specific functions
// Copyright (C) 2001-2010 OTRS AG, http://otrs.org/\n";
// --
// $Id: Core.UI.IE7Fixes.js,v 1.2 2010-06-07 11:36:25 mn Exp $
// --
// This software comes with ABSOLUTELY NO WARRANTY. For details, see
// the enclosed file COPYING for license information (AGPL). If you
// did not receive this file, see http://www.gnu.org/licenses/agpl.txt.
// --

"use strict";

var Core = Core || {};

Core.UI = Core.UI || {};

/**
 * @namespace
 * @exports TargetNS as Core.UI.IE7Fixes
 * @description
 *      This namespace contains IE7 specific functions for browser bugfixes
 */
Core.UI.IE7Fixes = (function (TargetNS) {
    /**
     * @function
     * @description
     *      This function implements the focus effects for IE7.
     * @param {String} FocusClass The name of the classes which will be added for focus effect.
     * @return nothing
     */
    TargetNS.InitIE7InputFocus = function (FocusClass) {
        // Exit function, if browser is not IE7
        if (!($.browser.msie && $.browser.version == "7.0"))
            return;

        // If hover class is not given, set it to default
        if (!FocusClass) FocusClass = "Focus";

        // Define mouse events for adding and removing hover class
        $('input[type=text], input[type=password], textarea')
            .live("focusin", function(e) {
                $(this).addClass(FocusClass);
            })
            .live("focusout", function(e) {
                $(this).removeClass(FocusClass);
            });
    };

    /**
     * @function
     * @description
     *      This function implements readonly field styling for IE6.
     * @param {String} ReadonlyClass The name of the class which will be added for styling readonly input fields.
     * @return nothing
     */
    TargetNS.InitIE7InputReadonly = function (ReadonlyClass) {
        // Exit function, if browser is not IE6
        if (!($.browser.msie && $.browser.version == "7.0"))
            return;

        // If style class is not given, set it to default
        if (!ReadonlyClass) ReadonlyClass = 'Readonly';

        // Add ReadonlyClass for readonly inputs
        $('input[type=text][readonly=true], input[type=password][readonly=true], textarea[readonly=true]')
            .addClass(ReadonlyClass)
            .bind('readonly', function() {
                if (!$(this).attr('readonly')) {
                    $(this).removeClass(ReadonlyClass);
                }
                else {
                    $(this).addClass(ReadonlyClass);
                }
            });
    };

    return TargetNS;
}(Core.UI.IE7Fixes || {}));<commit_msg>Shortened custom-event function.<commit_after>// --
// Core.UI.IE7Fixes.js - provides IE7 specific functions
// Copyright (C) 2001-2010 OTRS AG, http://otrs.org/\n";
// --
// $Id: Core.UI.IE7Fixes.js,v 1.3 2010-06-07 11:48:40 mn Exp $
// --
// This software comes with ABSOLUTELY NO WARRANTY. For details, see
// the enclosed file COPYING for license information (AGPL). If you
// did not receive this file, see http://www.gnu.org/licenses/agpl.txt.
// --

"use strict";

var Core = Core || {};

Core.UI = Core.UI || {};

/**
 * @namespace
 * @exports TargetNS as Core.UI.IE7Fixes
 * @description
 *      This namespace contains IE7 specific functions for browser bugfixes
 */
Core.UI.IE7Fixes = (function (TargetNS) {
    /**
     * @function
     * @description
     *      This function implements the focus effects for IE7.
     * @param {String} FocusClass The name of the classes which will be added for focus effect.
     * @return nothing
     */
    TargetNS.InitIE7InputFocus = function (FocusClass) {
        // Exit function, if browser is not IE7
        if (!($.browser.msie && $.browser.version == "7.0"))
            return;

        // If hover class is not given, set it to default
        if (!FocusClass) FocusClass = "Focus";

        // Define mouse events for adding and removing hover class
        $('input[type=text], input[type=password], textarea')
            .live("focusin", function(e) {
                $(this).addClass(FocusClass);
            })
            .live("focusout", function(e) {
                $(this).removeClass(FocusClass);
            });
    };

    /**
     * @function
     * @description
     *      This function implements readonly field styling for IE6.
     * @param {String} ReadonlyClass The name of the class which will be added for styling readonly input fields.
     * @return nothing
     */
    TargetNS.InitIE7InputReadonly = function (ReadonlyClass) {
        // Exit function, if browser is not IE6
        if (!($.browser.msie && $.browser.version == "7.0"))
            return;

        // If style class is not given, set it to default
        if (!ReadonlyClass) ReadonlyClass = 'Readonly';

        // Add ReadonlyClass for readonly inputs
        $('input[type=text][readonly=true], input[type=password][readonly=true], textarea[readonly=true]')
            .addClass(ReadonlyClass)
            .bind('readonly', function() {
                $(this).toggleClass(ReadonlyClass, $(this).attr('readonly'))
            });
    };

    return TargetNS;
}(Core.UI.IE7Fixes || {}));<|endoftext|>


<commit_before>// dependencies
//
import React from 'react';
import update from 'react-addons-update';
import uniqueId from 'lodash/uniqueId';
import classnames from 'classnames';

import Alert from './Alert';
import TextInput from './form/TextInput';

class Form extends React.Component {

    constructor(props) {
        super(props);

        this.state = { validation: {} };

        this.onChildValidationEvent = this.onChildValidationEvent.bind(this);

        // iterate over the children & add the onChange handler
        //
        this.children = React.Children.map(
            this.props.children,
            (child) => {
                const validationKey = uniqueId('form-child-');

                this.state.validation[validationKey] = null;

                return React.cloneElement(child, {
                    validationKey,
                    onChildValidationEvent: this.onChildValidationEvent,
                });
            }
        );
    }

    onChildValidationEvent(validationKey, message) {
        const delta = {};
        delta[validationKey] = { $set: message };

        this.setState(update(this.state, { validation: delta }));
    }

    validationErrors() {
        const errors = [];
        Object.keys(this.state.validation).forEach((key) => {
            if (this.state.validation[key]) {
                errors.push(this.state.validation[key]);
            }
        });
        return errors;
    }

    render() {
        const errors = this.validationErrors();

        const alert = errors.length > 0
            ? <Alert>

Please correct the following problems:

                    {errors.map((err) =>
{err}
)}

            </Alert>
            : '';
        return (
            <form
                className={classnames({
                    'form-inline':     this.props.inline,
                    'form-horizontal': this.props.horizontal,
                })}
            >
                {alert}
                {this.children}
            </form>
        );
    }
}

// set the property types for the component
//
Form.propTypes = {
    children: React.PropTypes.oneOfType([
        React.PropTypes.arrayOf(React.PropTypes.node),
        React.PropTypes.node,
    ]).isRequired,
};

// add the "sub-components"
//
Form.TextInput = TextInput;

// export the component
//
export default Form;
<commit_msg>added inline, horizontal to proptypes<commit_after>// dependencies
//
import React from 'react';
import update from 'react-addons-update';
import uniqueId from 'lodash/uniqueId';
import classnames from 'classnames';

import Alert from './Alert';
import TextInput from './form/TextInput';

class Form extends React.Component {

    constructor(props) {
        super(props);

        this.state = { validation: {} };

        this.onChildValidationEvent = this.onChildValidationEvent.bind(this);

        // iterate over the children & add the onChange handler
        //
        this.children = React.Children.map(
            this.props.children,
            (child) => {
                const validationKey = uniqueId('form-child-');

                this.state.validation[validationKey] = null;

                return React.cloneElement(child, {
                    validationKey,
                    onChildValidationEvent: this.onChildValidationEvent,
                });
            }
        );
    }

    onChildValidationEvent(validationKey, message) {
        const delta = {};
        delta[validationKey] = { $set: message };

        this.setState(update(this.state, { validation: delta }));
    }

    validationErrors() {
        const errors = [];
        Object.keys(this.state.validation).forEach((key) => {
            if (this.state.validation[key]) {
                errors.push(this.state.validation[key]);
            }
        });
        return errors;
    }

    render() {
        const errors = this.validationErrors();

        const alert = errors.length > 0
            ? <Alert>

Please correct the following problems:

                    {errors.map((err) =>
{err}
)}

            </Alert>
            : '';
        return (
            <form
                className={classnames({
                    'form-inline':     this.props.inline,
                    'form-horizontal': this.props.horizontal,
                })}
            >
                {alert}
                {this.children}
            </form>
        );
    }
}

// set the property types for the component
//
Form.propTypes = {
    inline:     React.PropTypes.bool,
    horizontal: React.PropTypes.bool,
    children:   React.PropTypes.oneOfType([
        React.PropTypes.arrayOf(React.PropTypes.node),
        React.PropTypes.node,
    ]).isRequired,
};

// add the "sub-components"
//
Form.TextInput = TextInput;

// export the component
//
export default Form;
<|endoftext|>


<commit_before>import { Component, createElement } from 'react'
import storeShape from '../utils/storeShape'
import shallowEqual from '../utils/shallowEqual'
import wrapActionCreators from '../utils/wrapActionCreators'
import isPlainObject from 'lodash/isPlainObject'
import hoistStatics from 'hoist-non-react-statics'
import invariant from 'invariant'

const defaultMapStateToProps = state => ({}) // eslint-disable-line no-unused-vars
const defaultMapDispatchToProps = dispatch => ({ dispatch })
const defaultMergeProps = (stateProps, dispatchProps, parentProps) => ({
  ...parentProps,
  ...stateProps,
  ...dispatchProps
})

function getDisplayName(WrappedComponent) {
  return WrappedComponent.displayName || WrappedComponent.name || 'Component'
}

function checkStateShape(componentDisplayName, props, methodName) {
  invariant(
    isPlainObject(props),
    '`%s %s` must return an object. Instead received %s.',
    componentDisplayName,
    methodName,
    props
  )
  return props
}

// Helps track hot reloading.
let nextVersion = 0

export default function connect(mapStateToProps, mapDispatchToProps, mergeProps, options = {}) {
  const shouldSubscribe = Boolean(mapStateToProps)
  const mapState = mapStateToProps || defaultMapStateToProps
  const mapDispatch = isPlainObject(mapDispatchToProps) ?
    wrapActionCreators(mapDispatchToProps) :
    mapDispatchToProps || defaultMapDispatchToProps

  const finalMergeProps = mergeProps || defaultMergeProps
  const checkMergedEquals = finalMergeProps !== defaultMergeProps
  const { pure = true, withRef = false } = options

  // Helps track hot reloading.
  const version = nextVersion++

  function computeMergedProps(componentDisplayName, stateProps, dispatchProps, parentProps) {
    const mergedProps = finalMergeProps(stateProps, dispatchProps, parentProps)
    return checkStateShape(componentDisplayName, mergedProps, 'mergeProps')
  }

  return function wrapWithConnect(WrappedComponent) {
    const connectDisplayName = `Connect(${getDisplayName(WrappedComponent)})`

    class Connect extends Component {
      shouldComponentUpdate() {
        return !pure || this.haveOwnPropsChanged || this.hasStoreStateChanged
      }

      constructor(props, context) {
        super(props, context)
        this.version = version
        this.store = props.store || context.store

        invariant(this.store,
          `Could not find "store" in either the context or ` +
          `props of "${connectDisplayName}". ` +
          `Either wrap the root component in a <Provider>, ` +
          `or explicitly pass "store" as a prop to "${connectDisplayName}".`
        )

        const storeState = this.store.getState()
        this.state = { storeState }
        this.clearCache()
      }

      computeStateProps(store, props) {
        if (!this.finalMapStateToProps) {
          return this.configureFinalMapState(store, props)
        }

        const state = store.getState()
        const stateProps = this.doStatePropsDependOnOwnProps ?
          this.finalMapStateToProps(state, props) :
          this.finalMapStateToProps(state)

        return checkStateShape(connectDisplayName, stateProps, 'mapStateToProps')
      }

      configureFinalMapState(store, props) {
        const mappedState = mapState(store.getState(), props)
        const isFactory = typeof mappedState === 'function'

        this.finalMapStateToProps = isFactory ? mappedState : mapState
        this.doStatePropsDependOnOwnProps = this.finalMapStateToProps.length !== 1

        return isFactory ?
          this.computeStateProps(store, props) :
          checkStateShape(connectDisplayName, mappedState, 'mapStateToProps')
      }

      computeDispatchProps(store, props) {
        if (!this.finalMapDispatchToProps) {
          return this.configureFinalMapDispatch(store, props)
        }

        const { dispatch } = store
        const dispatchProps = this.doDispatchPropsDependOnOwnProps ?
          this.finalMapDispatchToProps(dispatch, props) :
          this.finalMapDispatchToProps(dispatch)

        return checkStateShape(connectDisplayName, dispatchProps, 'mapDispatchToProps')
      }

      configureFinalMapDispatch(store, props) {
        const mappedDispatch = mapDispatch(store.dispatch, props)
        const isFactory = typeof mappedDispatch === 'function'

        this.finalMapDispatchToProps = isFactory ? mappedDispatch : mapDispatch
        this.doDispatchPropsDependOnOwnProps = this.finalMapDispatchToProps.length !== 1

        return isFactory ?
          this.computeDispatchProps(store, props) :
          checkStateShape(connectDisplayName, mappedDispatch, 'mapDispatchToProps')
      }

      updateStatePropsIfNeeded() {
        const nextStateProps = this.computeStateProps(this.store, this.props)
        if (this.stateProps && shallowEqual(nextStateProps, this.stateProps)) {
          return false
        }

        this.stateProps = nextStateProps
        return true
      }

      updateDispatchPropsIfNeeded() {
        const nextDispatchProps = this.computeDispatchProps(this.store, this.props)
        if (this.dispatchProps && shallowEqual(nextDispatchProps, this.dispatchProps)) {
          return false
        }

        this.dispatchProps = nextDispatchProps
        return true
      }

      updateMergedPropsIfNeeded() {
        const nextMergedProps = computeMergedProps(connectDisplayName, this.stateProps, this.dispatchProps, this.props)
        if (this.mergedProps && checkMergedEquals && shallowEqual(nextMergedProps, this.mergedProps)) {
          return false
        }

        this.mergedProps = nextMergedProps
        return true
      }

      isSubscribed() {
        return typeof this.unsubscribe === 'function'
      }

      trySubscribe() {
        if (shouldSubscribe && !this.unsubscribe) {
          this.unsubscribe = this.store.subscribe(this.handleChange.bind(this))
          this.handleChange()
        }
      }

      tryUnsubscribe() {
        if (this.unsubscribe) {
          this.unsubscribe()
          this.unsubscribe = null
        }
      }

      componentDidMount() {
        this.trySubscribe()
      }

      componentWillReceiveProps(nextProps) {
        if (!pure || !shallowEqual(nextProps, this.props)) {
          this.haveOwnPropsChanged = true
        }
      }

      componentWillUnmount() {
        this.tryUnsubscribe()
        this.clearCache()
      }

      clearCache() {
        this.dispatchProps = null
        this.stateProps = null
        this.mergedProps = null
        this.haveOwnPropsChanged = true
        this.hasStoreStateChanged = true
        this.renderedElement = null
        this.finalMapDispatchToProps = null
        this.finalMapStateToProps = null
      }

      handleChange() {
        if (!this.unsubscribe) {
          return
        }

        const prevStoreState = this.state.storeState
        const storeState = this.store.getState()

        if (!pure || prevStoreState !== storeState) {
          this.hasStoreStateChanged = true
          this.setState({ storeState })
        }
      }

      getWrappedInstance() {
        invariant(withRef,
          `To access the wrapped instance, you need to specify ` +
          `{ withRef: true } as the fourth argument of the connect() call.`
        )

        return this.refs.wrappedInstance
      }

      render() {
        const {
          haveOwnPropsChanged,
          hasStoreStateChanged,
          renderedElement
        } = this

        this.haveOwnPropsChanged = false
        this.hasStoreStateChanged = false

        let shouldUpdateStateProps = true
        let shouldUpdateDispatchProps = true
        if (pure && renderedElement) {
          shouldUpdateStateProps = hasStoreStateChanged || (
            haveOwnPropsChanged && this.doStatePropsDependOnOwnProps
          )
          shouldUpdateDispatchProps =
            haveOwnPropsChanged && this.doDispatchPropsDependOnOwnProps
        }

        let haveStatePropsChanged = false
        let haveDispatchPropsChanged = false
        if (shouldUpdateStateProps) {
          haveStatePropsChanged = this.updateStatePropsIfNeeded()
        }
        if (shouldUpdateDispatchProps) {
          haveDispatchPropsChanged = this.updateDispatchPropsIfNeeded()
        }

        let haveMergedPropsChanged = true
        if (
          haveStatePropsChanged ||
          haveDispatchPropsChanged ||
          haveOwnPropsChanged
        ) {
          haveMergedPropsChanged = this.updateMergedPropsIfNeeded()
        } else {
          haveMergedPropsChanged = false
        }

        if (!haveMergedPropsChanged && renderedElement) {
          return renderedElement
        }

        if (withRef) {
          this.renderedElement = createElement(WrappedComponent, {
            ...this.mergedProps,
            ref: 'wrappedInstance'
          })
        } else {
          this.renderedElement = createElement(WrappedComponent,
            this.mergedProps
          )
        }

        return this.renderedElement
      }
    }

    Connect.displayName = connectDisplayName
    Connect.WrappedComponent = WrappedComponent
    Connect.contextTypes = {
      store: storeShape
    }
    Connect.propTypes = {
      store: storeShape
    }

    if (process.env.NODE_ENV !== 'production') {
      Connect.prototype.componentWillUpdate = function componentWillUpdate() {
        if (this.version === version) {
          return
        }

        // We are hot reloading!
        this.version = version
        this.trySubscribe()
        this.clearCache()
      }
    }

    return hoistStatics(Connect, WrappedComponent)
  }
}
<commit_msg>use connectDisplayName directly in checkStateShape<commit_after>import { Component, createElement } from 'react'
import storeShape from '../utils/storeShape'
import shallowEqual from '../utils/shallowEqual'
import wrapActionCreators from '../utils/wrapActionCreators'
import isPlainObject from 'lodash/isPlainObject'
import hoistStatics from 'hoist-non-react-statics'
import invariant from 'invariant'

const defaultMapStateToProps = state => ({}) // eslint-disable-line no-unused-vars
const defaultMapDispatchToProps = dispatch => ({ dispatch })
const defaultMergeProps = (stateProps, dispatchProps, parentProps) => ({
  ...parentProps,
  ...stateProps,
  ...dispatchProps
})

function getDisplayName(WrappedComponent) {
  return WrappedComponent.displayName || WrappedComponent.name || 'Component'
}

// Helps track hot reloading.
let nextVersion = 0

export default function connect(mapStateToProps, mapDispatchToProps, mergeProps, options = {}) {
  const shouldSubscribe = Boolean(mapStateToProps)
  const mapState = mapStateToProps || defaultMapStateToProps
  const mapDispatch = isPlainObject(mapDispatchToProps) ?
    wrapActionCreators(mapDispatchToProps) :
    mapDispatchToProps || defaultMapDispatchToProps

  const finalMergeProps = mergeProps || defaultMergeProps
  const checkMergedEquals = finalMergeProps !== defaultMergeProps
  const { pure = true, withRef = false } = options

  // Helps track hot reloading.
  const version = nextVersion++

  return function wrapWithConnect(WrappedComponent) {
    const connectDisplayName = `Connect(${getDisplayName(WrappedComponent)})`

    function checkStateShape(props, methodName) {
      invariant(
        isPlainObject(props),
        '`%s %s` must return an object. Instead received %s.',
        connectDisplayName,
        methodName,
        props
      )
      return props
    }

    function computeMergedProps(stateProps, dispatchProps, parentProps) {
      const mergedProps = finalMergeProps(stateProps, dispatchProps, parentProps)
      return checkStateShape(mergedProps, 'mergeProps')
    }

    class Connect extends Component {
      shouldComponentUpdate() {
        return !pure || this.haveOwnPropsChanged || this.hasStoreStateChanged
      }

      constructor(props, context) {
        super(props, context)
        this.version = version
        this.store = props.store || context.store

        invariant(this.store,
          `Could not find "store" in either the context or ` +
          `props of "${connectDisplayName}". ` +
          `Either wrap the root component in a <Provider>, ` +
          `or explicitly pass "store" as a prop to "${connectDisplayName}".`
        )

        const storeState = this.store.getState()
        this.state = { storeState }
        this.clearCache()
      }

      computeStateProps(store, props) {
        if (!this.finalMapStateToProps) {
          return this.configureFinalMapState(store, props)
        }

        const state = store.getState()
        const stateProps = this.doStatePropsDependOnOwnProps ?
          this.finalMapStateToProps(state, props) :
          this.finalMapStateToProps(state)

        return checkStateShape(stateProps, 'mapStateToProps')
      }

      configureFinalMapState(store, props) {
        const mappedState = mapState(store.getState(), props)
        const isFactory = typeof mappedState === 'function'

        this.finalMapStateToProps = isFactory ? mappedState : mapState
        this.doStatePropsDependOnOwnProps = this.finalMapStateToProps.length !== 1

        return isFactory ?
          this.computeStateProps(store, props) :
          checkStateShape(mappedState, 'mapStateToProps')
      }

      computeDispatchProps(store, props) {
        if (!this.finalMapDispatchToProps) {
          return this.configureFinalMapDispatch(store, props)
        }

        const { dispatch } = store
        const dispatchProps = this.doDispatchPropsDependOnOwnProps ?
          this.finalMapDispatchToProps(dispatch, props) :
          this.finalMapDispatchToProps(dispatch)

        return checkStateShape(dispatchProps, 'mapDispatchToProps')
      }

      configureFinalMapDispatch(store, props) {
        const mappedDispatch = mapDispatch(store.dispatch, props)
        const isFactory = typeof mappedDispatch === 'function'

        this.finalMapDispatchToProps = isFactory ? mappedDispatch : mapDispatch
        this.doDispatchPropsDependOnOwnProps = this.finalMapDispatchToProps.length !== 1

        return isFactory ?
          this.computeDispatchProps(store, props) :
          checkStateShape(mappedDispatch, 'mapDispatchToProps')
      }

      updateStatePropsIfNeeded() {
        const nextStateProps = this.computeStateProps(this.store, this.props)
        if (this.stateProps && shallowEqual(nextStateProps, this.stateProps)) {
          return false
        }

        this.stateProps = nextStateProps
        return true
      }

      updateDispatchPropsIfNeeded() {
        const nextDispatchProps = this.computeDispatchProps(this.store, this.props)
        if (this.dispatchProps && shallowEqual(nextDispatchProps, this.dispatchProps)) {
          return false
        }

        this.dispatchProps = nextDispatchProps
        return true
      }

      updateMergedPropsIfNeeded() {
        const nextMergedProps = computeMergedProps(this.stateProps, this.dispatchProps, this.props)
        if (this.mergedProps && checkMergedEquals && shallowEqual(nextMergedProps, this.mergedProps)) {
          return false
        }

        this.mergedProps = nextMergedProps
        return true
      }

      isSubscribed() {
        return typeof this.unsubscribe === 'function'
      }

      trySubscribe() {
        if (shouldSubscribe && !this.unsubscribe) {
          this.unsubscribe = this.store.subscribe(this.handleChange.bind(this))
          this.handleChange()
        }
      }

      tryUnsubscribe() {
        if (this.unsubscribe) {
          this.unsubscribe()
          this.unsubscribe = null
        }
      }

      componentDidMount() {
        this.trySubscribe()
      }

      componentWillReceiveProps(nextProps) {
        if (!pure || !shallowEqual(nextProps, this.props)) {
          this.haveOwnPropsChanged = true
        }
      }

      componentWillUnmount() {
        this.tryUnsubscribe()
        this.clearCache()
      }

      clearCache() {
        this.dispatchProps = null
        this.stateProps = null
        this.mergedProps = null
        this.haveOwnPropsChanged = true
        this.hasStoreStateChanged = true
        this.renderedElement = null
        this.finalMapDispatchToProps = null
        this.finalMapStateToProps = null
      }

      handleChange() {
        if (!this.unsubscribe) {
          return
        }

        const prevStoreState = this.state.storeState
        const storeState = this.store.getState()

        if (!pure || prevStoreState !== storeState) {
          this.hasStoreStateChanged = true
          this.setState({ storeState })
        }
      }

      getWrappedInstance() {
        invariant(withRef,
          `To access the wrapped instance, you need to specify ` +
          `{ withRef: true } as the fourth argument of the connect() call.`
        )

        return this.refs.wrappedInstance
      }

      render() {
        const {
          haveOwnPropsChanged,
          hasStoreStateChanged,
          renderedElement
        } = this

        this.haveOwnPropsChanged = false
        this.hasStoreStateChanged = false

        let shouldUpdateStateProps = true
        let shouldUpdateDispatchProps = true
        if (pure && renderedElement) {
          shouldUpdateStateProps = hasStoreStateChanged || (
            haveOwnPropsChanged && this.doStatePropsDependOnOwnProps
          )
          shouldUpdateDispatchProps =
            haveOwnPropsChanged && this.doDispatchPropsDependOnOwnProps
        }

        let haveStatePropsChanged = false
        let haveDispatchPropsChanged = false
        if (shouldUpdateStateProps) {
          haveStatePropsChanged = this.updateStatePropsIfNeeded()
        }
        if (shouldUpdateDispatchProps) {
          haveDispatchPropsChanged = this.updateDispatchPropsIfNeeded()
        }

        let haveMergedPropsChanged = true
        if (
          haveStatePropsChanged ||
          haveDispatchPropsChanged ||
          haveOwnPropsChanged
        ) {
          haveMergedPropsChanged = this.updateMergedPropsIfNeeded()
        } else {
          haveMergedPropsChanged = false
        }

        if (!haveMergedPropsChanged && renderedElement) {
          return renderedElement
        }

        if (withRef) {
          this.renderedElement = createElement(WrappedComponent, {
            ...this.mergedProps,
            ref: 'wrappedInstance'
          })
        } else {
          this.renderedElement = createElement(WrappedComponent,
            this.mergedProps
          )
        }

        return this.renderedElement
      }
    }

    Connect.displayName = connectDisplayName
    Connect.WrappedComponent = WrappedComponent
    Connect.contextTypes = {
      store: storeShape
    }
    Connect.propTypes = {
      store: storeShape
    }

    if (process.env.NODE_ENV !== 'production') {
      Connect.prototype.componentWillUpdate = function componentWillUpdate() {
        if (this.version === version) {
          return
        }

        // We are hot reloading!
        this.version = version
        this.trySubscribe()
        this.clearCache()
      }
    }

    return hoistStatics(Connect, WrappedComponent)
  }
}
<|endoftext|>


<commit_before>/*jshint laxcomma:true, smarttabs: true, node:true */
'use strict';
/**
 * @module tastypie/lib/paginator
 * @author Eric Satterwhite
 * @requires util
 * @requires module:class
 * @requires module:class/options
 * @requires mout/lang/kindOf
 * @since 0.1.0
 * @requires xml2js
 * @requires util
 * @requires url
 * @requires events
 * @requires Class
 * @requires Options
 * @requires isNumber
 * @requires clone
 * @requires exceptions
 * @requires debug
 **/

var  xml2js      = require( 'xml2js' )                       // xml2js
	, util       = require( 'util' )                         // util
	, url        = require( 'url' )                          // url
	, debug      = require( 'debug' )('tastypie:paginator' ) // debug
	, events     = require( 'events' )                       // events
	, isNumber   = require( 'mout/lang/isNumber' )           // isNumber
	, Boom       = require('boom')
	, clone      = require( 'mout/lang/clone' )              // clone
	, Class      = require( './class' )                      // Class
	, Options    = require( './class/options' )                 // Options
	, Parent     = require( 'prime-util/prime/parentize' )    // Options
	, exceptions = require( './exceptions' )                 // exceptions
	, Paginator
	;

/**
 * Used to generate pages of array data. Also responsible for creating Meta data packets for api responses
 * @constructor
 * @alias module:tastypie/lib/paginator
 * @param {Object} options
 * @param {Object[]} [options.object=[]] The data to page
 * @param {?Number} [options.limit=null] The maximum number of object to include in a page
 * @param {Number} [options.offset=0] The number of object to skip
 * @param {Request} options.req A hapi.js request object
 * @param {Reply} options.res A hapi.js reply object
 * @example var Paginator = require('tastypie/lib/paginator')
paginator = new Paginator({
	limit: bundle.req.query.limit || 25
, req: bundle.req
, res: bundle.res
, collectionName: 'data'
, objects: []
});

to_be_serialize = paginator.page();
 */
module.exports =
Paginator = Class({
    inherits:events.EventEmitter
  , mixin:[ Parent, Options ]
  , options:{
	  objects:[]
	, limit:null
	, max:1000
	, offset:0
	, req:null
	, res:null
	, collectionName: 'objects'
  }
  , constructor: function( options ){
		this.setOptions( options );
  }

  /**
   * Generates a page of a data set
   * @method module:tastypie/lib/paginator#page
   * @return {Object} page An array sliced from the original data set using offset & limit parameters
   **/
  , page: function page(){
	  var limit = this.limit();
	  var offset = this.offset();
	  var count = this.count();
	  var ret = {
		  meta:{
			  count:count
			, limit: limit
			, offset: offset
		  }
	  };

	  if( limit ){
		  ret.meta.previous = this.previous( limit, offset, count );
		  ret.meta.next = this.next( limit, offset, count );
	  }

	  ret[ this.options.collectionName ] = this.slice( limit, offset );
	  // dereference the request and respons
	  this.setOptions({
			req:undefined
		  , res:undefined
	  });
	  return ret;
  }
  /**
   * Returns  the uri for the next page if their is one
   * @method module:tastypie/lib/paginator#next
   * @param {Number} limit the number of items in the page
   * @param {Number} offset where in the data set to derive the page from
   * @param {Number} count the length of the current data set
   * @return {String} url the URI that can be used to retrieve the next page
   **/
  , next: function next( limit, offset, count ){
	  var value = limit + offset
	  if( value > count - 1 ){
		  return null;
	  }

	  return this.uri(limit, value)
  }
  /**
   * determines the offset for the current data set using options, or pased in request
   * @method module:tastypie/lib/paginator#offset
   * @return {Number} offset THe resulting offset parameter
   **/
  , offset: function offset( ){
	  var offset = this.options.offset;
	  var query = this.options.req.query || {};

	  if( query.offset != null ){
		  offset = parseInt( query.offset, 10 )
	  }

	  if( !isNumber( offset ) || offset<0 ){
	  	var e = new Boom.badRequest("bad offset param: " + offset )
	  	e.req = this.options.req
	  	e.res = this.options.res
	  	return this.emit('error', e)
	  }

	  return offset;
  }
  /**
   * Returns  the uri for the previous page if their is one
   * @method module:tastypie/lib/paginator#previous
   * @param {Number} limit the number of items in the page
   * @param {Number} offset where in the data set to derive the page from
   * @param {Number} count the length of the current data set
   * @return {String} the URI that can be used to retrieve the previous page
   **/
  , previous: function previous( limit, offset, count ){

	  var value = offset - limit;
	  if( value < 0 ){
		  return null;
	  }

	  return this.uri( limit, value )
  }
  /**
   * returns the number of objects in the current data set
   * @method module:tastypie/lib/paginator#count
   * @return {Number}
   **/
  , count: function count(){
		return this.options.count
  }
  /**
   * retuns a slice from the current data set to represent a page
   * @method module:tastypie/lib/paginator#slice
   * @param {Number} limit The maximum number of items to include in the slice
   * @param {Number} offset The starting position in the data set at which to start the slice
   * @return {Array}
   **/
  ,slice: function slice( limit, offset ){
  	return this.options.objects;
  }

  /**
   * returns the number of items that should be included in the data set.
   * Checks req.query for limit or a configured limit option
   * @method module:tastypie/lib/paginator#limit
   * @return {Number}
   **/
  , limit: function limit(){
		var query = (this.options.req || {}).query || {}
		  , lmt
		  ;

		query.limit = query.limit ? parseInt( query.limit, 10) : query.limit;
		lmt = isNumber( query.limit ) ? query.limit ? query.limit : this.options.max : this.options.limit ? this.options.limit : 25;
		lmt = Math.min( lmt || this.options.max, this.options.max );

		if(!isNumber( lmt ) ){
			this.emit(
				'error'
				, new Boom.badRequest('limit must be a number')
			    , this.options.req
				, this.options.res
			);
		}
		return lmt;
  }
  /**
   * generates a URI that will return page of data
   * @method module:tastypie/lib/paginator#uri
   * @param {Number} limit The maximum number of items to include in the slice
   * @param {Number} offset The starting position in the data set at which to start the slice
   * @return {String} a formatted uri
   **/
  , uri: function uri( limit, offset ){
	  var values = clone(this.options.req.query || {});

	  values.limit = limit;
	  values.offset = offset;
	  return url.format({
	  	 pathname:this.options.req.path
	  	 ,query: values
	  });
  }
});
<commit_msg>fix paginator require docs<commit_after>/*jshint laxcomma:true, smarttabs: true, node:true */
'use strict';
/**
 * @module tastypie/lib/paginator
 * @author Eric Satterwhite
 * @requires util
 * @requires module:class
 * @requires module:class/options
 * @requires mout/lang/kindOf
 * @since 0.1.0
 * @requires xml2js
 * @requires util
 * @requires url
 * @requires events
 * @requires debug
 * @requires mout/lang/isNumber
 * @requires mout/lang/clone
 * @requires tastypie/lib/class
 * @requires tastypie/lib/class/options
 * @requires tastypie/lib/exceptions
 **/

var  util       = require( 'util' )                         // util
	, url        = require( 'url' )                          // url
	, debug      = require( 'debug' )('tastypie:paginator' ) // debug
	, events     = require( 'events' )                       // events
	, isNumber   = require( 'mout/lang/isNumber' )           // isNumber
	, Boom       = require('boom')
	, clone      = require( 'mout/lang/clone' )              // clone
	, Class      = require( './class' )                      // Class
	, Options    = require( './class/options' )                 // Options
	, Parent     = require( 'prime-util/prime/parentize' )    // Options
	, exceptions = require( './exceptions' )                 // exceptions
	, Paginator
	;

/**
 * Used to generate pages of array data. Also responsible for creating Meta data packets for api responses
 * @constructor
 * @alias module:tastypie/lib/paginator
 * @param {Object} options
 * @param {Object[]} [options.object=[]] The data to page
 * @param {?Number} [options.limit=null] The maximum number of object to include in a page
 * @param {Number} [options.offset=0] The number of object to skip
 * @param {Request} options.req A hapi.js request object
 * @param {Reply} options.res A hapi.js reply object
 * @example var Paginator = require('tastypie/lib/paginator')
paginator = new Paginator({
	limit: bundle.req.query.limit || 25
, req: bundle.req
, res: bundle.res
, collectionName: 'data'
, objects: []
});

to_be_serialize = paginator.page();
 */
module.exports =
Paginator = Class({
    inherits:events.EventEmitter
  , mixin:[ Parent, Options ]
  , options:{
	  objects:[]
	, limit:null
	, max:1000
	, offset:0
	, req:null
	, res:null
	, collectionName: 'objects'
  }
  , constructor: function( options ){
		this.setOptions( options );
  }

  /**
   * Generates a page of a data set
   * @method module:tastypie/lib/paginator#page
   * @return {Object} page An array sliced from the original data set using offset & limit parameters
   **/
  , page: function page(){
	  var limit = this.limit();
	  var offset = this.offset();
	  var count = this.count();
	  var ret = {
		  meta:{
			  count:count
			, limit: limit
			, offset: offset
		  }
	  };

	  if( limit ){
		  ret.meta.previous = this.previous( limit, offset, count );
		  ret.meta.next = this.next( limit, offset, count );
	  }

	  ret[ this.options.collectionName ] = this.slice( limit, offset );
	  // dereference the request and respons
	  this.setOptions({
			req:undefined
		  , res:undefined
	  });
	  return ret;
  }
  /**
   * Returns  the uri for the next page if their is one
   * @method module:tastypie/lib/paginator#next
   * @param {Number} limit the number of items in the page
   * @param {Number} offset where in the data set to derive the page from
   * @param {Number} count the length of the current data set
   * @return {String} url the URI that can be used to retrieve the next page
   **/
  , next: function next( limit, offset, count ){
	  var value = limit + offset
	  if( value > count - 1 ){
		  return null;
	  }

	  return this.uri(limit, value)
  }
  /**
   * determines the offset for the current data set using options, or pased in request
   * @method module:tastypie/lib/paginator#offset
   * @return {Number} offset THe resulting offset parameter
   **/
  , offset: function offset( ){
	  var offset = this.options.offset;
	  var query = this.options.req.query || {};

	  if( query.offset != null ){
		  offset = parseInt( query.offset, 10 )
	  }

	  if( !isNumber( offset ) || offset<0 ){
	  	var e = new Boom.badRequest("bad offset param: " + offset )
	  	e.req = this.options.req
	  	e.res = this.options.res
	  	return this.emit('error', e)
	  }

	  return offset;
  }
  /**
   * Returns  the uri for the previous page if their is one
   * @method module:tastypie/lib/paginator#previous
   * @param {Number} limit the number of items in the page
   * @param {Number} offset where in the data set to derive the page from
   * @param {Number} count the length of the current data set
   * @return {String} the URI that can be used to retrieve the previous page
   **/
  , previous: function previous( limit, offset, count ){

	  var value = offset - limit;
	  if( value < 0 ){
		  return null;
	  }

	  return this.uri( limit, value )
  }
  /**
   * returns the number of objects in the current data set
   * @method module:tastypie/lib/paginator#count
   * @return {Number}
   **/
  , count: function count(){
		return this.options.count
  }
  /**
   * retuns a slice from the current data set to represent a page
   * @method module:tastypie/lib/paginator#slice
   * @param {Number} limit The maximum number of items to include in the slice
   * @param {Number} offset The starting position in the data set at which to start the slice
   * @return {Array}
   **/
  ,slice: function slice( limit, offset ){
  	return this.options.objects;
  }

  /**
   * returns the number of items that should be included in the data set.
   * Checks req.query for limit or a configured limit option
   * @method module:tastypie/lib/paginator#limit
   * @return {Number}
   **/
  , limit: function limit(){
		var query = (this.options.req || {}).query || {}
		  , lmt
		  ;

		query.limit = query.limit ? parseInt( query.limit, 10) : query.limit;
		lmt = isNumber( query.limit ) ? query.limit ? query.limit : this.options.max : this.options.limit ? this.options.limit : 25;
		lmt = Math.min( lmt || this.options.max, this.options.max );

		if(!isNumber( lmt ) ){
			this.emit(
				'error'
				, new Boom.badRequest('limit must be a number')
			    , this.options.req
				, this.options.res
			);
		}
		return lmt;
  }
  /**
   * generates a URI that will return page of data
   * @method module:tastypie/lib/paginator#uri
   * @param {Number} limit The maximum number of items to include in the slice
   * @param {Number} offset The starting position in the data set at which to start the slice
   * @return {String} a formatted uri
   **/
  , uri: function uri( limit, offset ){
	  var values = clone(this.options.req.query || {});

	  values.limit = limit;
	  values.offset = offset;
	  return url.format({
	  	 pathname:this.options.req.path
	  	 ,query: values
	  });
  }
});
<|endoftext|>


<commit_before>// dependencies
//
import React from 'react';
import update from 'react-addons-update';
import uniqueId from 'lodash/uniqueId';
import classnames from 'classnames';

import Alert from './Alert';
import Dropdown from './form/Dropdown';
import RadioButtonGroup from './form/RadioButtonGroup';
import SubmitButton from './form/SubmitButton';
import TextInput from './form/TextInput';

// @TODO added labelColumns, inputColumns to Form

/**
 * The Form component
 */
class Form extends React.Component {
    /**
     * Construct the Form component instance
     * @param  {Object} props The component properties
     */
    constructor(props) {
        super(props);

        // initialize the state, which consists of the validation messages for
        // any children. This is just an empty object now, but as child
        // components are mounted, they will "call in" via the
        // `onChildValidationEvent` handler, at which time this state will
        // become populated with values
        //
        this.state = {
            validation:   {},
            hasValidated: {},
        };

        // bind `this` to the `isValid` method
        //
        this.isValid = this.isValid.bind(this);

        // bind `this` to the onChildValidationEvent handler
        //
        this.onChildValidationEvent = this.onChildValidationEvent.bind(this);
    }

    /**
     * Get the child context values
     *
     * These  values are availabe for use by children of the Form component.
     *
     * @return {Object} The child context values
     */
    getChildContext() {
        return {
            isValid:                this.isValid(),
            onChildValidationEvent: this.onChildValidationEvent,
        };
    }

    /**
     * Handle a validation event from one of the children of this Form
     * @param  {String} validationKey     A unique key identifying the child
     *                                    component
     * @param  {[type]} childHasValidated A flag to indicate whether the
     *                                    component has validated in response to
     *                                    user input
     * @param  {String|null} message      The validation error message, or null
     *                                    if the component is valid
     */
    onChildValidationEvent(validationKey, childHasValidated, message) {
        // build a change event to update the `validation` and `hasValidated`
        // state
        //
        const validation = {};
        validation[validationKey] = { $set: message };

        const hasValidated = {};
        hasValidated[validationKey] = { $set: !!childHasValidated };

        const delta = { validation, hasValidated };

        // update the Form component state
        //
        this.setState((state) => update(state, delta));
    }

    /**
     * Determine if the form is valid
     * @return {Boolean} If true, then all form components are valid
     */
    isValid() {
        // get the list of keys from the validation state
        //
        const keys = Object.keys(this.state.validation);

        // iterate over the list of keys
        //
        for (let idx = 0; idx < keys.length; idx++) {
            // do we have a validation error message for the current item? if
            // so, return false, since we have at least one component which has
            // failed validation
            //
            if (this.state.validation[keys[idx]]) {
                return false;
            }
        }

        // if we get here, then none of the children have failed validation.
        // Return true
        //
        return true;
    }

    /**
     * Build a list of validation errors for the Form
     * @return {Array} An array of validation errors (possibly empty, if all
     *                 components are valid)
     */
    validationErrors() {
        // declare an array to hold the error messages
        //
        const errors = [];

        // iterate through the keys of the validation state and add non-null
        // messages for children which have validated to the array
        //
        Object.keys(this.state.validation).forEach((key) => {
            if (this.state.hasValidated[key] && this.state.validation[key]) {
                errors.push(this.state.validation[key]);
            }
        });

        // return the list of error messages
        //
        return errors;
    }

    /**
     * Render the component
     * @return {React.Element} The React element describing the component
     */
    render() {
        // get the list of validation error messages for the form
        //
        const errors = this.validationErrors();

        // if we have errors, then add an Alert component describing the
        // problems
        //
        const alert = errors.length > 0
            ? <Alert style="error">

Please correct the following problems:

                    {errors.map((err) =>
{err}
)}

            </Alert>
            : '';

        // render the component and return it
        //
        return (

                {alert}
                {this.props.children}

        );
    }
}

// set the property types for the component
//
Form.propTypes = {
    inline:     React.PropTypes.bool,
    horizontal: React.PropTypes.bool,
    children:   React.PropTypes.oneOfType([
        React.PropTypes.arrayOf(React.PropTypes.node),
        React.PropTypes.node,
    ]).isRequired,
};

// set the child context types to propagate to the children
//
Form.childContextTypes = {
    isValid:                React.PropTypes.bool,
    onChildValidationEvent: React.PropTypes.func,
};

// add the "sub-components" so that they can be imported as part of the same
// package
//
Form.Dropdown = Dropdown;
Form.RadioButtonGroup = RadioButtonGroup;
Form.SubmitButton = SubmitButton;
Form.TextInput = TextInput;

// export the component
//
export default Form;
<commit_msg>registered component<commit_after>// dependencies
//
import React from 'react';
import update from 'react-addons-update';
import uniqueId from 'lodash/uniqueId';
import classnames from 'classnames';

import Alert from './Alert';
import CheckboxGroup from './form/CheckboxGroup';
import Dropdown from './form/Dropdown';
import RadioButtonGroup from './form/RadioButtonGroup';
import SubmitButton from './form/SubmitButton';
import TextInput from './form/TextInput';

// @TODO added labelColumns, inputColumns to Form

/**
 * The Form component
 */
class Form extends React.Component {
    /**
     * Construct the Form component instance
     * @param  {Object} props The component properties
     */
    constructor(props) {
        super(props);

        // initialize the state, which consists of the validation messages for
        // any children. This is just an empty object now, but as child
        // components are mounted, they will "call in" via the
        // `onChildValidationEvent` handler, at which time this state will
        // become populated with values
        //
        this.state = {
            validation:   {},
            hasValidated: {},
        };

        // bind `this` to the `isValid` method
        //
        this.isValid = this.isValid.bind(this);

        // bind `this` to the onChildValidationEvent handler
        //
        this.onChildValidationEvent = this.onChildValidationEvent.bind(this);
    }

    /**
     * Get the child context values
     *
     * These  values are availabe for use by children of the Form component.
     *
     * @return {Object} The child context values
     */
    getChildContext() {
        return {
            isValid:                this.isValid(),
            onChildValidationEvent: this.onChildValidationEvent,
        };
    }

    /**
     * Handle a validation event from one of the children of this Form
     * @param  {String} validationKey     A unique key identifying the child
     *                                    component
     * @param  {[type]} childHasValidated A flag to indicate whether the
     *                                    component has validated in response to
     *                                    user input
     * @param  {String|null} message      The validation error message, or null
     *                                    if the component is valid
     */
    onChildValidationEvent(validationKey, childHasValidated, message) {
        // build a change event to update the `validation` and `hasValidated`
        // state
        //
        const validation = {};
        validation[validationKey] = { $set: message };

        const hasValidated = {};
        hasValidated[validationKey] = { $set: !!childHasValidated };

        const delta = { validation, hasValidated };

        // update the Form component state
        //
        this.setState((state) => update(state, delta));
    }

    /**
     * Determine if the form is valid
     * @return {Boolean} If true, then all form components are valid
     */
    isValid() {
        // get the list of keys from the validation state
        //
        const keys = Object.keys(this.state.validation);

        // iterate over the list of keys
        //
        for (let idx = 0; idx < keys.length; idx++) {
            // do we have a validation error message for the current item? if
            // so, return false, since we have at least one component which has
            // failed validation
            //
            if (this.state.validation[keys[idx]]) {
                return false;
            }
        }

        // if we get here, then none of the children have failed validation.
        // Return true
        //
        return true;
    }

    /**
     * Build a list of validation errors for the Form
     * @return {Array} An array of validation errors (possibly empty, if all
     *                 components are valid)
     */
    validationErrors() {
        // declare an array to hold the error messages
        //
        const errors = [];

        // iterate through the keys of the validation state and add non-null
        // messages for children which have validated to the array
        //
        Object.keys(this.state.validation).forEach((key) => {
            if (this.state.hasValidated[key] && this.state.validation[key]) {
                errors.push(this.state.validation[key]);
            }
        });

        // return the list of error messages
        //
        return errors;
    }

    /**
     * Render the component
     * @return {React.Element} The React element describing the component
     */
    render() {
        // get the list of validation error messages for the form
        //
        const errors = this.validationErrors();

        // if we have errors, then add an Alert component describing the
        // problems
        //
        const alert = errors.length > 0
            ? <Alert style="error">

Please correct the following problems:

                    {errors.map((err) =>
{err}
)}

            </Alert>
            : '';

        // render the component and return it
        //
        return (

                {alert}
                {this.props.children}

        );
    }
}

// set the property types for the component
//
Form.propTypes = {
    inline:     React.PropTypes.bool,
    horizontal: React.PropTypes.bool,
    children:   React.PropTypes.oneOfType([
        React.PropTypes.arrayOf(React.PropTypes.node),
        React.PropTypes.node,
    ]).isRequired,
};

// set the child context types to propagate to the children
//
Form.childContextTypes = {
    isValid:                React.PropTypes.bool,
    onChildValidationEvent: React.PropTypes.func,
};

// add the "sub-components" so that they can be imported as part of the same
// package
//
Form.CheckboxGroup = CheckboxGroup;
Form.Dropdown = Dropdown;
Form.RadioButtonGroup = RadioButtonGroup;
Form.SubmitButton = SubmitButton;
Form.TextInput = TextInput;

// export the component
//
export default Form;
<|endoftext|>