<commit_before>'use strict';

const Boom = require('@hapi/boom');
const LambdaContext = require('./LambdaContext');
const functionHelper = require('./functionHelper');
const debugLog = require('./debugLog');
const {
  capitalizeKeys,
  normalizeMultiValueQuery,
  normalizeQuery,
  nullIfEmpty,
} = require('./utils');
const authCanExecuteResource = require('./authCanExecuteResource');

module.exports = function createAuthScheme(
  authFun,
  authorizerOptions,
  funName,
  endpointPath,
  options,
  serverlessLog,
  servicePath,
  serviceRuntime,
  serverlessService,
) {
  const authFunName = authorizerOptions.name;

  let identityHeader = 'authorization';

  if (authorizerOptions.type !== 'request') {
    const identitySourceMatch = /^method.request.header.((?:\w+-?)+\w+)$/.exec(
      authorizerOptions.identitySource,
    );
    if (!identitySourceMatch || identitySourceMatch.length !== 2) {
      throw new Error(
        `Serverless Offline only supports retrieving tokens from the headers (λ: ${authFunName})`,
      );
    }
    identityHeader = identitySourceMatch[1].toLowerCase();
  }

  const funOptions = functionHelper.getFunctionOptions(
    authFun,
    funName,
    servicePath,
    serviceRuntime,
  );

  // Create Auth Scheme
  return () => ({
    authenticate(request, h) {
      process.env = Object.assign(
        {},
        serverlessService.provider.environment,
        authFun.environment,
        process.env,
      );
      console.log(''); // Just to make things a little pretty
      serverlessLog(
        `Running Authorization function for ${request.method} ${request.path} (λ: ${authFunName})`,
      );

      // Get Authorization header
      const { req } = request.raw;

      // Get path params
      // aws doesn't auto decode path params - hapi does
      const pathParams = { ...request.params };

      let event;
      let handler;

      // Create event Object for authFunction
      //   methodArn is the ARN of the function we are running we are authorizing access to (or not)
      //   Account ID and API ID are not simulated
      if (authorizerOptions.type === 'request') {
        event = {
          headers: {},
          httpMethod: request.method.toUpperCase(),
          multiValueHeaders: {},
          multiValueQueryStringParameters: request.query
            ? normalizeMultiValueQuery(request.query)
            : {},
          path: request.path,
          pathParameters: nullIfEmpty(pathParams),
          queryStringParameters: request.query
            ? normalizeQuery(request.query)
            : {},
          type: 'REQUEST',
        };

        if (req.rawHeaders) {
          for (let i = 0; i < req.rawHeaders.length; i += 2) {
            event.headers[req.rawHeaders[i]] = req.rawHeaders[i + 1];
            event.multiValueHeaders[req.rawHeaders[i]] = (
              event.multiValueHeaders[req.rawHeaders[i]] || []
            ).concat(req.rawHeaders[i + 1]);
          }
        } else {
          event.headers = Object.assign(
            request.headers,
            capitalizeKeys(request.headers),
          );
          event.multiValueHeaders = normalizeMultiValueQuery(event.headers);
        }
      } else {
        const authorization = req.headers[identityHeader];

        const identityValidationExpression = new RegExp(
          authorizerOptions.identityValidationExpression,
        );
        const matchedAuthorization = identityValidationExpression.test(
          authorization,
        );
        const finalAuthorization = matchedAuthorization ? authorization : '';

        debugLog(`Retrieved ${identityHeader} header "${finalAuthorization}"`);

        event = {
          authorizationToken: finalAuthorization,
          type: 'TOKEN',
        };
      }

      const httpMethod = request.method.toUpperCase();
      const apiId = 'random-api-id';
      const accountId = 'random-account-id';
      const resourcePath = request.path.replace(
        new RegExp(`^/${options.stage}`),
        '',
      );

      event.methodArn = `arn:aws:execute-api:${options.region}:${accountId}:${apiId}/${options.stage}/${httpMethod}${resourcePath}`;

      event.requestContext = {
        accountId,
        apiId,
        httpMethod,
        requestId: 'random-request-id',
        resourceId: 'random-resource-id',
        resourcePath,
        stage: options.stage,
      };

      // Create the Authorization function handler
      try {
        handler = functionHelper.createHandler(funOptions, options);
      } catch (err) {
        debugLog(`create authorization function handler error: ${err}`);

        throw Boom.badImplementation(
          null,
          `Error while loading ${authFunName}: ${err.message}`,
        );
      }

      return new Promise((resolve, reject) => {
        let done = false;
        // Creat the Lambda Context for the Auth function
        const lambdaContext = new LambdaContext({
          callback: (err, result, fromPromise) => {
            if (done) {
              const warning = fromPromise
                ? `Warning: Auth function '${authFunName}' returned a promise and also uses a callback!\nThis is problematic and might cause issues in your lambda.`
                : `Warning: callback called twice within Auth function '${authFunName}'!`;

              serverlessLog(warning);

              return;
            }

            done = true;

            // Return an unauthorized response
            const onError = (error) => {
              serverlessLog(
                `Authorization function returned an error response: (λ: ${authFunName})`,
                error,
              );

              return reject(Boom.unauthorized('Unauthorized'));
            };

            if (err) {
              onError(err);

              return;
            }

            const onSuccess = (policy) => {
              // Validate that the policy document has the principalId set
              if (!policy.principalId) {
                serverlessLog(
                  `Authorization response did not include a principalId: (λ: ${authFunName})`,
                  err,
                );

                return reject(
                  Boom.forbidden('No principalId set on the Response'),
                );
              }

              if (
                !authCanExecuteResource(policy.policyDocument, event.methodArn)
              ) {
                serverlessLog(
                  `Authorization response didn't authorize user to access resource: (λ: ${authFunName})`,
                  err,
                );

                return reject(
                  Boom.forbidden(
                    'User is not authorized to access this resource',
                  ),
                );
              }

              serverlessLog(
                `Authorization function returned a successful response: (λ: ${authFunName})`,
                policy,
              );

              // Set the credentials for the rest of the pipeline
              return resolve(
                h.authenticated({
                  credentials: {
                    context: policy.context,
                    usageIdentifierKey: policy.usageIdentifierKey,
                    user: policy.principalId,
                  },
                }),
              );
            };

            if (result && typeof result.then === 'function') {
              debugLog('Auth function returned a promise');
              result.then(onSuccess).catch(onError);
            } else if (result instanceof Error) {
              onError(result);
            } else {
              onSuccess(result);
            }
          },
          functionName: authFun.name,
          memorySize:
            authFun.memorySize || serverlessService.provider.memorySize,
          timeout: authFun.timeout || serverlessService.provider.timeout,
        });

        const x = handler(event, lambdaContext, lambdaContext.done);

        // Promise support
        if (!done) {
          if (x && typeof x.then === 'function') {
            x.then(lambdaContext.succeed).catch(lambdaContext.fail);
          } else if (x instanceof Error) {
            lambdaContext.fail(x);
          }
        }
      });
    },
  });
};
<commit_msg>Move callback out of constructor parameter<commit_after>'use strict';

const Boom = require('@hapi/boom');
const LambdaContext = require('./LambdaContext');
const functionHelper = require('./functionHelper');
const debugLog = require('./debugLog');
const {
  capitalizeKeys,
  normalizeMultiValueQuery,
  normalizeQuery,
  nullIfEmpty,
} = require('./utils');
const authCanExecuteResource = require('./authCanExecuteResource');

module.exports = function createAuthScheme(
  authFun,
  authorizerOptions,
  funName,
  endpointPath,
  options,
  serverlessLog,
  servicePath,
  serviceRuntime,
  serverlessService,
) {
  const authFunName = authorizerOptions.name;

  let identityHeader = 'authorization';

  if (authorizerOptions.type !== 'request') {
    const identitySourceMatch = /^method.request.header.((?:\w+-?)+\w+)$/.exec(
      authorizerOptions.identitySource,
    );
    if (!identitySourceMatch || identitySourceMatch.length !== 2) {
      throw new Error(
        `Serverless Offline only supports retrieving tokens from the headers (λ: ${authFunName})`,
      );
    }
    identityHeader = identitySourceMatch[1].toLowerCase();
  }

  const funOptions = functionHelper.getFunctionOptions(
    authFun,
    funName,
    servicePath,
    serviceRuntime,
  );

  // Create Auth Scheme
  return () => ({
    authenticate(request, h) {
      process.env = Object.assign(
        {},
        serverlessService.provider.environment,
        authFun.environment,
        process.env,
      );
      console.log(''); // Just to make things a little pretty
      serverlessLog(
        `Running Authorization function for ${request.method} ${request.path} (λ: ${authFunName})`,
      );

      // Get Authorization header
      const { req } = request.raw;

      // Get path params
      // aws doesn't auto decode path params - hapi does
      const pathParams = { ...request.params };

      let event;
      let handler;

      // Create event Object for authFunction
      //   methodArn is the ARN of the function we are running we are authorizing access to (or not)
      //   Account ID and API ID are not simulated
      if (authorizerOptions.type === 'request') {
        event = {
          headers: {},
          httpMethod: request.method.toUpperCase(),
          multiValueHeaders: {},
          multiValueQueryStringParameters: request.query
            ? normalizeMultiValueQuery(request.query)
            : {},
          path: request.path,
          pathParameters: nullIfEmpty(pathParams),
          queryStringParameters: request.query
            ? normalizeQuery(request.query)
            : {},
          type: 'REQUEST',
        };

        if (req.rawHeaders) {
          for (let i = 0; i < req.rawHeaders.length; i += 2) {
            event.headers[req.rawHeaders[i]] = req.rawHeaders[i + 1];
            event.multiValueHeaders[req.rawHeaders[i]] = (
              event.multiValueHeaders[req.rawHeaders[i]] || []
            ).concat(req.rawHeaders[i + 1]);
          }
        } else {
          event.headers = Object.assign(
            request.headers,
            capitalizeKeys(request.headers),
          );
          event.multiValueHeaders = normalizeMultiValueQuery(event.headers);
        }
      } else {
        const authorization = req.headers[identityHeader];

        const identityValidationExpression = new RegExp(
          authorizerOptions.identityValidationExpression,
        );
        const matchedAuthorization = identityValidationExpression.test(
          authorization,
        );
        const finalAuthorization = matchedAuthorization ? authorization : '';

        debugLog(`Retrieved ${identityHeader} header "${finalAuthorization}"`);

        event = {
          authorizationToken: finalAuthorization,
          type: 'TOKEN',
        };
      }

      const httpMethod = request.method.toUpperCase();
      const apiId = 'random-api-id';
      const accountId = 'random-account-id';
      const resourcePath = request.path.replace(
        new RegExp(`^/${options.stage}`),
        '',
      );

      event.methodArn = `arn:aws:execute-api:${options.region}:${accountId}:${apiId}/${options.stage}/${httpMethod}${resourcePath}`;

      event.requestContext = {
        accountId,
        apiId,
        httpMethod,
        requestId: 'random-request-id',
        resourceId: 'random-resource-id',
        resourcePath,
        stage: options.stage,
      };

      // Create the Authorization function handler
      try {
        handler = functionHelper.createHandler(funOptions, options);
      } catch (err) {
        debugLog(`create authorization function handler error: ${err}`);

        throw Boom.badImplementation(
          null,
          `Error while loading ${authFunName}: ${err.message}`,
        );
      }

      return new Promise((resolve, reject) => {
        let done = false;

        const callback = (err, result, fromPromise) => {
          if (done) {
            const warning = fromPromise
              ? `Warning: Auth function '${authFunName}' returned a promise and also uses a callback!\nThis is problematic and might cause issues in your lambda.`
              : `Warning: callback called twice within Auth function '${authFunName}'!`;

            serverlessLog(warning);

            return;
          }

          done = true;

          // Return an unauthorized response
          const onError = (error) => {
            serverlessLog(
              `Authorization function returned an error response: (λ: ${authFunName})`,
              error,
            );

            return reject(Boom.unauthorized('Unauthorized'));
          };

          if (err) {
            onError(err);

            return;
          }

          const onSuccess = (policy) => {
            // Validate that the policy document has the principalId set
            if (!policy.principalId) {
              serverlessLog(
                `Authorization response did not include a principalId: (λ: ${authFunName})`,
                err,
              );

              return reject(
                Boom.forbidden('No principalId set on the Response'),
              );
            }

            if (
              !authCanExecuteResource(policy.policyDocument, event.methodArn)
            ) {
              serverlessLog(
                `Authorization response didn't authorize user to access resource: (λ: ${authFunName})`,
                err,
              );

              return reject(
                Boom.forbidden(
                  'User is not authorized to access this resource',
                ),
              );
            }

            serverlessLog(
              `Authorization function returned a successful response: (λ: ${authFunName})`,
              policy,
            );

            // Set the credentials for the rest of the pipeline
            return resolve(
              h.authenticated({
                credentials: {
                  context: policy.context,
                  usageIdentifierKey: policy.usageIdentifierKey,
                  user: policy.principalId,
                },
              }),
            );
          };

          if (result && typeof result.then === 'function') {
            debugLog('Auth function returned a promise');
            result.then(onSuccess).catch(onError);
          } else if (result instanceof Error) {
            onError(result);
          } else {
            onSuccess(result);
          }
        };

        // Creat the Lambda Context for the Auth function
        const lambdaContext = new LambdaContext({
          callback,
          functionName: authFun.name,
          memorySize:
            authFun.memorySize || serverlessService.provider.memorySize,
          timeout: authFun.timeout || serverlessService.provider.timeout,
        });

        const x = handler(event, lambdaContext, lambdaContext.done);

        // Promise support
        if (!done) {
          if (x && typeof x.then === 'function') {
            x.then(lambdaContext.succeed).catch(lambdaContext.fail);
          } else if (x instanceof Error) {
            lambdaContext.fail(x);
          }
        }
      });
    },
  });
};
<|endoftext|>


<commit_before>var React = require('react');
var globals = require('./globals');
var Panel = require('react-bootstrap').Panel;

var ExperimentSetView = module.exports.ExperimentSetView = React.createClass({

    parsedCreationDate(){
        if (!('date_created' in this.props.context)) return null;
        return 'Created ' + (new Date(this.props.context.date_created)).toLocaleString(undefined, {
            year : "numeric",
            month : "long",
            day : "numeric",
            hour : "numeric",
            minute : "numeric"
        });
    },

    parsedStatus(){
        if (!('status' in this.props.context)) return null;
        return { this.props.context.status };
    },

    parsedExperimentSetType(){
        if (!('experimentset_type' in this.props.context)) return null;
        return (

                { this.props.context.experimentset_type }

        );
    },

    render: function() {
        var itemClass = globals.itemClass(this.props.context, 'view-detail panel');
        var title = globals.listing_titles.lookup(this.props.context)({context: this.props.context});
        var sortKeys = Object.keys(this.props.context).sort();
        //var tips = tipsFromSchema(this.props.schemas, context);

        return (

Experiment Set

                        { this.parsedStatus() }

Accession  { title }

{ this.parsedExperimentSetType() }

{ this.parsedCreationDate() }

                <Panel className="data-display panel-body-with-header">

                        {sortKeys.map((ikey, idx) =>

{ ikey }

{ formValue(this.props.schemas, this.props.context[ikey]) }

                        )}

                </Panel>

        );
    }

});

globals.panel_views.register(ExperimentSetView, 'ExperimentSet');

var formValue = function (schemas, item) {
    var toReturn = [];
    if(Array.isArray(item)) {
        for (var i=0; i < item.length; i++){
            toReturn.push(formValue(schemas, item[i]));
        }
    }else if (typeof item === 'object') {
        //toReturn.push(<SubIPanel schemas={schemas} content={item}/>);
        //toReturn.push(item);
        //console.log(item);
    }else{
        if (typeof item === 'string' && item.charAt(0) === '/') {
            toReturn.push({item})
        }else{
            toReturn.push(item);
        }
    }
    return(

{toReturn}

    );
};<commit_msg>FF-314 #comment Ongoing - icons for exp-set status msg<commit_after>var React = require('react');
var globals = require('./globals');
var Panel = require('react-bootstrap').Panel;

var ExperimentSetView = module.exports.ExperimentSetView = React.createClass({

    parsedCreationDate(){
        if (!('date_created' in this.props.context)) return null;
        return 'Created ' + (new Date(this.props.context.date_created)).toLocaleString(undefined, {
            year : "numeric",
            month : "long",
            day : "numeric",
            hour : "numeric",
            minute : "numeric"
        });
    },

    parsedStatus(){
        if (!('status' in this.props.context)) return null;
        var iconClass = null;
        switch (this.props.context.status){

            case 'in review by lab':
            case 'in review by project':
                iconClass = 'ss-stopwatch';
                break;
        }
        console.log(iconClass);
        return  { this.props.context.status };
    },

    parsedExperimentSetType(){
        if (!('experimentset_type' in this.props.context)) return null;
        return (

                { this.props.context.experimentset_type }

        );
    },

    render: function() {
        var itemClass = globals.itemClass(this.props.context, 'view-detail panel');
        var title = globals.listing_titles.lookup(this.props.context)({context: this.props.context});
        var sortKeys = Object.keys(this.props.context).sort();
        //var tips = tipsFromSchema(this.props.schemas, context);

        return (

Experiment Set

                        { this.parsedStatus() }

Accession  { title }

{ this.parsedExperimentSetType() }

{ this.parsedCreationDate() }

                <Panel className="data-display panel-body-with-header">

                        {sortKeys.map((ikey, idx) =>

{ ikey }

{ formValue(this.props.schemas, this.props.context[ikey]) }

                        )}

                </Panel>

        );
    }

});

globals.panel_views.register(ExperimentSetView, 'ExperimentSet');

var formValue = function (schemas, item) {
    var toReturn = [];
    if(Array.isArray(item)) {
        for (var i=0; i < item.length; i++){
            toReturn.push(formValue(schemas, item[i]));
        }
    }else if (typeof item === 'object') {
        //toReturn.push(<SubIPanel schemas={schemas} content={item}/>);
        //toReturn.push(item);
        //console.log(item);
    }else{
        if (typeof item === 'string' && item.charAt(0) === '/') {
            toReturn.push({item})
        }else{
            toReturn.push(item);
        }
    }
    return(

{toReturn}

    );
};<|endoftext|>


<commit_before>/*
Name: Mag-Redux v0.1
Description: MagJS Redux implementation
Author: Michael Glazer
License: MIT
Homepage: https://github.com/magnumjs/mag.js
Example: http://embed.plnkr.co/VvZoqFQk8MqDHYThB8eH/preview
(c) 2015
*/
!function(e){function t(){for(var e=arguments.length,t=Array(e),n=0;e>n;n++)t[n]=arguments[n];return function(e){return t.reduceRight(function(e,t){return t(e)},e)}}function n(e){return e&&"object"==typeof e?(e="function"==typeof e.constructor?Object.getPrototypeOf(e):Object.prototype,null===e?!0:(e=e.constructor,"function"==typeof e&&e instanceof e&&Function.prototype.toString.call(e)===Function.prototype.toString.call(Object))):!1}function r(e,t){return Object.keys(e).reduce(function(n,r){return n[r]=t(e[r],r),n},{})}function o(e,t){return Object.keys(e).reduce(function(n,r){return t(e[r])&&(n[r]=e[r]),n},{})}function i(e,t){return function(){return t(e.apply(void 0,arguments))}}function u(e,t,r){var o=Object.keys(t);return t=r&&r.type===a.INIT?"initialState argument passed to createStore":"previous state received by the reducer",0===o.length?"Store does not have a valid reducer. Make sure the argument passed to combineReducers is an object whose values are reducers.":n(e)?(e=Object.keys(e).filter(function(e){return 0>o.indexOf(e)}),0<e.length?"Unexpected "+(1<e.length?"keys":"key")+" "+('"'+e.join('", "')+'" found in '+t+". ")+"Expected to find one of the known reducer keys instead: "+('"'+o.join('", "')+'". Unexpected keys will be ignored.'):void 0):"The "+t+' has unexpected type of "'+{}.toString.call(e).match(/\s([a-z|A-Z]+)/)[1]+'". Expected argument to be an object with the following '+('keys: "'+o.join('", "')+'"')}function c(e){Object.keys(e).forEach(function(t){var n=e[t];if(void 0===n(void 0,{type:a.INIT}))throw Error('Reducer "'+t+'" returned undefined during initialization. If the state passed to the reducer is undefined, you must explicitly return the initial state. The initial state may not be undefined.');var r="@@redux/PROBE_UNKNOWN_ACTION_"+Math.random().toString(36).substring(7).split("").join(".");if(void 0===n(void 0,{type:r}))throw Error('Reducer "'+t+'" returned undefined when probed with a random type. '+("Don't try to handle "+a.INIT+' or other actions in "redux/*" ')+"namespace. They are considered private. Instead, you must return the current state for any unknown actions, unless it is undefined, in which case you must return the initial state, regardless of the action type. The initial state may not be undefined.")})}var a={INIT:"@@redux/INIT"},s=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n,r=arguments[t];for(n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e};e.Redux={createStore:function(e,t){function r(e){if(!n(e))throw Error("Actions must be plain objects. Use custom middleware for async actions.");if(void 0===e.type)throw Error('Actions may not have an undefined "type" property. Have you misspelled a constant?');if(c)throw Error("Reducers may not dispatch actions.");try{c=!0,i=o(i,e)}finally{c=!1}return u.slice().forEach(function(e){return e()}),e}if("function"!=typeof e)throw Error("Expected the reducer to be a function.");var o=e,i=t,u=[],c=!1;return r({type:a.INIT}),{dispatch:r,subscribe:function(e){return u.push(e),function(){var t=u.indexOf(e);u.splice(t,1)}},getState:function(){return i},replaceReducer:function(e){o=e,r({type:a.INIT})}}},combineReducers:function(e){var t,n=o(e,function(e){return"function"==typeof e});try{c(n)}catch(i){t=i}var a=r(n,function(){});return function(e,o){if(void 0===e&&(e=a),t)throw t;var i=r(n,function(t,n){var r=t(e[n],o);if(void 0===r)throw r=o&&o.type,Error('Reducer "'+n+'" returned undefined handling '+(r&&'"'+r+'"'||"an action")+". To ignore an action, you must explicitly return the previous state.");return r}),c=u(e,i,o);return c&&console.error(c),i}},bindActionCreators:function(e,t){if("function"==typeof e)return i(e,t);if("object"!=typeof e||null===e||void 0===e)throw Error("bindActionCreators expected an object or a function, instead received "+(null===e?"null":typeof e)+'. Did you write "import ActionCreators from" instead of "import * as ActionCreators from"?');return r(e,function(e){return i(e,t)})},applyMiddleware:function(){for(var e=arguments.length,n=Array(e),r=0;e>r;r++)n[r]=arguments[r];return function(e){return function(r,o){var i=e(r,o),u=i.dispatch,c=[],a={getState:i.getState,dispatch:function(e){return u(e)}};return c=n.map(function(e){return e(a)}),u=t.apply(void 0,c)(i.dispatch),s({},i,{dispatch:u})}}},compose:t}}(window),function(e,t){var n=function(e){function t(e,t){var n=Object.assign({},e);delete n.type;var r=Object.keys(n);return t.forEach(function(e,t){void 0!==n[r[t]]&&(n[r[t]]=e)}),Object.assign({},e,n)}var n,r={};for(n in e)r[n]=function(e){var n=[].slice.call(arguments);return[].shift.apply(n),t("function"==typeof e?e.apply({},n):e,n)}.bind({},e[n]);return r};t.reduxConnect=function(r,o,i,u){var c;i=e.combineReducers(i),c=u?e.applyMiddleware.apply({},u)(e.createStore)(i):e.createStore(i);var a={},s=typeof r;return u=typeof o,"function"==u?a=o(c.dispatch):"object"==u&&(o=n(o),a=e.bindActionCreators(o,c.dispatch)),"object"==s&&t.merge(a,c.getState()),function(e,n){var o=t.create(e,n,a);return c.subscribe(function(){var e=c.getState();"function"==s&&(e=r(c.getState())),t.merge(o().getProps(),e)}),o}}}(Redux,mag);
<commit_msg>Update mag-redux.0.1.min.js<commit_after>/*
Mag-Redux v0.21
http://github.com/magnumjs/mag.js
(c) Michael Glazer
License: MIT
*/
!function(e){function t(){for(var e=arguments.length,t=Array(e),n=0;e>n;n++)t[n]=arguments[n];return function(e){return t.reduceRight(function(e,t){return t(e)},e)}}function n(e){return e&&"object"==typeof e?(e="function"==typeof e.constructor?Object.getPrototypeOf(e):Object.prototype,null===e?!0:(e=e.constructor,"function"==typeof e&&e instanceof e&&Function.prototype.toString.call(e)===Function.prototype.toString.call(Object))):!1}function r(e,t){return Object.keys(e).reduce(function(n,r){return n[r]=t(e[r],r),n},{})}function o(e,t){return Object.keys(e).reduce(function(n,r){return t(e[r])&&(n[r]=e[r]),n},{})}function i(e,t){return function(){return t(e.apply(void 0,arguments))}}function u(e,t,r){var o=Object.keys(t);return t=r&&r.type===a.INIT?"initialState argument passed to createStore":"previous state received by the reducer",0===o.length?"Store does not have a valid reducer. Make sure the argument passed to combineReducers is an object whose values are reducers.":n(e)?(e=Object.keys(e).filter(function(e){return 0>o.indexOf(e)}),0<e.length?"Unexpected "+(1<e.length?"keys":"key")+" "+('"'+e.join('", "')+'" found in '+t+". ")+"Expected to find one of the known reducer keys instead: "+('"'+o.join('", "')+'". Unexpected keys will be ignored.'):void 0):"The "+t+' has unexpected type of "'+{}.toString.call(e).match(/\s([a-z|A-Z]+)/)[1]+'". Expected argument to be an object with the following '+('keys: "'+o.join('", "')+'"')}function c(e){Object.keys(e).forEach(function(t){var n=e[t];if(void 0===n(void 0,{type:a.INIT}))throw Error('Reducer "'+t+'" returned undefined during initialization. If the state passed to the reducer is undefined, you must explicitly return the initial state. The initial state may not be undefined.');var r="@@redux/PROBE_UNKNOWN_ACTION_"+Math.random().toString(36).substring(7).split("").join(".");if(void 0===n(void 0,{type:r}))throw Error('Reducer "'+t+'" returned undefined when probed with a random type. '+("Don't try to handle "+a.INIT+' or other actions in "redux/*" ')+"namespace. They are considered private. Instead, you must return the current state for any unknown actions, unless it is undefined, in which case you must return the initial state, regardless of the action type. The initial state may not be undefined.")})}var a={INIT:"@@redux/INIT"},s=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n,r=arguments[t];for(n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e};e.Redux={createStore:function(e,t){function r(e){if(!n(e))throw Error("Actions must be plain objects. Use custom middleware for async actions.");if(void 0===e.type)throw Error('Actions may not have an undefined "type" property. Have you misspelled a constant?');if(c)throw Error("Reducers may not dispatch actions.");try{c=!0,i=o(i,e)}finally{c=!1}return u.slice().forEach(function(e){return e()}),e}if("function"!=typeof e)throw Error("Expected the reducer to be a function.");var o=e,i=t,u=[],c=!1;return r({type:a.INIT}),{dispatch:r,subscribe:function(e){return u.push(e),function(){var t=u.indexOf(e);u.splice(t,1)}},getState:function(){return i},replaceReducer:function(e){o=e,r({type:a.INIT})}}},combineReducers:function(e){var t,n=o(e,function(e){return"function"==typeof e});try{c(n)}catch(i){t=i}var a=r(n,function(){});return function(e,o){if(void 0===e&&(e=a),t)throw t;var i=r(n,function(t,n){var r=t(e[n],o);if(void 0===r)throw r=o&&o.type,Error('Reducer "'+n+'" returned undefined handling '+(r&&'"'+r+'"'||"an action")+". To ignore an action, you must explicitly return the previous state.");return r}),c=u(e,i,o);return c&&console.error(c),i}},bindActionCreators:function(e,t){if("function"==typeof e)return i(e,t);if("object"!=typeof e||null===e||void 0===e)throw Error("bindActionCreators expected an object or a function, instead received "+(null===e?"null":typeof e)+'. Did you write "import ActionCreators from" instead of "import * as ActionCreators from"?');return r(e,function(e){return i(e,t)})},applyMiddleware:function(){for(var e=arguments.length,n=Array(e),r=0;e>r;r++)n[r]=arguments[r];return function(e){return function(r,o){var i=e(r,o),u=i.dispatch,c=[],a={getState:i.getState,dispatch:function(e){return u(e)}};return c=n.map(function(e){return e(a)}),u=t.apply(void 0,c)(i.dispatch),s({},i,{dispatch:u})}}},compose:t}}(window),function(e,t){var n=function(e){function t(e,t){var n=Object.assign({},e);delete n.type;var r=Object.keys(n);return t.forEach(function(e,t){void 0!==n[r[t]]&&(n[r[t]]=e)}),Object.assign({},e,n)}var n,r={};for(n in e)r[n]=function(e){var n=[].slice.call(arguments);return[].shift.apply(n),t("function"==typeof e?e.apply({},n):e,n)}.bind({},e[n]);return r};t.reduxConnect=function(r,o,i,u){var c;i=e.combineReducers(i),c=u?e.applyMiddleware.apply({},u)(e.createStore)(i):e.createStore(i);var a={},s=typeof r;return u=typeof o,"function"==u?a=o(c.dispatch):"object"==u&&(o=n(o),a=e.bindActionCreators(o,c.dispatch)),"object"==s&&t.merge(a,c.getState()),function(e,n){var o=t.create(e,n,a);return c.subscribe(function(){var e=c.getState();"function"==s&&(e=r(c.getState())),t.merge(o().getProps(),e)}),o}}}(Redux,mag);
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
 *
 * WSO2 Inc. licenses this file to you under the Apache License,
 * Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

var palette = new Rickshaw.Color.Palette({scheme: "classic9"});

function drawGraph_connectedcup(from, to) {
    $("#y_axis-temperature").html("");
    $("#smoother-temperature").html("");
    $("#legend-temperature").html("");
    $("#chart-temperature").html("");
    $("#x_axis-temperature").html("");
    $("#slider-temperature").html("");

    $("#y_axis-coffeelevel").html("");
    $("#smoother-coffeelevel").html("");
    $("#legend-coffeelevel").html("");
    $("#chart-coffeelevel").html("");
    $("#x_axis-coffeelevel").html("");
    $("#slider-coffeelevel").html("");

    var devices = $("#connectedcup-details").data("devices");
    var tzOffset = new Date().getTimezoneOffset() * 60;

    var chartWrapperElmId = "#connectedcup-div-chart";
    var graphWidth = $(chartWrapperElmId).width() - 50;
    var temperatureGraphConfig = {
        element: document.getElementById("chart-temperature"),
        width: graphWidth,
        height: 400,
        strokeWidth: 2,
        renderer: 'line',
        interpolation: "linear",
        unstack: true,
        stack: false,
        xScale: d3.time.scale(),
        padding: {top: 0.2, left: 0.02, right: 0.02, bottom: 0.2},
        series: []
    };

    var coffeelevelGraphConfig = {
        element: document.getElementById("chart-coffeelevel"),
        width: graphWidth,
        height: 400,
        strokeWidth: 2,
        renderer: 'line',
        interpolation: "linear",
        unstack: true,
        stack: false,
        xScale: d3.time.scale(),
        padding: {top: 0.2, left: 0.02, right: 0.02, bottom: 0.2},
        series: []
    };

    if (devices) {
        for (var i = 0; i < devices.length; i++) {
            temperatureGraphConfig['series'].push(
                    {
                        'color': palette.color(),
                        'data': [{
                            x: parseInt(new Date().getTime() / 1000),
                            y: 0
                        }],
                        'name': devices[i].name
                    });

            coffeelevelGraphConfig['series'].push(
                {
                    'color': palette.color(),
                    'data': [{
                        x: parseInt(new Date().getTime() / 1000),
                        y: 0
                    }],
                    'name': devices[i].name
                });
        }
    } else {
        temperatureGraphConfig['series'].push(
                {
                    'color': palette.color(),
                    'data': [{
                        x: parseInt(new Date().getTime() / 1000),
                        y: 0
                    }],
                    'name': $("#connectedcup-details").data("devicename")
                });
        coffeelevelGraphConfig['series'].push(
            {
                'color': palette.color(),
                'data': [{
                    x: parseInt(new Date().getTime() / 1000),
                    y: 0
                }],
                'name': $("#connectedcup-details").data("devicename")
            });
    }

    var temperatureGraph = new Rickshaw.Graph(temperatureGraphConfig);
    var coffeelevelGraph = new Rickshaw.Graph(coffeelevelGraphConfig);

    temperatureGraph.render();
    coffeelevelGraph.render

    var xAxisTemepature = new Rickshaw.Graph.Axis.Time({
        graph: temperatureGraph
    });

    xAxisTemepature.render();

    var xAxisCoffeelevel = new Rickshaw.Graph.Axis.Time({
        graph: coffeelevelGraph
    });

    xAxisCoffeelevel.render();

    var yAxisTemperature = new Rickshaw.Graph.Axis.Y({
        graph: temperatureGraph,
        orientation: 'left',
        element: document.getElementById("y_axis-temperature"),
        width: 40,
        height: 410
    });

    yAxisTemperature.render();

    var yAxisCoffeelevel = new Rickshaw.Graph.Axis.Y({
        graph: coffeelevelGraph,
        orientation: 'left',
        element: document.getElementById("y_axis-coffeelevel"),
        width: 40,
        height: 410
    });

    yAxisCoffeelevel.render();

    var slider = new Rickshaw.Graph.RangeSlider.Preview({
        graph: temperatureGraph,
        element: document.getElementById("slider-temperature")
    });

    var legend = new Rickshaw.Graph.Legend({
        graph: temperatureGraph,
        element: document.getElementById('legend-temperature')
    });

    var sliderCoffee = new Rickshaw.Graph.RangeSlider.Preview({
        graph: coffeelevelGraph,
        element: document.getElementById("slider-coffeelevel")
    });

    var legendCoffee = new Rickshaw.Graph.Legend({
        graph: coffeelevelGraph,
        element: document.getElementById('legend-coffeelevel')
    });

    var hoverDetail = new Rickshaw.Graph.HoverDetail({
        graph: temperatureGraph,
        formatter: function (series, x, y) {
            var date = '' +
                       moment((x + tzOffset) * 1000).format('Do MMM YYYY h:mm:ss a') + '';
            var swatch = '';
            return swatch + series.name + ": " + parseInt(y) + '
' + date;
        }
    });

    var hoverDetailCoffeelevel = new Rickshaw.Graph.HoverDetail({
        graph: coffeelevelGraph,
        formatter: function (series, x, y) {
            var date = '' +
                moment((x + tzOffset) * 1000).format('Do MMM YYYY h:mm:ss a') + '';
            var swatch = '';
            return swatch + series.name + ": " + parseInt(y) + '
' + date;
        }
    });

    var shelving = new Rickshaw.Graph.Behavior.Series.Toggle({
        graph: temperatureGraph,
        legend: legend
    });

    var order = new Rickshaw.Graph.Behavior.Series.Order({
        graph: temperatureGraph,
        legend: legend
    });

    var highlighter = new Rickshaw.Graph.Behavior.Series.Highlight({
        graph: temperatureGraph,
        legend: legend
    });

    var shelvingCoffee = new Rickshaw.Graph.Behavior.Series.Toggle({
        graph: coffeelevelGraph,
        legend: legendCoffee
    });

    var orderCoffee = new Rickshaw.Graph.Behavior.Series.Order({
        graph: coffeelevelGraph,
        legend: legendCoffee
    });

    var highlighterCoffee = new Rickshaw.Graph.Behavior.Series.Highlight({
        graph: coffeelevelGraph,
        legend: legendCoffee
    });

    var deviceIndex = 0;

    if (devices) {
        getData();
    } else {
        var backendApiUrl = $("#connectedcup-div-chart").data("backend-api-url") + "/sensors/temperature" + "?from=" + from + "&to=" + to;
        var successCallback = function (data) {
            if (data) {
                drawTemperatureLineGraph(JSON.parse(data));
            }
        };
        invokerUtil.get(backendApiUrl, successCallback, function (message) {
            console.log(message);
        });

        var coffeeLevelApiUrl = $("#connectedcup-div-chart").data("backend-api-url") + "/sensors/coffeelevel"
            + "?from=" + from + "&to=" + to;
        var successCallbackCoffeeLevel = function (data) {
            if (data) {
                drawCoffeeLevelLineGraph(JSON.parse(data));
            }
        };
        invokerUtil.get(coffeeLevelApiUrl, successCallbackCoffeeLevel, function (message) {
            console.log(message);
        });
    }

    function getData() {
        if (deviceIndex >= devices.length) {
            return;
        }
        var backendApiUrl = $("#connectedcup-div-chart").data("backend-api-url") + devices[deviceIndex].deviceIdentifier
            + "/sensors/temperature"
                            + "?from=" + from + "&to=" + to;
        var successCallback = function (data) {
            if (data) {
                drawTemperatureLineGraph(JSON.parse(data));
            }
            deviceIndex++;
            getData();
        };
        invokerUtil.get(backendApiUrl, successCallback, function (message) {
            console.log(message);
            deviceIndex++;
            getData();
        });
        var coffeeLevelApiUrl = $("#connectedcup-div-chart").data("backend-api-url") + devices[deviceIndex].deviceIdentifier
            +  "/sensors/coffeelevel" + "?from=" + from + "&to=" + to;

        var successCallbackCoffeeLevel = function (data) {
            if (data) {
                drawCoffeeLevelLineGraph(JSON.parse(data));
            }
        };
        invokerUtil.get(coffeeLevelApiUrl, successCallbackCoffeeLevel, function (message) {
            console.log(message);
        });
    }

    function drawTemperatureLineGraph(data) {
        if (data.length === 0 || data.length === undefined) {
            return;
        }

        var chartData = [];
        for (var i = 0; i < data.length; i++) {
            chartData.push(
                    {
                        x: parseInt(data[i].values.time) - tzOffset,
                        y: parseInt(data[i].values.temperature)
                    }
            );
        }

        temperatureGraphConfig.series[deviceIndex].data = chartData;
        temperatureGraph.update();
    }

    function drawCoffeeLevelLineGraph(data) {
        if (data.length === 0 || data.length === undefined) {
            return;
        }

        var chartData = [];
        for (var i = 0; i < data.length; i++) {
            chartData.push(
                {
                    x: parseInt(data[i].values.time) - tzOffset,
                    y: parseInt(data[i].values.coffeelevel)
                }
            );
        }

        coffeelevelGraphConfig.series[deviceIndex].data = chartData;
        coffeelevelGraph.update();
    }
}
<commit_msg>fixed formatting issues<commit_after>/*
 * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
 *
 * WSO2 Inc. licenses this file to you under the Apache License,
 * Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

var palette = new Rickshaw.Color.Palette({scheme: "classic9"});

function drawGraph_connectedcup(from, to) {
    $("#y_axis-temperature").html("");
    $("#smoother-temperature").html("");
    $("#legend-temperature").html("");
    $("#chart-temperature").html("");
    $("#x_axis-temperature").html("");
    $("#slider-temperature").html("");

    $("#y_axis-coffeelevel").html("");
    $("#smoother-coffeelevel").html("");
    $("#legend-coffeelevel").html("");
    $("#chart-coffeelevel").html("");
    $("#x_axis-coffeelevel").html("");
    $("#slider-coffeelevel").html("");

    var devices = $("#connectedcup-details").data("devices");
    var tzOffset = new Date().getTimezoneOffset() * 60;

    var chartWrapperElmId = "#connectedcup-div-chart";
    var graphWidth = $(chartWrapperElmId).width() - 50;
    var temperatureGraphConfig = {
        element: document.getElementById("chart-temperature"),
        width: graphWidth,
        height: 400,
        strokeWidth: 2,
        renderer: 'line',
        interpolation: "linear",
        unstack: true,
        stack: false,
        xScale: d3.time.scale(),
        padding: {top: 0.2, left: 0.02, right: 0.02, bottom: 0.2},
        series: []
    };

    var coffeelevelGraphConfig = {
        element: document.getElementById("chart-coffeelevel"),
        width: graphWidth,
        height: 400,
        strokeWidth: 2,
        renderer: 'line',
        interpolation: "linear",
        unstack: true,
        stack: false,
        xScale: d3.time.scale(),
        padding: {top: 0.2, left: 0.02, right: 0.02, bottom: 0.2},
        series: []
    };

    if (devices) {
        for (var i = 0; i < devices.length; i++) {
            temperatureGraphConfig['series'].push(
                    {
                        'color': palette.color(),
                        'data': [{
                            x: parseInt(new Date().getTime() / 1000),
                            y: 0
                        }],
                        'name': devices[i].name
                    });

            coffeelevelGraphConfig['series'].push(
                {
                    'color': palette.color(),
                    'data': [{
                        x: parseInt(new Date().getTime() / 1000),
                        y: 0
                    }],
                    'name': devices[i].name
                });
        }
    } else {
        temperatureGraphConfig['series'].push(
                {
                    'color': palette.color(),
                    'data': [{
                        x: parseInt(new Date().getTime() / 1000),
                        y: 0
                    }],
                    'name': $("#connectedcup-details").data("devicename")
                });
        coffeelevelGraphConfig['series'].push(
            {
                'color': palette.color(),
                'data': [{
                    x: parseInt(new Date().getTime() / 1000),
                    y: 0
                }],
                'name': $("#connectedcup-details").data("devicename")
            });
    }

    var temperatureGraph = new Rickshaw.Graph(temperatureGraphConfig);
    var coffeelevelGraph = new Rickshaw.Graph(coffeelevelGraphConfig);

    temperatureGraph.render();
    coffeelevelGraph.render

    var xAxisTemepature = new Rickshaw.Graph.Axis.Time({
        graph: temperatureGraph
    });

    xAxisTemepature.render();

    var xAxisCoffeelevel = new Rickshaw.Graph.Axis.Time({
        graph: coffeelevelGraph
    });

    xAxisCoffeelevel.render();

    var yAxisTemperature = new Rickshaw.Graph.Axis.Y({
        graph: temperatureGraph,
        orientation: 'left',
        element: document.getElementById("y_axis-temperature"),
        width: 40,
        height: 410
    });

    yAxisTemperature.render();

    var yAxisCoffeelevel = new Rickshaw.Graph.Axis.Y({
        graph: coffeelevelGraph,
        orientation: 'left',
        element: document.getElementById("y_axis-coffeelevel"),
        width: 40,
        height: 410
    });

    yAxisCoffeelevel.render();

    var slider = new Rickshaw.Graph.RangeSlider.Preview({
        graph: temperatureGraph,
        element: document.getElementById("slider-temperature")
    });

    var legend = new Rickshaw.Graph.Legend({
        graph: temperatureGraph,
        element: document.getElementById('legend-temperature')
    });

    var sliderCoffee = new Rickshaw.Graph.RangeSlider.Preview({
        graph: coffeelevelGraph,
        element: document.getElementById("slider-coffeelevel")
    });

    var legendCoffee = new Rickshaw.Graph.Legend({
        graph: coffeelevelGraph,
        element: document.getElementById('legend-coffeelevel')
    });

    var hoverDetail = new Rickshaw.Graph.HoverDetail({
        graph: temperatureGraph,
        formatter: function (series, x, y) {
            var date = '' +
                       moment((x + tzOffset) * 1000).format('Do MMM YYYY h:mm:ss a') + '';
            var swatch = '';
            return swatch + series.name + ": " + parseInt(y) + '
' + date;
        }
    });

    var hoverDetailCoffeelevel = new Rickshaw.Graph.HoverDetail({
        graph: coffeelevelGraph,
        formatter: function (series, x, y) {
            var date = '' +
                moment((x + tzOffset) * 1000).format('Do MMM YYYY h:mm:ss a') + '';
            var swatch = '';
            return swatch + series.name + ": " + parseInt(y) + '
' + date;
        }
    });

    var shelving = new Rickshaw.Graph.Behavior.Series.Toggle({
        graph: temperatureGraph,
        legend: legend
    });

    var order = new Rickshaw.Graph.Behavior.Series.Order({
        graph: temperatureGraph,
        legend: legend
    });

    var highlighter = new Rickshaw.Graph.Behavior.Series.Highlight({
        graph: temperatureGraph,
        legend: legend
    });

    var shelvingCoffee = new Rickshaw.Graph.Behavior.Series.Toggle({
        graph: coffeelevelGraph,
        legend: legendCoffee
    });

    var orderCoffee = new Rickshaw.Graph.Behavior.Series.Order({
        graph: coffeelevelGraph,
        legend: legendCoffee
    });

    var highlighterCoffee = new Rickshaw.Graph.Behavior.Series.Highlight({
        graph: coffeelevelGraph,
        legend: legendCoffee
    });

    var deviceIndex = 0;

    if (devices) {
        getData();
    } else {
        var backendApiUrl = $("#connectedcup-div-chart").data("backend-api-url") + "/sensors/temperature" + "?from=" + from + "&to=" + to;
        var successCallback = function (data) {
            if (data) {
                drawTemperatureLineGraph(JSON.parse(data));
            }
        };
        invokerUtil.get(backendApiUrl, successCallback, function (message) {});

        var coffeeLevelApiUrl = $("#connectedcup-div-chart").data("backend-api-url") + "/sensors/coffeelevel"
            + "?from=" + from + "&to=" + to;
        var successCallbackCoffeeLevel = function (data) {
            if (data) {
                drawCoffeeLevelLineGraph(JSON.parse(data));
            }
        };
        invokerUtil.get(coffeeLevelApiUrl, successCallbackCoffeeLevel, function (message) {
            console.log(message);
        });
    }

    function getData() {
        if (deviceIndex >= devices.length) {
            return;
        }
        var backendApiUrl = $("#connectedcup-div-chart").data("backend-api-url") + devices[deviceIndex].deviceIdentifier
            + "/sensors/temperature"
                            + "?from=" + from + "&to=" + to;
        var successCallback = function (data) {
            if (data) {
                drawTemperatureLineGraph(JSON.parse(data));
            }
            deviceIndex++;
            getData();
        };
        invokerUtil.get(backendApiUrl, successCallback, function (message) {
            console.log(message);
            deviceIndex++;
            getData();
        });
        var coffeeLevelApiUrl = $("#connectedcup-div-chart").data("backend-api-url") + devices[deviceIndex].deviceIdentifier
            +  "/sensors/coffeelevel" + "?from=" + from + "&to=" + to;

        var successCallbackCoffeeLevel = function (data) {
            if (data) {
                drawCoffeeLevelLineGraph(JSON.parse(data));
            }
        };
        invokerUtil.get(coffeeLevelApiUrl, successCallbackCoffeeLevel, function (message) {
            console.log(message);
        });
    }

    function drawTemperatureLineGraph(data) {
        if (data.length === 0 || data.length === undefined) {
            return;
        }

        var chartData = [];
        for (var i = 0; i < data.length; i++) {
            chartData.push(
                {
                    x: parseInt(data[i].values.time) - tzOffset,
                    y: parseInt(data[i].values.temperature)
                }
            );
        }

        temperatureGraphConfig.series[deviceIndex].data = chartData;
        temperatureGraph.update();
    }

    function drawCoffeeLevelLineGraph(data) {
        if (data.length === 0 || data.length === undefined) {
            return;
        }

        var chartData = [];
        for (var i = 0; i < data.length; i++) {
            chartData.push(
                {
                    x: parseInt(data[i].values.time) - tzOffset,
                    y: parseInt(data[i].values.coffeelevel)
                }
            );
        }

        coffeelevelGraphConfig.series[deviceIndex].data = chartData;
        coffeelevelGraph.update();
    }
}
<|endoftext|>


<commit_before>import AboutInfo from '../index';

import expect from 'expect';
import { shallow } from 'enzyme';
import React from 'react';

describe('<AboutInfo />', () => {
  it('Expect to have unit tests specified', () => {
    expect(true).toEqual(false);
  });
});
<commit_msg>Feat: delete about info tests<commit_after><|endoftext|>


<commit_before>
odoo.define('account.section_and_note_backend', function (require) {
// The goal of this file is to contain JS hacks related to allowing
// section and note on sale order and invoice.

// [UPDATED] now also allows configuring products on sale order.

"use strict";
var FieldChar = require('web.basic_fields').FieldChar;
var FieldOne2Many = require('web.relational_fields').FieldOne2Many;
var fieldRegistry = require('web.field_registry');
var ListFieldText = require('web.basic_fields').ListFieldText;
var ListRenderer = require('web.ListRenderer');

var SectionAndNoteListRenderer = ListRenderer.extend({
    /**
     * We want section and note to take the whole line (except handle and trash)
     * to look better and to hide the unnecessary fields.
     *
     * @override
     */
    _renderBodyCell: function (record, node, index, options) {
        var $cell = this._super.apply(this, arguments);

        var isSection = record.data.display_type === 'line_section';
        var isNote = record.data.display_type === 'line_note';

        if (isSection || isNote) {
            if (node.attrs.widget === "handle") {
                return $cell;
            } else if (node.attrs.name === "name") {
                var nbrColumns = this._getNumberOfCols();
                if (this.handleField) {
                    nbrColumns--;
                }
                if (this.addTrashIcon) {
                    nbrColumns--;
                }
                $cell.attr('colspan', nbrColumns);
            } else {
                return $cell.addClass('o_hidden');
            }
        }

        return $cell;
    },
    /**
     * We add the o_is_{display_type} class to allow custom behaviour both in JS and CSS.
     *
     * @override
     */
    _renderRow: function (record, index) {
        var $row = this._super.apply(this, arguments);

        if (record.data.display_type) {
            $row.addClass('o_is_' + record.data.display_type);
        }

        return $row;
    },
    /**
     * We want to add .o_section_and_note_list_view on the table to have stronger CSS.
     *
     * @override
     * @private
     */
    _renderView: function () {
        var self = this;
        return this._super.apply(this, arguments).then(function () {
            self.$('.o_list_table').addClass('o_section_and_note_list_view');
        });
    }
});

// We create a custom widget because this is the cleanest way to do it:
// to be sure this custom code will only impact selected fields having the widget
// and not applied to any other existing ListRenderer.
var SectionAndNoteFieldOne2Many = FieldOne2Many.extend({
    description: "",
    /**
     * We want to use our custom renderer for the list.
     *
     * @override
     */
    _getRenderer: function () {
        if (this.view.arch.tag === 'tree') {
            return SectionAndNoteListRenderer;
        }
        return this._super.apply(this, arguments);
    },
});

// This is a merge between a FieldText and a FieldChar.
// We want a FieldChar for section,
// and a FieldText for the rest (product and note).
var SectionAndNoteFieldText = function (parent, name, record, options) {
    var isSection = record.data.display_type === 'line_section';
    var Constructor = isSection ? FieldChar : ListFieldText;
    return new Constructor(parent, name, record, options);
};

fieldRegistry.add('section_and_note_one2many', SectionAndNoteFieldOne2Many);
fieldRegistry.add('section_and_note_text', SectionAndNoteFieldText);

});
<commit_msg>[IMP] account: allow extension of SectionAndNoteListRenderer<commit_after>
odoo.define('account.section_and_note_backend', function (require) {
// The goal of this file is to contain JS hacks related to allowing
// section and note on sale order and invoice.

// [UPDATED] now also allows configuring products on sale order.

"use strict";
var FieldChar = require('web.basic_fields').FieldChar;
var FieldOne2Many = require('web.relational_fields').FieldOne2Many;
var fieldRegistry = require('web.field_registry');
var ListFieldText = require('web.basic_fields').ListFieldText;
var ListRenderer = require('web.ListRenderer');

var SectionAndNoteListRenderer = ListRenderer.extend({
    /**
     * We want section and note to take the whole line (except handle and trash)
     * to look better and to hide the unnecessary fields.
     *
     * @override
     */
    _renderBodyCell: function (record, node, index, options) {
        var $cell = this._super.apply(this, arguments);

        var isSection = record.data.display_type === 'line_section';
        var isNote = record.data.display_type === 'line_note';

        if (isSection || isNote) {
            if (node.attrs.widget === "handle") {
                return $cell;
            } else if (node.attrs.name === "name") {
                var nbrColumns = this._getNumberOfCols();
                if (this.handleField) {
                    nbrColumns--;
                }
                if (this.addTrashIcon) {
                    nbrColumns--;
                }
                $cell.attr('colspan', nbrColumns);
            } else {
                return $cell.addClass('o_hidden');
            }
        }

        return $cell;
    },
    /**
     * We add the o_is_{display_type} class to allow custom behaviour both in JS and CSS.
     *
     * @override
     */
    _renderRow: function (record, index) {
        var $row = this._super.apply(this, arguments);

        if (record.data.display_type) {
            $row.addClass('o_is_' + record.data.display_type);
        }

        return $row;
    },
    /**
     * We want to add .o_section_and_note_list_view on the table to have stronger CSS.
     *
     * @override
     * @private
     */
    _renderView: function () {
        var self = this;
        return this._super.apply(this, arguments).then(function () {
            self.$('.o_list_table').addClass('o_section_and_note_list_view');
        });
    }
});

// We create a custom widget because this is the cleanest way to do it:
// to be sure this custom code will only impact selected fields having the widget
// and not applied to any other existing ListRenderer.
var SectionAndNoteFieldOne2Many = FieldOne2Many.extend({
    description: "",
    /**
     * We want to use our custom renderer for the list.
     *
     * @override
     */
    _getRenderer: function () {
        if (this.view.arch.tag === 'tree') {
            return SectionAndNoteListRenderer;
        }
        return this._super.apply(this, arguments);
    },
});

// This is a merge between a FieldText and a FieldChar.
// We want a FieldChar for section,
// and a FieldText for the rest (product and note).
var SectionAndNoteFieldText = function (parent, name, record, options) {
    var isSection = record.data.display_type === 'line_section';
    var Constructor = isSection ? FieldChar : ListFieldText;
    return new Constructor(parent, name, record, options);
};

fieldRegistry.add('section_and_note_one2many', SectionAndNoteFieldOne2Many);
fieldRegistry.add('section_and_note_text', SectionAndNoteFieldText);

return SectionAndNoteListRenderer;
});
<|endoftext|>


<commit_before>"use strict";

const http = require("http"),
	serializers = new Map();

// Default serializer
function tenso (arg, err, status = 200, stack = false) {
	return {
		data: arg,
		error: err !== null ? (stack ? err.stack : err.message) || err || http.STATUS_CODES[status] : null,
		links: [],
		status: status
	};
}

serializers.set("application/json", tenso);

module.exports = serializers;
<commit_msg>Updating default serializer<commit_after>"use strict";

const codes = require("http").STATUS_CODES,
	serializers = new Map();

serializers.set("application/json", (arg, err, status = 200, stack = false) => {
	return {
		data: arg,
		error: err !== null ? (stack ? err.stack : err.message) || err || codes[status] : null,
		links: [],
		status: status
	};
});

module.exports = serializers;
<|endoftext|>


<commit_before>import {
  Subject,
  BehaviorSubject,
  Scheduler,
  Observable
} from '@reactivex/rxjs'

import {
  createState,
  filterActions
} from './util/state'

import {
  parseOpts,
  logAgendas,
  logStore
} from './util/logger'

import assert from './util/assert'
import wrapActions from './util/wrapActions'
import isPromise from './util/isPromise'
import isObservable from './util/isObservable'
import warn from './util/warn'

const _scheduleNotice = warn('Dispatcher method `schedule` is deprecated. Please use `next` instead.')
const _dispatchNotice = warn('Dispatcher method `dispatch` is deprecated. Please use `next` instead.')

const KICKSTART_ACTION = { type: '_INIT_' }

export default function createDispatcher(opts = {}) {
  const dispatcher = new Subject()

  const identifier = Symbol()
  const cache = []

  // Options: Scheduler
  const scheduler = opts.scheduler || Scheduler.queue

  // Options: Logging
  const logging = parseOpts(opts.logging)
  if (logging.agendas) {
    logAgendas(dispatcher)
  }

  function nextAgenda(agenda) {
    const obs = agenda
      .subscribeOn(scheduler)
      .publishReplay()
      .refCount()

    dispatcher.next(obs)
  }

  function reduce(fn, init) {
    if (typeof fn[identifier] === 'number') {
      return cache[fn[identifier]].store
    }

    // Generate cache index and set it on the reducer
    const index = cache.length
    fn[identifier] = index

    // Create cursor pointing to the state history
    let cursor = createState(fn, fn(init, KICKSTART_ACTION))
    const initialState = cursor.state

    // Describe states using the series of agendas
    const store = Observable.of(initialState)
      .concat(dispatcher
        .map(agenda => {
          // Reference agenda's root state
          const anchor = cursor

          // Collect agenda's actions
          const actions = []

          // Prepare agenda logger if necessary
          const logger = logging.stores ? logStore(fn.name || index, agenda) : null

          // Map Agenda to consecutive states and catch errors
          return agenda
            .filter(Boolean)
            .map(action => {
              cursor = cursor.doNext(action)
              actions.push(action)

              if (logger) {
                logger.change(action, cursor.state) // Logging new state by action
              }

              return cursor.state
            })
            .catch(err => {
              if (!logger) {
                console.error(err)
              }

              // Filter past actions by all of the failed agenda
              const previousState = cursor.state
              filterActions(anchor, x => actions.indexOf(x) === -1)

              if (logger) {
                logger.revert([ previousState, cursor.state ], err, actions) // Logging reversion
              }

              return Observable.of(cursor.state)
            })
        })
        .mergeAll()
      )
      .distinctUntilChanged()
      .publishReplay(1)

    const subscription = store.connect()

    // Cache the store
    cache.push({
      store,
      subscription
    })

    return store
  }

  // DEPRECATED: dispatch will soon be removed in favor of next
  function dispatch(action) {
    _dispatchNotice()
    assert(typeof action === 'function' || typeof action === 'object',
      'Expected a thunk, promise or action as argument.')

    if (isPromise(action)) {
      nextAgenda(Observable.fromPromise(action))
      return action
    }

    if (typeof action === 'function') {
      const res = action(x => {
        dispatcher.next(Observable.of(x))
      })

      return Promise.resolve(res)
    }

    dispatcher.next(Observable.of(action))
    return Promise.resolve(action)
  }

  // DEPRECATED: dispatch will soon be removed in favor of next
  function schedule(...agendas) {
    _scheduleNotice()
    assert(agendas.reduce((acc, obj) => acc && isObservable(obj), true),
      'Agendas can only be represented by Observables.')

    if (agendas.length === 1) {
      nextAgenda(agendas[0])
    } else if (agendas.length > 1) {
      nextAgenda(Observable.concat(...agendas))
    }
  }

  function next(arg) {
    if (isObservable(arg)) {
      nextAgenda(arg)
    } else if (isPromise(arg)) {
      nextAgenda(Observable.fromPromise(arg))
    } else if (typeof arg === 'function') {
      const res = arg(x => next(x), reduce)
      if (isObservable(res)) {
        nextAgenda(res)
      }
    } else {
      nextAgenda(Observable.of(arg))
    }
  }

  return Object.assign(Object.create(dispatcher), {
    next,
    dispatch,
    schedule,
    reduce,
    wrapActions(arg) {
      return wrapActions({ next }, arg)
    }
  })
}

<commit_msg>Add stricter distinctUntilChanged filter to stores<commit_after>import {
  Subject,
  BehaviorSubject,
  Scheduler,
  Observable
} from '@reactivex/rxjs'

import {
  createState,
  filterActions
} from './util/state'

import {
  parseOpts,
  logAgendas,
  logStore
} from './util/logger'

import assert from './util/assert'
import wrapActions from './util/wrapActions'
import isPromise from './util/isPromise'
import isObservable from './util/isObservable'
import warn from './util/warn'

const _scheduleNotice = warn('Dispatcher method `schedule` is deprecated. Please use `next` instead.')
const _dispatchNotice = warn('Dispatcher method `dispatch` is deprecated. Please use `next` instead.')

const KICKSTART_ACTION = { type: '_INIT_' }

export default function createDispatcher(opts = {}) {
  const dispatcher = new Subject()

  const identifier = Symbol()
  const cache = []

  // Options: Scheduler
  const scheduler = opts.scheduler || Scheduler.queue

  // Options: Logging
  const logging = parseOpts(opts.logging)
  if (logging.agendas) {
    logAgendas(dispatcher)
  }

  function nextAgenda(agenda) {
    const obs = agenda
      .subscribeOn(scheduler)
      .publishReplay()
      .refCount()

    dispatcher.next(obs)
  }

  function reduce(fn, init) {
    if (typeof fn[identifier] === 'number') {
      return cache[fn[identifier]].store
    }

    // Generate cache index and set it on the reducer
    const index = cache.length
    fn[identifier] = index

    // Create cursor pointing to the state history
    let cursor = createState(fn, fn(init, KICKSTART_ACTION))
    const initialState = cursor.state

    // Describe states using the series of agendas
    const store = Observable.of(initialState)
      .concat(dispatcher
        .map(agenda => {
          // Reference agenda's root state
          const anchor = cursor

          // Collect agenda's actions
          const actions = []

          // Prepare agenda logger if necessary
          const logger = logging.stores ? logStore(fn.name || index, agenda) : null

          // Map Agenda to consecutive states and catch errors
          return agenda
            .filter(Boolean)
            .map(action => {
              cursor = cursor.doNext(action)
              actions.push(action)

              if (logger) {
                logger.change(action, cursor.state) // Logging new state by action
              }

              return cursor.state
            })
            .catch(err => {
              if (!logger) {
                console.error(err)
              }

              // Filter past actions by all of the failed agenda
              const previousState = cursor.state
              filterActions(anchor, x => actions.indexOf(x) === -1)

              if (logger) {
                logger.revert([ previousState, cursor.state ], err, actions) // Logging reversion
              }

              return Observable.of(cursor.state)
            })
            .distinctUntilChanged()
        })
        .mergeAll())
      .distinctUntilChanged()
      .publishReplay(1)

    const subscription = store.connect()

    // Cache the store
    cache.push({
      store,
      subscription
    })

    return store
  }

  // DEPRECATED: dispatch will soon be removed in favor of next
  function dispatch(action) {
    _dispatchNotice()
    assert(typeof action === 'function' || typeof action === 'object',
      'Expected a thunk, promise or action as argument.')

    if (isPromise(action)) {
      nextAgenda(Observable.fromPromise(action))
      return action
    }

    if (typeof action === 'function') {
      const res = action(x => {
        dispatcher.next(Observable.of(x))
      })

      return Promise.resolve(res)
    }

    dispatcher.next(Observable.of(action))
    return Promise.resolve(action)
  }

  // DEPRECATED: dispatch will soon be removed in favor of next
  function schedule(...agendas) {
    _scheduleNotice()
    assert(agendas.reduce((acc, obj) => acc && isObservable(obj), true),
      'Agendas can only be represented by Observables.')

    if (agendas.length === 1) {
      nextAgenda(agendas[0])
    } else if (agendas.length > 1) {
      nextAgenda(Observable.concat(...agendas))
    }
  }

  function next(arg) {
    if (isObservable(arg)) {
      nextAgenda(arg)
    } else if (isPromise(arg)) {
      nextAgenda(Observable.fromPromise(arg))
    } else if (typeof arg === 'function') {
      const res = arg(x => next(x), reduce)
      if (isObservable(res)) {
        nextAgenda(res)
      }
    } else {
      nextAgenda(Observable.of(arg))
    }
  }

  return Object.assign(Object.create(dispatcher), {
    next,
    dispatch,
    schedule,
    reduce,
    wrapActions(arg) {
      return wrapActions({ next }, arg)
    }
  })
}

<|endoftext|>


<commit_before>// Constants for variable length encoded binary
var NULL_COLUMN = 251;
var UNSIGNED_CHAR_COLUMN = 251;
var UNSIGNED_SHORT_COLUMN = 252;
var UNSIGNED_INT24_COLUMN = 253;
var UNSIGNED_INT64_COLUMN = 254;

var UNSIGNED_CHAR_LENGTH = 1;
var UNSIGNED_SHORT_LENGTH = 2;
var UNSIGNED_INT24_LENGTH = 3;
var UNSIGNED_INT64_LENGTH = 8;

function BufferReader(buffer) {
  this.buffer = buffer;
  this.position = 0;
}

BufferReader.prototype.readUInt8 = function() {
  var pos = this.position;
  this.position += 1;

  return this.buffer.readUInt8(pos);
};

BufferReader.prototype.readUInt16 = function() {
  var pos = this.position;
  this.position += 2;

  return this.buffer.readUInt16LE(pos);
};

BufferReader.prototype.readUInt32 = function() {
  var pos = this.position;
  this.position += 4;

  return this.buffer.readUInt32LE(pos);
};

BufferReader.prototype.readUInt24 = function() {
  var low = this.readUInt16();
  var high = this.readUInt8();
  return (high << 16) + low;
};

BufferReader.prototype.readUInt64 = function() {
  var pos = this.position;
  this.position += 8;

  // from http://stackoverflow.com/questions/17687307/convert-a-64bit-little-endian-integer-to-number
  return this.buffer.readInt32LE(pos) +
    0x100000000 * this.buffer.readUInt32LE(pos + 4);
};

BufferReader.prototype.readString = function() {
  var strBuf = this.buffer.slice(this.position);
  this.position = this.buffer.length;

  return strBuf.toString('ascii');
};

BufferReader.prototype.readStringInBytes = function(length) {
  var strBuf = this.buffer.slice(this.position, this.position + length);
  this.position += length;

  return strBuf.toString('ascii');
};

BufferReader.prototype.readHexInBytes = function(length) {
  var buf = this.buffer.slice(this.position, this.position + length);
  this.position += length;

  return buf.toString('hex');
};

BufferReader.prototype.readBytesArray = function(length) {
  var result = [];
  var hexString = this.readHexInBytes(length);
  for (var i = 0; i < hexString.length; i = i + 2) {
    result.push(parseInt(hexString.substr(i, 2), 16));
  }
  return result;
};

// Read a variable-length "Length Coded Binary" integer. This is derived
// from the MySQL protocol, and re-used in the binary log format. This
// format uses the first byte to alternately store the actual value for
// integer values <= 250, or to encode the number of following bytes
// used to store the actual value, which can be 2, 3, or 8. It also
// includes support for SQL NULL as a special case.
BufferReader.prototype.readVariant = function() {
  var result = null;
  var firstByte = this.readUInt8();

  if (firstByte < UNSIGNED_CHAR_COLUMN) {
    result = firstByte;
  } else if (firstByte === NULL_COLUMN) {
    result = null;
  } else if (firstByte === UNSIGNED_SHORT_COLUMN) {
    result = this.readUInt16();
  } else if (firstByte === UNSIGNED_INT24_COLUMN) {
    result = this.readUInt24();
  } else if (firstByte === UNSIGNED_INT64_COLUMN) {
    result = this.readUInt64();
  } else {
    throw new Error('Invalid variable-length integer');
  }

  return result;
};

var padWith = function(val, length) {
  var bits = val.split('');
  if (bits.length < length) {
    var left = length - bits.length;
    for (var j = left - 1; j >= 0; j--) {
      bits.unshift('0');
    }
    val = bits.join('');
  }

  return val;
};

// Read an arbitrary-length bitmap, provided its length.
// Returns an array of true/false values.
BufferReader.prototype.readBitArray = function(length) {
  var size = Math.floor((length + 7) / 8);

  var bytes = [];
  for (var i = size - 1; i >= 0; i--) {
    bytes.unshift(this.readUInt8());
  }

  var bitmap = [];
  var bitmapStr = bytes.map(function(aByte) {
    return padWith(aByte.toString(2), 8);
  }).join('');

  for (var k = bitmapStr.length - 1; k >= 0; k--) {
    bitmap.push(bitmapStr[k] === '1');
  }

  return bitmap.slice(0, length);
};

exports.BufferReader = BufferReader;
<commit_msg>Remove unused variables<commit_after>// Constants for variable length encoded binary
var NULL_COLUMN = 251;
var UNSIGNED_CHAR_COLUMN = 251;
var UNSIGNED_SHORT_COLUMN = 252;
var UNSIGNED_INT24_COLUMN = 253;
var UNSIGNED_INT64_COLUMN = 254;

function BufferReader(buffer) {
  this.buffer = buffer;
  this.position = 0;
}

BufferReader.prototype.readUInt8 = function() {
  var pos = this.position;
  this.position += 1;

  return this.buffer.readUInt8(pos);
};

BufferReader.prototype.readUInt16 = function() {
  var pos = this.position;
  this.position += 2;

  return this.buffer.readUInt16LE(pos);
};

BufferReader.prototype.readUInt32 = function() {
  var pos = this.position;
  this.position += 4;

  return this.buffer.readUInt32LE(pos);
};

BufferReader.prototype.readUInt24 = function() {
  var low = this.readUInt16();
  var high = this.readUInt8();
  return (high << 16) + low;
};

BufferReader.prototype.readUInt64 = function() {
  var pos = this.position;
  this.position += 8;

  // from http://stackoverflow.com/questions/17687307/convert-a-64bit-little-endian-integer-to-number
  return this.buffer.readInt32LE(pos) +
    0x100000000 * this.buffer.readUInt32LE(pos + 4);
};

BufferReader.prototype.readString = function() {
  var strBuf = this.buffer.slice(this.position);
  this.position = this.buffer.length;

  return strBuf.toString('ascii');
};

BufferReader.prototype.readStringInBytes = function(length) {
  var strBuf = this.buffer.slice(this.position, this.position + length);
  this.position += length;

  return strBuf.toString('ascii');
};

BufferReader.prototype.readHexInBytes = function(length) {
  var buf = this.buffer.slice(this.position, this.position + length);
  this.position += length;

  return buf.toString('hex');
};

BufferReader.prototype.readBytesArray = function(length) {
  var result = [];
  var hexString = this.readHexInBytes(length);
  for (var i = 0; i < hexString.length; i = i + 2) {
    result.push(parseInt(hexString.substr(i, 2), 16));
  }
  return result;
};

// Read a variable-length "Length Coded Binary" integer. This is derived
// from the MySQL protocol, and re-used in the binary log format. This
// format uses the first byte to alternately store the actual value for
// integer values <= 250, or to encode the number of following bytes
// used to store the actual value, which can be 2, 3, or 8. It also
// includes support for SQL NULL as a special case.
BufferReader.prototype.readVariant = function() {
  var result = null;
  var firstByte = this.readUInt8();

  if (firstByte < UNSIGNED_CHAR_COLUMN) {
    result = firstByte;
  } else if (firstByte === NULL_COLUMN) {
    result = null;
  } else if (firstByte === UNSIGNED_SHORT_COLUMN) {
    result = this.readUInt16();
  } else if (firstByte === UNSIGNED_INT24_COLUMN) {
    result = this.readUInt24();
  } else if (firstByte === UNSIGNED_INT64_COLUMN) {
    result = this.readUInt64();
  } else {
    throw new Error('Invalid variable-length integer');
  }

  return result;
};

var padWith = function(val, length) {
  var bits = val.split('');
  if (bits.length < length) {
    var left = length - bits.length;
    for (var j = left - 1; j >= 0; j--) {
      bits.unshift('0');
    }
    val = bits.join('');
  }

  return val;
};

// Read an arbitrary-length bitmap, provided its length.
// Returns an array of true/false values.
BufferReader.prototype.readBitArray = function(length) {
  var size = Math.floor((length + 7) / 8);

  var bytes = [];
  for (var i = size - 1; i >= 0; i--) {
    bytes.unshift(this.readUInt8());
  }

  var bitmap = [];
  var bitmapStr = bytes.map(function(aByte) {
    return padWith(aByte.toString(2), 8);
  }).join('');

  for (var k = bitmapStr.length - 1; k >= 0; k--) {
    bitmap.push(bitmapStr[k] === '1');
  }

  return bitmap.slice(0, length);
};

exports.BufferReader = BufferReader;
<|endoftext|>


<commit_before>import React, {
  StyleSheet,
  Text,
  TextInput,
  View,
  Platform,
  DatePickerIOS,
} from 'react-native'
import Styles from '../../styles/Styles'
import ViewText from '../ViewText'

const DateQuestionIOS = React.createClass ({
  propTypes: {
    id: React.PropTypes.string.isRequired,
    text: React.PropTypes.string.isRequired,
    index: React.PropTypes.number.isRequired,
    value: React.PropTypes.object,
    mode: React.PropTypes.string,
    onChange: React.PropTypes.func.isRequired,
  },

  getDefaultProps: function () {
    return {
      value: new Date(),
      timeZoneOffset: (-1) * (new Date()).getTimezoneOffset(),
      mode: 'date',
    };
  },

  getInitialState: function() {
    return {
      value: this.checkDate(this.props.value),
      timeZoneOffsetInHours: this.props.timeZoneOffset,
    }
  },

  /* Methods */
  handleChange(value) {
    this.setState({
      value: value
    })
    this.props.onChange(value)
  },

  checkDate(value) {
    if (typeof value === 'string') {
      try {
        value = new Date(value);
      } catch(e) {
        console.error('could not parse date: ' + value);
      }
    }
    return value;
  },

  /* Render */
  render() {
    // Due to a bug in react-native's source, DatePickerIOS is currently unstable and may cause problems with rendering.
    // Issue: https://github.com/facebook/react-native/issues/6264
    // PR fix: https://github.com/facebook/react-native/pull/7472

    return (
      <View style={Styles.question.block}>
        <ViewText
          style={Styles.question.header}
          textStyle={Styles.question.headerText}>
            Question #{this.props.index}
        </ViewText>
        <Text style={[Styles.type.h3, Styles.question.text]}>{this.props.text}</Text>
        <Text>Notice: Date Picker for iOS is currently unstable.</Text>
        <DatePickerIOS
          mode={this.props.mode}
          timeZoneOffsetInMinutes={this.props.timeZoneOffset}
          onDateChange={this.handleChange}
          date={this.checkDate(this.state.value)}
          style={{marginLeft: -9}}
          />
      </View>
    )
  }
})

module.exports = DateQuestionIOS

<commit_msg>Adds value that went missing on conflict for DateQuestionIOS.<commit_after>import React, {
  StyleSheet,
  Text,
  TextInput,
  View,
  Platform,
  DatePickerIOS,
} from 'react-native'
import Styles from '../../styles/Styles'
import ViewText from '../ViewText'

const DateQuestionIOS = React.createClass ({
  propTypes: {
    id: React.PropTypes.string.isRequired,
    text: React.PropTypes.string.isRequired,
    index: React.PropTypes.number.isRequired,
    value: React.PropTypes.oneOfType([
      React.PropTypes.string,
      React.PropTypes.instanceOf(Date)
    ]),
    mode: React.PropTypes.string,
    onChange: React.PropTypes.func.isRequired,
  },

  getDefaultProps: function () {
    return {
      value: new Date(),
      timeZoneOffset: (-1) * (new Date()).getTimezoneOffset(),
      mode: 'date',
    };
  },

  getInitialState: function() {
    return {
      value: this.checkDate(this.props.value),
      timeZoneOffsetInHours: this.props.timeZoneOffset,
    }
  },

  /* Methods */
  handleChange(value) {
    this.setState({
      value: value
    })
    this.props.onChange(value)
  },

  checkDate(value) {
    if (typeof value === 'string') {
      try {
        value = new Date(value);
      } catch(e) {
        console.error('could not parse date: ' + value);
      }
    }
    return value;
  },

  /* Render */
  render() {
    // Due to a bug in react-native's source, DatePickerIOS is currently unstable and may cause problems with rendering.
    // Issue: https://github.com/facebook/react-native/issues/6264
    // PR fix: https://github.com/facebook/react-native/pull/7472

    return (
      <View style={Styles.question.block}>
        <ViewText
          style={Styles.question.header}
          textStyle={Styles.question.headerText}>
            Question #{this.props.index}
        </ViewText>
        <Text style={[Styles.type.h3, Styles.question.text]}>{this.props.text}</Text>
        <Text>Notice: Date Picker for iOS is currently unstable.</Text>
        <DatePickerIOS
          mode={this.props.mode}
          timeZoneOffsetInMinutes={this.props.timeZoneOffset}
          onDateChange={this.handleChange}
          date={this.checkDate(this.state.value)}
          style={{marginLeft: -9}}
          />
      </View>
    )
  }
})

module.exports = DateQuestionIOS

<|endoftext|>


<commit_before>const DocumentDBClient = require('documentdb').DocumentClient;
const config = {
    DatabaseId: "mean-dev",
    CollectionId: "users",
    Host: process.env.DocDb_Host,
    AuthKey: process.env.DocDb_AuthKey,
};

config.CollLink = 'dbs/' + config.DatabaseId + '/colls/' + config.TwitterCollectionId

module.exports = function (context, message) {

    let err = null;

    const docDbClient = new DocumentDBClient(config.Host, { masterKey: config.AuthKey });
    var querySpec = {
        query: 'SELECT * FROM c WHERE (c.twitter[\'$id\'] = @userid AND \'twitter\' = @platform) AND (c.instagram[\'$id\'] = @userid AND \'instagram\' = @platform) AND (c.facebook[\'$id\'] = @userid AND \'facebook\' = @platform)',
        parameters: [{
            name: '@userid',
            value: message.userid
        },
        {
            name: '@platform',
            value: message.platform
        }]
    };

    let datas = docDbClient.queryCollections(config.CollLink, querySpec);
    let userdata = datas[0];
    context.log(userdata);//TEMP LOGGING

    if (!userdata) {
        console.log('Not tracking user');

        err = new Error('Not tracking user');
    }

    if (!userdata.twitter && !userdata.facebook || !userdata.instagram) {
        console.log('No social profiles');

        err = new Error('No social profiles');
    }

    if (!userdata.id) {
        console.log('No user id');

        err = new Error('No social profiles');
    }

    let data = new Object();

    if (!err) {
        data.userid = userdata.id;
        data.platform = message.platform;
        data.mediaid = message.mediaid;

        if (message.twitter) {
            console.log('adding twitter');

            data.twitter = {
                id: message.twitter.$id,
                token: message.twitter.token,
                username: message.twitter.username,
            };
        }

        if (message.instagram) {
            console.log('adding instagram');

            data.instagram = {
                id: message.instagram.$id,
                token: message.instagram.token,
                username: message.instagram.username,
            };
        }

        if (message.facebook) {
            console.log('adding facebook');

            data.facebook = {
                id: message.facebook.$id,
                token: message.facebook.token,
                username: message.facebook.email,
            };
        }
    }

    context.done(err, data);
};<commit_msg>fix action<commit_after>const DocumentDBClient = require('documentdb').DocumentClient;
const config = {
    DatabaseId: "mean-dev",
    CollectionId: "users",
    Host: process.env.DocDb_Host,
    AuthKey: process.env.DocDb_AuthKey,
};

config.CollLink = 'dbs/' + config.DatabaseId + '/colls/' + config.TwitterCollectionId

module.exports = function (context, message) {

    let err = null;

    const docDbClient = new DocumentDBClient(config.Host, { masterKey: config.AuthKey });
    var querySpec = {
        query: 'SELECT * FROM c WHERE (c.twitter[\'$id\'] = @userid AND \'twitter\' = @platform) AND (c.instagram[\'$id\'] = @userid AND \'instagram\' = @platform) AND (c.facebook[\'$id\'] = @userid AND \'facebook\' = @platform)',
        parameters: [{
            name: '@userid',
            value: message.userid
        },
        {
            name: '@platform',
            value: message.platform
        }]
    };

    let datas = docDbClient.queryCollections(config.CollLink, querySpec);
    context.log(datas);//TEMP LOGGING
    let userdata = datas[0];
    context.log(userdata);//TEMP LOGGING

    if (!userdata || userdata == undefined) {
        console.log('Not tracking user');

        err = new Error('Not tracking user');
    }

    if (!userdata.twitter && !userdata.facebook || !userdata.instagram) {
        console.log('No social profiles');

        err = new Error('No social profiles');
    }

    if (!userdata.id) {
        console.log('No user id');

        err = new Error('No social profiles');
    }

    let data = new Object();

    if (!err) {
        data.userid = userdata.id;
        data.platform = message.platform;
        data.mediaid = message.mediaid;

        if (message.twitter) {
            console.log('adding twitter');

            data.twitter = {
                id: message.twitter.$id,
                token: message.twitter.token,
                username: message.twitter.username,
            };
        }

        if (message.instagram) {
            console.log('adding instagram');

            data.instagram = {
                id: message.instagram.$id,
                token: message.instagram.token,
                username: message.instagram.username,
            };
        }

        if (message.facebook) {
            console.log('adding facebook');

            data.facebook = {
                id: message.facebook.$id,
                token: message.facebook.token,
                username: message.facebook.email,
            };
        }
    }

    context.done(err, data);
};<|endoftext|>


<commit_before>'use strict';

// Core module config

angular.module('core')
    .config(['$facebookProvider',
        function($facebookProvider)
        {
            $facebookProvider.setAppId('1664525490499797');
            $facebookProvider.setPermissions('email,user_likes,friends');
            $facebookProvider.setCustomInit({
                xfbml: true

            });

        }
    ]).run( function( $rootScope ) {

        // Load the facebook SDK asynchronously
          (function(){

                 window.onload = function() {

                  var options = { scope: 'profile' };

                    amazon.Login.authorize(options,'/api/auth/amazon/callback', function(response) {

                       if ( response.error ) {
                           alert('oauth error ' + response.error);
                           return;
                       }
                       alert('success: ' + response.access_token);
                   });

               };

            // If we've already installed the SDK, we're done
            if (document.getElementById('facebook-jssdk')) {return;}

            // Get the first script element, which we'll use to find the parent node
            var firstScriptElement = document.getElementsByTagName('script')[0];

            // Create a new script element and set its id
            var facebookJS = document.createElement('script');
            facebookJS.id = 'facebook-jssdk';

            // Set the new script's source to the source of the Facebook JS SDK
            facebookJS.src = '//connect.facebook.net/en_US/all.js';

            // Insert the Facebook JS SDK

            firstScriptElement.parentNode.insertBefore(facebookJS, firstScriptElement);
        }());
    });

<commit_msg>global declaration<commit_after>'use strict';

// Core module config

angular.module('core')
    .config(['$facebookProvider',
        function($facebookProvider)
        {
            $facebookProvider.setAppId('1664525490499797');
            $facebookProvider.setPermissions('email,user_likes,friends');
            $facebookProvider.setCustomInit({
                xfbml: true

            });

        }
    ]).run( function( $rootScope ) {

        // Load the facebook SDK asynchronously
          (function(){

                 window.onload = function() {

                  var options = { scope: 'profile' };

                    amazon.Login.authorize(options,function(response) {

                       if ( response.error ) {
                           alert('oauth error ' + response.error);
                           return;
                       }
                       alert('success: ' + response.access_token);
                   });

               };

            // If we've already installed the SDK, we're done
            if (document.getElementById('facebook-jssdk')) {return;}

            // Get the first script element, which we'll use to find the parent node
            var firstScriptElement = document.getElementsByTagName('script')[0];

            // Create a new script element and set its id
            var facebookJS = document.createElement('script');
            facebookJS.id = 'facebook-jssdk';

            // Set the new script's source to the source of the Facebook JS SDK
            facebookJS.src = '//connect.facebook.net/en_US/all.js';

            // Insert the Facebook JS SDK

            firstScriptElement.parentNode.insertBefore(facebookJS, firstScriptElement);
        }());
    });

<|endoftext|>


<commit_before>import { createAction } from 'redux-actions';
import _ from 'lodash';

import { decryptFrom } from 'utility/nacl';
import { appendMessage } from 'js/actions/data/messages';
import { ONLINE, OFFLINE, findUser, setOnlineStatus } from 'actions/data/users';
import redux from 'js/redux-store';

import notify from 'js/notifications';

export const DECRYPTING_MESSAGE = 'message-processor/DECRYPTING_MESSAGE';
export const DECRYPTION_COMPLETE = 'message-processor/DECRYPTION_COMPLETE';

export const decryptingMessage = createAction(DECRYPTING_MESSAGE);
export const decryptionComplete = createAction(DECRYPTION_COMPLETE);

export const APP_NAME = 'tanqueRéact';
export const APP_VERSION = '0.1';

export function processMessage(socketPayload) {
  return (dispatch, getState) => {
    const {
      status,
      uid: from,
      message: encryptedPayload
    } = socketPayload;

    if (_.isEmpty(socketPayload)) return;

    if (status === 404) return process404(socketPayload);

    const state = getState();

    return processChatMessage(encryptedPayload, from, state);
  };
}

function process404(messagePayload) {
  const uid = messagePayload.detail;

  redux.dispatch(setOnlineStatus(uid, OFFLINE));
}

function processChatMessage(messagePayload, fromUid, state) {
  const users = state.data.users.records;
  const { privateKey } = state.identity.config;
  const decrypted = decrypt(messagePayload, fromUid, users, privateKey);

  // tell the UI that a message has been received
  redux.dispatch(appendMessage(decrypted));

  // because we received something from somebody,
  // mark them as online.
  redux.dispatch(setOnlineStatus(decrypted.sender.uid, ONLINE));

  notify(decrypted);

  return decrypted;
}

function decrypt(encryptedPayload, fromUid, users, privateKey) {
  redux.dispatch(decryptingMessage({ encryptedPayload }));
  const publicKey = findUser(fromUid, users).publickey;

  const decryptedPayloadJson = decryptFrom(
    encryptedPayload,
    publicKey,
    privateKey
  );

  const decryptedPayload = JSON.parse(decryptedPayloadJson);

  redux.dispatch(decryptionComplete({ decryptedPayload }));

  return decryptedPayload;
}
<commit_msg>add console message for user not found<commit_after>import { createAction } from 'redux-actions';
import _ from 'lodash';

import { decryptFrom } from 'utility/nacl';
import { appendMessage } from 'js/actions/data/messages';
import { ONLINE, OFFLINE, findUser, setOnlineStatus } from 'actions/data/users';
import redux from 'js/redux-store';
import notify from 'js/notifications';
import { toastError } from 'utility/toast';

export const DECRYPTING_MESSAGE = 'message-processor/DECRYPTING_MESSAGE';
export const DECRYPTION_COMPLETE = 'message-processor/DECRYPTION_COMPLETE';

export const decryptingMessage = createAction(DECRYPTING_MESSAGE);
export const decryptionComplete = createAction(DECRYPTION_COMPLETE);

export const APP_NAME = 'tanqueRéact';
export const APP_VERSION = '0.1';

export function processMessage(socketPayload) {
  return (dispatch, getState) => {
    const {
      status,
      uid: from,
      message: encryptedPayload
    } = socketPayload;

    if (_.isEmpty(socketPayload)) return;

    if (status === 404) return process404(socketPayload);

    const state = getState();

    return processChatMessage(encryptedPayload, from, state);
  };
}

function process404(messagePayload) {
  const uid = messagePayload.detail;

  redux.dispatch(setOnlineStatus(uid, OFFLINE));
}

function processChatMessage(messagePayload, fromUid, state) {
  const users = state.data.users.records;
  const { privateKey } = state.identity.config;
  const decrypted = decrypt(messagePayload, fromUid, users, privateKey);

  // tell the UI that a message has been received
  redux.dispatch(appendMessage(decrypted));

  // because we received something from somebody,
  // mark them as online.
  redux.dispatch(setOnlineStatus(decrypted.sender.uid, ONLINE));

  notify(decrypted);

  return decrypted;
}

function decrypt(encryptedPayload, fromUid, users, privateKey) {
  redux.dispatch(decryptingMessage({ from: fromUid, encryptedPayload }));
  const user = findUser(fromUid, users);

  if (user === undefined) {
    console.error('user for ', fromUid, ' not found...');
    return;
  }

  const publicKey = user.publickey;

  const decryptedPayloadJson = decryptFrom(
    encryptedPayload,
    publicKey,
    privateKey
  );

  const decryptedPayload = JSON.parse(decryptedPayloadJson);

  redux.dispatch(decryptionComplete({ decryptedPayload }));

  return decryptedPayload;
}
<|endoftext|>