<commit_before>
// DATA
// import { FMRS_MA_2018 } from '../../../data/state/massachusetts/2018/FMRS_MA_2018';
import { UNEARNED_INCOME_SOURCES } from '../../../data/state/massachusetts/name-cores';

// UTILITIES
import { toCashflow, sumCashflow, getGrossUnearnedIncomeMonthly } from '../../../helpers/cashflow';
import { sum } from '../../../helpers/math';

// TO RETURN
import { Result } from '../../../helpers/Result';

/**
* Properties client is required to have to get some kind
* of value back. I guess none really, since at the very
* start they won't have any properties...
*/
var subsidyRequiredProps = [
// Maybe old rent share and contract rent
// Maybe some kind of income and expenses?
];

/** Using old and new cash flow data, return new subsidy amount,
* include new rent share.
*
* @function
* @since 09/2017
*
* With Project Hopes's guidance, we're using old known values (as
* known as they can get) to derive new values.
* @see Deriving: {@link https://docs.google.com/document/d/1o1Tm0HioHeY4NcBSDcjSbXDOjmCAJdI47kG5Fyms0UI/edit#}.
* @see Definitions: {@link https://portal.hud.gov/hudportal/documents/huddoc?id=DOC_11749.pdf}
*
* @todo Find out how close to 0/change the benefit amount needs to be in
* order for the client to be warned.
*/
const getHousingBenefit = function ( client ) {
  /*
  * var diff = new min ttp - old min ttp;
  * var new rent share = old rent share + diff;
  * var new subsidy = contract rent - new rent share
  */
  var prev = 'previous';

  // Send it right back if it's missing input values
  var missingProps = propsNeeded( client, subsidyRequiredProps );
  if ( missingProps.length ) {
    // Until we have some reliable way of knowing the right names for the fields:
    var details = 'Some required form fields have\'t been filled in yet.';
    var result = new Result( { result: 'incomplete', details: 'Form incomplete', data: { missingProps: missingProps } } );
    return result;
  }

  var ttps        = getTTPs( client ),
      diff        = ttps.newTTP - ttps.oldTTP,
      newShare    = diff + toCashflow( client, prev, 'RentShare' ),
      contrRent   = toCashflow( client, prev, 'ContractRent' );

  // Don't pay more rent than the landlord is asking for
  var maxShare    = Math.min( contrRent, newShare ),
      newSubsidy  = contrRent - maxShare;

  var result = {
    result: 'good',
    details: 'All good!',
    benefitValue: newSubsidy,
    data: { newRentShare: maxShare }
  };

  /** @todo When to give a warning for Section 8? */
  if ( newSubsidy <= 500 ) {
    result.result   = 'information';
    result.details  = 'Your housing subsidy is getting low.';
  }

  var officialResult = new Result( result );

  return officialResult;
};  // End getHousingBenefit

/**
* @todo Function description
*
* '#' refers to # item on form at Appendix B of http://www.tacinc.org/media/58886/S8MS%20Full%20Book.pdf
* Is using raw monthly values or converting values to monthly amounts
*/
const getTTPs = function ( client ) {

  var oldNet = getNetIncome( client, 'previous' ),
      newNet = getNetIncome( client, 'current' );

  var oldAdj = getAdjustedIncome( client, 'previous', oldNet ),
      newAdj = getAdjustedIncome( client, 'current', newNet );

  /** @todo A placeholder till we know what to do with negative values */
  oldAdj = Math.max( 0, oldAdj );
  newAdj = Math.max( 0, newAdj );

  // #17, 30% of Adjusted Monthly Income
  var oldAdjToTest = oldAdj * 0.3,
      newAdjToTest = newAdj * 0.3,
      // #18, 10% of Monthly Income
      oldNetToTest = oldNet * 0.1,
      newNetToTest = newNet * 0.1;

  /**
  * TTP = 'total tenant payment'. One place (pg 59) calls this min ttp
  * but another (Appendix B) calls it max. Second makes more sense.
  * Represents max rent share.
  *
  * Note: welfare rent and PHA min rent are not known and so not
  * included in the test. MA may not have welfare rent and PHA min
  * can be waived.
  */
  var oldMaxTTP = Math.max( oldNetToTest, oldAdjToTest ),
      newMaxTTP = Math.max( newNetToTest, newAdjToTest ),
      ttps      = { oldTTP: oldMaxTTP, newTTP: newMaxTTP };

  return ttps;
};  // End getTTPs()

// =============================
// NET INCOME
// =============================

/**
* @todo Function description
*/
const getNetIncome = function ( client, timeframe ) {
  var unearned = getGrossUnearnedIncomeMonthly( client, timeframe ),
      gross    = unearned + toCashflow( client, timeframe, 'EarnedIncome' ),
      net      = gross - toCashflow( client, timeframe, 'IncomeExclusions' );
  return net;
};  // End getNetIncome()

// =============================
// ADJUSTED INCOME
// =============================
/** Properties for all child care expenses */
const childcareProps = [
  'ChildDirectCareCosts', 'ChildBeforeAndAfterSchoolCareCosts',
  'ChildTransportationCosts', 'ChildOtherCareCosts'
];

/**
* @todo Function description
*
* This is only adjusted income as defined for the Section 8 program
* '#' refers to # item on form at Appendix B of http://www.tacinc.org/media/58886/S8MS%20Full%20Book.pdf
* 'pg' refers to the written page number of https://portal.hud.gov/hudportal/documents/huddoc?id=DOC_11749.pdf (gone)
*
* Is using raw monthly values or converting values to monthly amounts
*/
const getAdjustedIncome = function ( client, timeframe, net ) {

  var time       = timeframe,
      allowances = [];

  // #4 & #5
  var depAllowanceAnnual  = (client[ time + 'NumberOfDependents'] || 0) * 480;
  allowances.push( depAllowanceAnnual/12 );
  // #6
  var childcare   = sumCashflow( client, time, childcareProps ),
      ccIncome    = toCashflow( client, time, 'EarnedIncomeBecauseOfChildCare' ),
      /** @todo If student or looking for work, during those hours the expense isn't limited? 2007 Ch. 5 doc */
      ccMin       = Math.min( childcare, ccIncome );
  allowances.push( ccMin );
  // #7 - 13
  var disAndMed = getDisabledAndMedicalAllowancesSum( client, timeframe, net )
  allowances.push( disAndMed );
  // #14
  /** @todo Fix 'current' + etc not existing while 'previous' + etc does */
  if ( client[ time + 'DisabledOrElderlyHeadOrSpouse' ] ) { allowances.push( 400/12 ); }

  var total = sum( allowances ),
      adj   = net - total;

  /** @todo What do we do if this is negative, e.g. dependent allowances are greater than income? */
  return adj;
};  // End getAdjustedIncome()

/**
* Medical allowance needs assistance allowance amounts
* '#' refers to # item on form at Appendix B of http://www.tacinc.org/media/58886/S8MS%20Full%20Book.pdf
* 'pg' refers to the written page number of https://portal.hud.gov/hudportal/documents/huddoc?id=DOC_11749.pdf (gone)
* Is using raw monthly values
*/
const getDisabledAndMedicalAllowancesSum = function ( client, timeframe, net ) {

  var time          = timeframe,
      netSubtractor = net * 0.03;  // #8, #13

  // ----- Assistance Allowance #C, #7 - 11 ----- \\
  // pg 5-30 to 5-31
  var handcpExpense  = toCashflow( client, time, 'DisabledAssistance' ),  // #7
      asstSubtracted = handcpExpense - netSubtractor,  // #9
      asstIncome     = toCashflow( client, time, 'EarnedIncomeBecauseOfAdultCare' ), // #10
      hcapAllowance  = Math.min( asstSubtracted, asstIncome ),  // #11
      hcapMin        = Math.max( 0, hcapAllowance );  // Don't get negative

  // ----- Maybe Stop #D ----- \\
  /** Only keep going if there's a disabled/elderly head or spouse (or sole member) */
  if ( !client[ time + 'DisabledOrElderlyHeadOrSpouse' ] ) { return hcapMin; }

  // ----- Medical Allowance #12 - 13 ----- \\
  // #12, pg 5-31 to 5-32
  var disOrElderlyMedical = toCashflow( client, time, 'DisabledOrElderlyMedical' ),
      // pg 5-31 says all medical expenses count for this household
      otherMedical        = toCashflow( client, time, 'RegularMedical' ),
      medicalExpenses     = disOrElderlyMedical + otherMedical;  // #12

  // Read all of pg 5-32 and 5-34 for the following conditional.
  // Jumps around because cases are overlapping.

  var medAllowance = 0;
  // #13a, pg 5-32 bottom (5-33 to 5-34 example falls in here)
  // Note: #13 forgets the '>=' part and just says '>'
  if ( asstSubtracted >= 0 ) {
    medAllowance = medicalExpenses;

  // #13b
  // pg 5-33 middle /and/ pg 5-32 middle, above "special calcuations"
  // In both cases handcpExpense is >= 0 and can be safely aded.
  } else {
    var sum = medicalExpenses + handcpExpense;
    medAllowance = sum - netSubtractor;
  }

  var medMin = Math.max( 0, medAllowance );

  // #15 contribution ( #11 + #13 )
  return hcapMin + medMin;
};  // End getDisabledAndMedicalAllowancesSum()

const propsNeeded = function ( client, props ) {

  /** @todo Accumulate a string instead */
  /** @todo Put in helpers/validators */
	var missingProps = [];

	for ( let propi = 0; propi < props.length; propi++ ) {
		let key = props[ propi ];
		if ( client[ key ] === undefined ) { missingProps.push( key ); }
	}

	return missingProps;
};  // End propsNeeded()

export {
  getHousingBenefit
};
<commit_msg>Can't have required fields. Removes requirements from housing.js.<commit_after>
// DATA
import { UNEARNED_INCOME_SOURCES } from '../../../data/state/massachusetts/name-cores';

// UTILITIES
import { toCashflow, sumCashflow, getGrossUnearnedIncomeMonthly } from '../../../helpers/cashflow';
import { sum } from '../../../helpers/math';

// TO RETURN
import { Result } from '../../../helpers/Result';

/**
* There should be no required properties since we want results from the start
* and everything at the start is `undefined`.
*/

/** Using old and new cash flow data, return new subsidy amount,
* include new rent share.
*
* @function
* @since 09/2017
*
* With Project Hopes's guidance, we're using old known values (as
* known as they can get) to derive new values.
* @see Deriving: {@link https://docs.google.com/document/d/1o1Tm0HioHeY4NcBSDcjSbXDOjmCAJdI47kG5Fyms0UI/edit#}.
* @see Definitions: {@link https://portal.hud.gov/hudportal/documents/huddoc?id=DOC_11749.pdf}
*
* @todo Find out how close to 0/change the benefit amount needs to be in
* order for the client to be warned.
*/
const getHousingBenefit = function ( client ) {
  /*
  * var diff = new min ttp - old min ttp;
  * var new rent share = old rent share + diff;
  * var new subsidy = contract rent - new rent share
  */
  var prev = 'previous';

  var ttps        = getTTPs( client ),
      diff        = ttps.newTTP - ttps.oldTTP,
      newShare    = diff + toCashflow( client, prev, 'RentShare' ),
      contrRent   = toCashflow( client, prev, 'ContractRent' );

  // Don't pay more rent than the landlord is asking for
  var maxShare    = Math.min( contrRent, newShare ),
      newSubsidy  = contrRent - maxShare;

  var result = {
    result: 'good',
    details: 'All good!',
    benefitValue: newSubsidy,
    data: { newRentShare: maxShare }
  };

  /** @todo When to give a warning for Section 8? */
  if ( newSubsidy <= 500 ) {
    result.result   = 'information';
    result.details  = 'Your housing subsidy is getting low.';
  }

  var officialResult = new Result( result );

  return officialResult;
};  // End getHousingBenefit

/**
* @todo Function description
*
* '#' refers to # item on form at Appendix B of http://www.tacinc.org/media/58886/S8MS%20Full%20Book.pdf
* Is using raw monthly values or converting values to monthly amounts
*/
const getTTPs = function ( client ) {

  var oldNet = getNetIncome( client, 'previous' ),
      newNet = getNetIncome( client, 'current' );

  var oldAdj = getAdjustedIncome( client, 'previous', oldNet ),
      newAdj = getAdjustedIncome( client, 'current', newNet );

  /** @todo A placeholder till we know what to do with negative values */
  oldAdj = Math.max( 0, oldAdj );
  newAdj = Math.max( 0, newAdj );

  // #17, 30% of Adjusted Monthly Income
  var oldAdjToTest = oldAdj * 0.3,
      newAdjToTest = newAdj * 0.3,
      // #18, 10% of Monthly Income
      oldNetToTest = oldNet * 0.1,
      newNetToTest = newNet * 0.1;

  /**
  * TTP = 'total tenant payment'. One place (pg 59) calls this min ttp
  * but another (Appendix B) calls it max. Second makes more sense.
  * Represents max rent share.
  *
  * Note: welfare rent and PHA min rent are not known and so not
  * included in the test. MA may not have welfare rent and PHA min
  * can be waived.
  */
  var oldMaxTTP = Math.max( oldNetToTest, oldAdjToTest ),
      newMaxTTP = Math.max( newNetToTest, newAdjToTest ),
      ttps      = { oldTTP: oldMaxTTP, newTTP: newMaxTTP };

  return ttps;
};  // End getTTPs()

// =============================
// NET INCOME
// =============================

/**
* @todo Function description
*/
const getNetIncome = function ( client, timeframe ) {
  var unearned = getGrossUnearnedIncomeMonthly( client, timeframe ),
      gross    = unearned + toCashflow( client, timeframe, 'EarnedIncome' ),
      net      = gross - toCashflow( client, timeframe, 'IncomeExclusions' );
  return net;
};  // End getNetIncome()

// =============================
// ADJUSTED INCOME
// =============================
/** Properties for all child care expenses */
const childcareProps = [
  'ChildDirectCareCosts', 'ChildBeforeAndAfterSchoolCareCosts',
  'ChildTransportationCosts', 'ChildOtherCareCosts'
];

/**
* @todo Function description
*
* This is only adjusted income as defined for the Section 8 program
* '#' refers to # item on form at Appendix B of http://www.tacinc.org/media/58886/S8MS%20Full%20Book.pdf
* 'pg' refers to the written page number of https://portal.hud.gov/hudportal/documents/huddoc?id=DOC_11749.pdf (gone)
*
* Is using raw monthly values or converting values to monthly amounts
*/
const getAdjustedIncome = function ( client, timeframe, net ) {

  var time       = timeframe,
      allowances = [];

  // #4 & #5
  var depAllowanceAnnual  = (client[ time + 'NumberOfDependents'] || 0) * 480;
  allowances.push( depAllowanceAnnual/12 );
  // #6
  var childcare   = sumCashflow( client, time, childcareProps ),
      ccIncome    = toCashflow( client, time, 'EarnedIncomeBecauseOfChildCare' ),
      /** @todo If student or looking for work, during those hours the expense isn't limited? 2007 Ch. 5 doc */
      ccMin       = Math.min( childcare, ccIncome );
  allowances.push( ccMin );
  // #7 - 13
  var disAndMed = getDisabledAndMedicalAllowancesSum( client, timeframe, net )
  allowances.push( disAndMed );
  // #14
  /** @todo Fix 'current' + etc not existing while 'previous' + etc does */
  if ( client[ time + 'DisabledOrElderlyHeadOrSpouse' ] ) { allowances.push( 400/12 ); }

  var total = sum( allowances ),
      adj   = net - total;

  /** @todo What do we do if this is negative, e.g. dependent allowances are greater than income? */
  return adj;
};  // End getAdjustedIncome()

/**
* Medical allowance needs assistance allowance amounts
* '#' refers to # item on form at Appendix B of http://www.tacinc.org/media/58886/S8MS%20Full%20Book.pdf
* 'pg' refers to the written page number of https://portal.hud.gov/hudportal/documents/huddoc?id=DOC_11749.pdf (gone)
* Is using raw monthly values
*/
const getDisabledAndMedicalAllowancesSum = function ( client, timeframe, net ) {

  var time          = timeframe,
      netSubtractor = net * 0.03;  // #8, #13

  // ----- Assistance Allowance #C, #7 - 11 ----- \\
  // pg 5-30 to 5-31
  var handcpExpense  = toCashflow( client, time, 'DisabledAssistance' ),  // #7
      asstSubtracted = handcpExpense - netSubtractor,  // #9
      asstIncome     = toCashflow( client, time, 'EarnedIncomeBecauseOfAdultCare' ), // #10
      hcapAllowance  = Math.min( asstSubtracted, asstIncome ),  // #11
      hcapMin        = Math.max( 0, hcapAllowance );  // Don't get negative

  // ----- Maybe Stop #D ----- \\
  /** Only keep going if there's a disabled/elderly head or spouse (or sole member) */
  if ( !client[ time + 'DisabledOrElderlyHeadOrSpouse' ] ) { return hcapMin; }

  // ----- Medical Allowance #12 - 13 ----- \\
  // #12, pg 5-31 to 5-32
  var disOrElderlyMedical = toCashflow( client, time, 'DisabledOrElderlyMedical' ),
      // pg 5-31 says all medical expenses count for this household
      otherMedical        = toCashflow( client, time, 'RegularMedical' ),
      medicalExpenses     = disOrElderlyMedical + otherMedical;  // #12

  // Read all of pg 5-32 and 5-34 for the following conditional.
  // Jumps around because cases are overlapping.

  var medAllowance = 0;
  // #13a, pg 5-32 bottom (5-33 to 5-34 example falls in here)
  // Note: #13 forgets the '>=' part and just says '>'
  if ( asstSubtracted >= 0 ) {
    medAllowance = medicalExpenses;

  // #13b
  // pg 5-33 middle /and/ pg 5-32 middle, above "special calcuations"
  // In both cases handcpExpense is >= 0 and can be safely aded.
  } else {
    var sum = medicalExpenses + handcpExpense;
    medAllowance = sum - netSubtractor;
  }

  var medMin = Math.max( 0, medAllowance );

  // #15 contribution ( #11 + #13 )
  return hcapMin + medMin;
};  // End getDisabledAndMedicalAllowancesSum()

export {
  getHousingBenefit
};
<|endoftext|>


<commit_before>import { CHANGE_MODE, CHANGE_SORT_KEY, CHANGE_REVERSE } from '../constants/settings';

export function changeShowMode(showMode) {
  return {
    type: CHANGE_MODE,
    showMode
  };
}

export function changeSortKey(sortKey) {
  return {
    type: CHANGE_SORT_KEY,
    sortKey
  };
}

export function changeReverse(reverse) {
  return {
    type: CHANGE_REVERSE,
    reverse
  }
}
<commit_msg>Add semicolon<commit_after>import { CHANGE_MODE, CHANGE_SORT_KEY, CHANGE_REVERSE } from '../constants/settings';

export function changeShowMode(showMode) {
  return {
    type: CHANGE_MODE,
    showMode
  };
}

export function changeSortKey(sortKey) {
  return {
    type: CHANGE_SORT_KEY,
    sortKey
  };
}

export function changeReverse(reverse) {
  return {
    type: CHANGE_REVERSE,
    reverse
  };
}
<|endoftext|>


<commit_before>export default function(data){

    var nrows = data.length;

    if (nrows === undefined || nrows === null){
        keys = ['message'];
        nrows = 1;
        ncols = 1;
        rows = [['command executed']];
    }else{
        var rows = [];
        var ncols = Object.keys(data[0]).length;
        var keys = Object.keys(data[0]);

        for (var i = 0; i < nrows; i++) {
            var row = [];
            for (var j = 0; j < ncols; j++) {
                row.push(data[i][keys[j]]);
            };
            rows.push(row);
        };
    };
    const data_formatted = { 'columnnames': keys, 'ncols': ncols, 'nrows': nrows, 'rows': rows };

    return data_formatted;
};
<commit_msg>Resolve eslint errors for parse.js<commit_after>export default function (data) {
  let keys;
  let ncols;
  let rows;

  let nrows = data.length;

  // repsonse is 'command executed' if database callback is empty
  if (typeof nrows === 'undefined' || nrows === null) {
    keys = ['message'];
    nrows = 1;
    ncols = 1;
    rows = [['command executed']];
  } else {
    rows = [];
    ncols = Object.keys(data[0]).length;
    keys = Object.keys(data[0]);

    for (let i = 0; i < nrows; i++) {
      const row = [];
      for (let j = 0; j < ncols; j++) {
        row.push(data[i][keys[j]]);
      }
      rows.push(row);
    }
  }
  return { columnnames: keys, ncols, nrows, rows };
}
<|endoftext|>


<commit_before>var events = require('events');
var util = require('util');
var childProcess = require("child_process");
var byline = require("byline");

function Subprocess() {
    events.EventEmitter.call(this);

    this.output = [];
}
util.inherits(Subprocess, events.EventEmitter);

Subprocess.prototype.exec = function (cmd, opts) {
    if (this.childProcess) throw { message: "Subprocess already running" };

    this.cmd = cmd;

    opts || (opts = {});
    var env = {
        TERM: "xterm-color"
    };
    for (var key in (opts.env || {})) env[key] = opts.env[key];
        console.log(opts.env);
    this.childProcess = childProcess.spawn(cmd[0], cmd.slice(1), { cwd: opts.cwd, env: env });

    var self = this;

    ['stdout', 'stderr'].forEach(function (stream) {
        byline(self.childProcess[stream]).on('data', function (line) {
            var lineSpec = { stream: stream, line: line };
            self.output.push(lineSpec);
            self.emit('line', lineSpec);
        });
    });

    this.childProcess.on('close', function (code) {
        self.exitCode = code;
        self.emit('close', code);
    });
};

module.exports = Subprocess;
<commit_msg>Clean up undesirable output<commit_after>var events = require('events');
var util = require('util');
var childProcess = require("child_process");
var byline = require("byline");

function Subprocess() {
    events.EventEmitter.call(this);

    this.output = [];
}
util.inherits(Subprocess, events.EventEmitter);

Subprocess.prototype.exec = function (cmd, opts) {
    if (this.childProcess) throw { message: "Subprocess already running" };

    this.cmd = cmd;

    opts || (opts = {});
    var env = {
        TERM: "xterm-color"
    };
    for (var key in (opts.env || {})) env[key] = opts.env[key];
    this.childProcess = childProcess.spawn(cmd[0], cmd.slice(1), { cwd: opts.cwd, env: env });

    var self = this;

    ['stdout', 'stderr'].forEach(function (stream) {
        byline(self.childProcess[stream]).on('data', function (line) {
            var lineSpec = { stream: stream, line: line };
            self.output.push(lineSpec);
            self.emit('line', lineSpec);
        });
    });

    this.childProcess.on('close', function (code) {
        self.exitCode = code;
        self.emit('close', code);
    });
};

module.exports = Subprocess;
<|endoftext|>


<commit_before>import { connect } from 'react-redux';
import { createSelector } from 'reselect';
import { flexDirectionRow } from 'browser-vendor-prefix';
import { moveLeft } from './actions';
import { reset, setX } from './actions';
import { snapX } from 'panels-ui';
import { spring, TransitionMotion } from 'react-motion';
import debounce from 'lodash.debounce';
import getViewportWidth from './get-viewport-width';
import MoveLeft from './move-left';
import Panel from '../panels/component';
import React, { Component } from 'react';

const DEBOUNCE = 150;
const REBOUND = 500;

export class Runtime extends Component {
  constructor(props) {
    super(props);

    this.onVisibilityChange = this.onVisibilityChange.bind(this);
    this.setXDebounced = debounce(this.setX.bind(this), DEBOUNCE);
    this.setViewportWidthDebounced = debounce(this.setViewportWidth.bind(this), DEBOUNCE);

    this.willEnter = this.willEnter.bind(this);
    this.willLeave = this.willLeave.bind(this);
  }

  componentDidMount() {
    this.$runtime.addEventListener('scroll', this.setXDebounced, false);
    window.addEventListener('resize', this.setViewportWidthDebounced, false);
    window.addEventListener('orientationchange', this.setViewportWidthDebounced, false);
    document.addEventListener('visibilitychange', this.onVisibilityChange);

    this.setViewportWidth();
  }

  componentDidUpdate(prevProps) {
    const { props } = this;

    if (prevProps.focusPanel && props.focusPanel && props.focusPanel.title !== prevProps.focusPanel.title) {
      window.document.title = props.focusPanel.title;
    }

    if (props.routes !== prevProps.routes) {
      props.reset(props.preferredSnapPoint);
    }

    if (props.shouldReset !== prevProps.shouldReset && props.shouldReset) {
      props.reset(props.preferredSnapPoint);
    }

    if (props.x !== prevProps.x) {
      snapX(this.$runtime, props.x);
    }
  }

  componentWillUnmount() {
    this.$runtime.removeEventListener('scroll', this.setXDebounced);
    window.removeEventListener('resize', this.setViewportWidthDebounced, false);
    window.removeEventListener('orientationchange', this.setViewportWidthDebounced, false);
  }

  onVisibilityChange() {
    if (document.visibilityState === 'hidden') {
      this.$runtime.removeEventListener('scroll', this.setXDebounced);
      window.removeEventListener('resize', this.setViewportWidthDebounced, false);
      window.removeEventListener('orientationchange', this.setViewportWidthDebounced, false);
    } else {
      setTimeout(() => {
        this.$runtime.addEventListener('scroll', this.setXDebounced, false);
        window.addEventListener('resize', this.setViewportWidthDebounced, false);
        window.addEventListener('orientationchange', this.setViewportWidthDebounced, false);
      }, REBOUND);
    }
  }

  willEnter() {
    return {
      x: 0
    };
  }

  willLeave() {
    return {
      x: spring(0, { stifness: 210 })
    };
  }

  render() {
    const {
      canMoveLeft, context, focus, focusPanel, moveLeft, routes, snapPoint, width, widths
    } = this.props;
    const runtimeStyle = focusPanel ? {
      ...style,
      ...focusPanel.styleBackground
    } : style;

    return (

 this.$runtime = $e } style={runtimeStyle}>
        { canMoveLeft && <MoveLeft onClick={moveLeft} snapPoint={snapPoint} /> }

        <TransitionMotion
          willEnter={this.willEnter}
          willLeave={this.willLeave}
          styles={routes.map((route, i) => ({
            key: i, // route.context,
            data: {
              route,
              width: widths[i] || 360
            },
            style: {
              x: spring(1, { stifness: 210 })
            }
          }))}>
          {interpolatedStyles => (

              { interpolatedStyles.map((config, i) => (
                <Panel
                  isContext={i >= context}
                  isFocus={i === focus}
                  isVisible={config.data.route.visible}
                  key={config.key}
                  route={config.data.route}
                  shouldWrap={i === routes.length - 1}
                  x={config.style.x}
                  zIndex={routes.length - i}
                  width={config.data.width}
                />
              )) }

          )}
        </TransitionMotion>

    );
  }

  setViewportWidth() {
    this.props.reset(this.props.preferredSnapPoint, getViewportWidth());
  }

  setX() {
    this.props.setX(this.$runtime.scrollLeft);
  }
}

const style = {
  height: '100%',
  overflowX: 'auto',
  overflowY: 'hidden',
  width: '100vw'
};

const stylePanels = {
  ...flexDirectionRow,
  height: '100%'
};

const getFocusPanel = ({panels, router}) => {
  const focusRoute = router.routes[router.focus];
  return panels.byId[`${focusRoute.app}${focusRoute.path}`];
};

// const getFocusPanel = createSelector(
//   state => state.panels,
//   state => state.router.routes[state.router.focus],
//   (panels, focusRoute) => panels[`${focusRoute.app}${focusRoute.path}`]
// );

// const getCanMoveLeft = createSelector(
//   state => state.runtime.shouldGoMobile,
//   state => state.runtime.x,
//   (shouldGoMobile, x) => !shouldGoMobile && x > 0
// );

const getCanMoveLeft = ({runtime}) => !runtime.shouldGoMobile && runtime.x > 0;

function mapStateToProps(state, props) {
  return {
    canMoveLeft: getCanMoveLeft(state),
    context: state.router.context,
    focus: state.router.focus,
    focusPanel: getFocusPanel(state),
    routes: state.router.routes,
    shouldReset: state.runtime.shouldReset,
    snapPoint: state.runtime.snapPoint,
    x: state.runtime.x,
    width: state.runtime.width,
    widths: state.runtime.widths
  };
}

const mapDispatchToProps = {
  moveLeft,
  reset,
  setX
};
export default connect(mapStateToProps, mapDispatchToProps)(Runtime);
<commit_msg>fix: focus panel title<commit_after>import { connect } from 'react-redux';
import { createSelector } from 'reselect';
import { flexDirectionRow } from 'browser-vendor-prefix';
import { moveLeft } from './actions';
import { reset, setX } from './actions';
import { snapX } from 'panels-ui';
import { spring, TransitionMotion } from 'react-motion';
import debounce from 'lodash.debounce';
import getViewportWidth from './get-viewport-width';
import MoveLeft from './move-left';
import Panel from '../panels/component';
import React, { Component } from 'react';

const DEBOUNCE = 150;
const REBOUND = 500;

export class Runtime extends Component {
  constructor(props) {
    super(props);

    this.onVisibilityChange = this.onVisibilityChange.bind(this);
    this.setXDebounced = debounce(this.setX.bind(this), DEBOUNCE);
    this.setViewportWidthDebounced = debounce(this.setViewportWidth.bind(this), DEBOUNCE);

    this.willEnter = this.willEnter.bind(this);
    this.willLeave = this.willLeave.bind(this);
  }

  componentDidMount() {
    this.$runtime.addEventListener('scroll', this.setXDebounced, false);
    window.addEventListener('resize', this.setViewportWidthDebounced, false);
    window.addEventListener('orientationchange', this.setViewportWidthDebounced, false);
    document.addEventListener('visibilitychange', this.onVisibilityChange);

    this.setViewportWidth();
  }

  componentDidUpdate(prevProps) {
    const { props } = this;

    // TODO FIXME this needs to be reworked :/
    if ((!prevProps.focusPanel && props.focusPanel) || (prevProps.focusPanel && props.focusPanel && props.focusPanel.title !== prevProps.focusPanel.title)) {
      window.document.title = props.focusPanel.title || props.focusPanel.type;
    }

    if (props.routes !== prevProps.routes) {
      props.reset(props.preferredSnapPoint);
    }

    if (props.shouldReset !== prevProps.shouldReset && props.shouldReset) {
      props.reset(props.preferredSnapPoint);
    }

    if (props.x !== prevProps.x) {
      snapX(this.$runtime, props.x);
    }
  }

  componentWillUnmount() {
    this.$runtime.removeEventListener('scroll', this.setXDebounced);
    window.removeEventListener('resize', this.setViewportWidthDebounced, false);
    window.removeEventListener('orientationchange', this.setViewportWidthDebounced, false);
  }

  onVisibilityChange() {
    if (document.visibilityState === 'hidden') {
      this.$runtime.removeEventListener('scroll', this.setXDebounced);
      window.removeEventListener('resize', this.setViewportWidthDebounced, false);
      window.removeEventListener('orientationchange', this.setViewportWidthDebounced, false);
    } else {
      setTimeout(() => {
        this.$runtime.addEventListener('scroll', this.setXDebounced, false);
        window.addEventListener('resize', this.setViewportWidthDebounced, false);
        window.addEventListener('orientationchange', this.setViewportWidthDebounced, false);
      }, REBOUND);
    }
  }

  willEnter() {
    return {
      x: 0
    };
  }

  willLeave() {
    return {
      x: spring(0, { stifness: 210 })
    };
  }

  render() {
    const {
      canMoveLeft, context, focus, focusPanel, moveLeft, routes, snapPoint, width, widths
    } = this.props;
    const runtimeStyle = focusPanel ? {
      ...style,
      ...focusPanel.styleBackground
    } : style;

    return (

 this.$runtime = $e } style={runtimeStyle}>
        { canMoveLeft && <MoveLeft onClick={moveLeft} snapPoint={snapPoint} /> }

        <TransitionMotion
          willEnter={this.willEnter}
          willLeave={this.willLeave}
          styles={routes.map((route, i) => ({
            key: i, // route.context,
            data: {
              route,
              width: widths[i] || 360
            },
            style: {
              x: spring(1, { stifness: 210 })
            }
          }))}>
          {interpolatedStyles => (

              { interpolatedStyles.map((config, i) => (
                <Panel
                  isContext={i >= context}
                  isFocus={i === focus}
                  isVisible={config.data.route.visible}
                  key={config.key}
                  route={config.data.route}
                  shouldWrap={i === routes.length - 1}
                  x={config.style.x}
                  zIndex={routes.length - i}
                  width={config.data.width}
                />
              )) }

          )}
        </TransitionMotion>

    );
  }

  setViewportWidth() {
    this.props.reset(this.props.preferredSnapPoint, getViewportWidth());
  }

  setX() {
    this.props.setX(this.$runtime.scrollLeft);
  }
}

const style = {
  height: '100%',
  overflowX: 'auto',
  overflowY: 'hidden',
  width: '100vw'
};

const stylePanels = {
  ...flexDirectionRow,
  height: '100%'
};

const getFocusPanel = ({panels, router}) => {
  const focusRoute = router.routes[router.focus];
  return panels.byId[`${focusRoute.app}${focusRoute.path}`];
};

// const getFocusPanel = createSelector(
//   state => state.panels,
//   state => state.router.routes[state.router.focus],
//   (panels, focusRoute) => panels[`${focusRoute.app}${focusRoute.path}`]
// );

// const getCanMoveLeft = createSelector(
//   state => state.runtime.shouldGoMobile,
//   state => state.runtime.x,
//   (shouldGoMobile, x) => !shouldGoMobile && x > 0
// );

const getCanMoveLeft = ({runtime}) => !runtime.shouldGoMobile && runtime.x > 0;

function mapStateToProps(state, props) {
  return {
    canMoveLeft: getCanMoveLeft(state),
    context: state.router.context,
    focus: state.router.focus,
    focusPanel: getFocusPanel(state),
    routes: state.router.routes,
    shouldReset: state.runtime.shouldReset,
    snapPoint: state.runtime.snapPoint,
    x: state.runtime.x,
    width: state.runtime.width,
    widths: state.runtime.widths
  };
}

const mapDispatchToProps = {
  moveLeft,
  reset,
  setX
};
export default connect(mapStateToProps, mapDispatchToProps)(Runtime);
<|endoftext|>


<commit_before>module.exports = function(robot) {

  robot.respond(/trello/i, function(res_r) {

    var express = require('express');

    var http = require('http')
    var OAuth = require('oauth').OAuth
    var url = require('url')

    /*
    /     Express Server Setup
    */
    var app = express();

    app.use(express.static('public'));

    // var server = app.listen("/hubot/trello-oauth");
    // app.listen('/tmp/sock');
    var server = app.listen(3000, function () {
      console.log('Server up and running...🏃🏃');
      console.log("Listening on port %s", server.address().port);
    });

    /*
    /     OAuth Setup and Functions
    */
    const requestURL = "https://trello.com/1/OAuthGetRequestToken";
    const accessURL = "https://trello.com/1/OAuthGetAccessToken";
    const authorizeURL = "https://trello.com/1/OAuthAuthorizeToken";
    const appName = "anbot team";

    // Be sure to include your key and secret in 🗝.env ↖ over there.
    // You can get your key and secret from Trello at: https://trello.com/app-key
    const key = process.env.HUBOT_TRELLO_KEY;
    //const token = process.env.HUBOT_TRELLO_TOKEN;
    const secret = process.env.HUBOT_TRELLO_OAUTH;

    // Trello redirects the user here after authentication
    const loginCallback = "https://andreasbot.herokuapp.com/hubot/trello-oauth";

    // You should {"token": "tokenSecret"} pairs in a real application
    // Storage should be more permanent (redis would be a good choice)
    const oauth_secrets = {};

    const oauth = new OAuth(requestURL, accessURL, key, secret, "1.0A", loginCallback, "HMAC-SHA1")

    const login = function(req, res) {
      oauth.getOAuthRequestToken(function(error, token, tokenSecret, results){
        // console.log(`in getOAuthRequestToken - token: ${token}, tokenSecret: ${tokenSecret}, resultes ${JSON.stringify(results)}, error: ${JSON.stringify(error)}`);
        oauth_secrets[token] = tokenSecret;
        res.redirect(`${authorizeURL}?oauth_token=${token}&name=${appName}`);
      });
    };

    var callback = function(request, response) {
      const query = url.parse(request.url, true).query;
      const token = query.oauth_token;
      const tokenSecret = oauth_secrets[token];
      const verifier = query.oauth_verifier;
      oauth.getOAuthAccessToken(token, tokenSecret, verifier, function(error, accessToken, accessTokenSecret, results){
        // In a real app, the accessToken and accessTokenSecret should be stored
        console.log(`in getOAuthAccessToken - accessToken: ${accessToken}, accessTokenSecret: ${accessTokenSecret}, error: ${error}`);
        oauth.getProtectedResource("https://api.trello.com/1/members/me", "GET", accessToken, accessTokenSecret, function(error, data, response){
          // Now we can respond with data to show that we have access to your Trello account via OAuth
          console.log(`in getProtectedResource - accessToken: ${accessToken}, accessTokenSecret: ${accessTokenSecret}`);
          response.send(data)
        });
      });
    };

    /*
    /     Routes
    */

    res_r.send("localhost:3000");

    // app.get("/", function (request, response) {
    //   console.log(`GET '/' 🤠 ${Date()}`);
    //   response.send("
Oh, hello there!
Login with OAuth!");
    // });

    app.get("/", function (request, response) {
      console.log(`GET '/' ${Date()}`);
      login(request, response);
    });

    app.get("/callback", function (request, response) {
      console.log(`GET '/callback' ${Date()}`);
      callback(request, response);
    });

  })
}<commit_msg>update trello oauth<commit_after>module.exports = function(robot) {

  robot.respond(/trello/i, function(res_r) {

    var express = require('express');

    var http = require('http')
    var OAuth = require('oauth').OAuth
    var url = require('url')

    /*
    /     Express Server Setup
    */
    var app = express();

    app.use(express.static('public'));

    // var server = app.listen("/hubot/trello-oauth");
    // app.listen('/tmp/sock');
    var server = app.listen(process.env.PORT, function () {
      console.log('Server up and running...🏃🏃');
      console.log("Listening on port %s", server.address().port);
    });

    /*
    /     OAuth Setup and Functions
    */
    const requestURL = "https://trello.com/1/OAuthGetRequestToken";
    const accessURL = "https://trello.com/1/OAuthGetAccessToken";
    const authorizeURL = "https://trello.com/1/OAuthAuthorizeToken";
    const appName = "anbot team";

    // Be sure to include your key and secret in 🗝.env ↖ over there.
    // You can get your key and secret from Trello at: https://trello.com/app-key
    const key = process.env.HUBOT_TRELLO_KEY;
    //const token = process.env.HUBOT_TRELLO_TOKEN;
    const secret = process.env.HUBOT_TRELLO_OAUTH;

    // Trello redirects the user here after authentication
    const loginCallback = "https://andreasbot.herokuapp.com/hubot/trello-oauth";

    // You should {"token": "tokenSecret"} pairs in a real application
    // Storage should be more permanent (redis would be a good choice)
    const oauth_secrets = {};

    const oauth = new OAuth(requestURL, accessURL, key, secret, "1.0A", loginCallback, "HMAC-SHA1")

    const login = function(req, res) {
      oauth.getOAuthRequestToken(function(error, token, tokenSecret, results){
        // console.log(`in getOAuthRequestToken - token: ${token}, tokenSecret: ${tokenSecret}, resultes ${JSON.stringify(results)}, error: ${JSON.stringify(error)}`);
        oauth_secrets[token] = tokenSecret;
        res.redirect(`${authorizeURL}?oauth_token=${token}&name=${appName}`);
      });
    };

    var callback = function(request, response) {
      const query = url.parse(request.url, true).query;
      const token = query.oauth_token;
      const tokenSecret = oauth_secrets[token];
      const verifier = query.oauth_verifier;
      oauth.getOAuthAccessToken(token, tokenSecret, verifier, function(error, accessToken, accessTokenSecret, results){
        // In a real app, the accessToken and accessTokenSecret should be stored
        console.log(`in getOAuthAccessToken - accessToken: ${accessToken}, accessTokenSecret: ${accessTokenSecret}, error: ${error}`);
        oauth.getProtectedResource("https://api.trello.com/1/members/me", "GET", accessToken, accessTokenSecret, function(error, data, response){
          // Now we can respond with data to show that we have access to your Trello account via OAuth
          console.log(`in getProtectedResource - accessToken: ${accessToken}, accessTokenSecret: ${accessTokenSecret}`);
          response.send(data)
        });
      });
    };

    /*
    /     Routes
    */

    res_r.send("localhost:3000");

    // app.get("/", function (request, response) {
    //   console.log(`GET '/' 🤠 ${Date()}`);
    //   response.send("
Oh, hello there!
Login with OAuth!");
    // });

    app.get("/", function (request, response) {
      console.log(`GET '/' ${Date()}`);
      login(request, response);
    });

    app.get("/callback", function (request, response) {
      console.log(`GET '/callback' ${Date()}`);
      callback(request, response);
    });

  })
}<|endoftext|>


<commit_before>/**
 * @module /ui/select.reel
 * @requires montage/ui/component
 */
var Component = require("montage/ui/component").Component;

/**
 * @class Select
 * @extends Component
 */
exports.Select = Component.specialize( /** @lends Select# */ {

    constructor: {
        value: function Select() {
            this.super();
        }
    },

    /*
     * labelPropertyName is the name of the field to display in the select.
     * if not set, the component will try to use the object itself
     */
    labelPropertyName: {
        value: null
    },

    /*
     * valuePropertyName is the name of the field that will be set in @owner.value
     * if not set, the object itself will be set.
     */
    valuePropertyName: {
        value: null
    },

    /*
     * comparePropertyName is the name of the field that will be used to compare two objects
     * if not set, valuePropertyName will be used or the object itself as last resort.
     */
    comparePropertyName: {
        value: null
    },

    /*
     * array of possible objects
     */
    content: { value: null },

    allowsNull: { value: false },

    enabled: { value: true },

    /*
     * value of the curently selected object
     */
    value: {
        value: null
    },

    nullLabel: {
        value: "N/A"
    },

    enterDocument: {
        value: function(firstTime) {
            this.super(firstTime);

            if (firstTime) {
                var self = this;
                if (this.comparePropertyName)
                    this._compareValues = function(x, y) {
                        return x[self.comparePropertyName] == y[self.comparePropertyName];
                    };
                else if (this.valuePropertyName)
                    this._compareValues = function(x, y) {
                        return x == y[self.valuePropertyName];
                    };
                else
                    this._compareValues = function(x, y) {
                        return x == y;
                    };

                this.defineBindings({
                    "_selected": {
                        "<->": "value",
                        convert: function(value) {
                            if (value && self.content) {
                                for (var i = 0; i < self.content.length; i++){
                                    if (self.content[i] && self._compareValues(value, self.content[i])){
                                        return self.content[i];
                                    }
                                }
                                console.warn('"' + self._label(value) + '" not in possible values.');
                            }

                            if (self.allowsNull){
                                return null;
                            }

                            if(self.content){
                                return self.content[0];
                            }

                            return null;
                        },
                        revert: function(value) {
                            if (!value){
                                return null;
                            }

                            if (self.valuePropertyName) {
                                return value[self.valuePropertyName];
                            } else {
                                return value;
                            }
                        }
                    }
                });
            }
        }
    },

    _compareValues: {
        value: null
    },

    _selected: {
        value: null
    },

    _label: {
        value: function(item) {
            if (this.labelPropertyName){
                return item[this.labelPropertyName];
            }
            return item;
        }
    },

    captureEntryAction: {
        value: function(event) {
            this._selected = event.detail.entry;
            this.dropdown.hide();
        }
    }
});
<commit_msg>Be careful to booleans in select<commit_after>/**
 * @module /ui/select.reel
 * @requires montage/ui/component
 */
var Component = require("montage/ui/component").Component;

/**
 * @class Select
 * @extends Component
 */
exports.Select = Component.specialize( /** @lends Select# */ {

    constructor: {
        value: function Select() {
            this.super();
        }
    },

    /*
     * labelPropertyName is the name of the field to display in the select.
     * if not set, the component will try to use the object itself
     */
    labelPropertyName: {
        value: null
    },

    /*
     * valuePropertyName is the name of the field that will be set in @owner.value
     * if not set, the object itself will be set.
     */
    valuePropertyName: {
        value: null
    },

    /*
     * comparePropertyName is the name of the field that will be used to compare two objects
     * if not set, valuePropertyName will be used or the object itself as last resort.
     */
    comparePropertyName: {
        value: null
    },

    /*
     * array of possible objects
     */
    content: { value: null },

    allowsNull: { value: false },

    enabled: { value: true },

    /*
     * value of the curently selected object
     */
    value: {
        value: null
    },

    nullLabel: {
        value: "N/A"
    },

    enterDocument: {
        value: function(firstTime) {
            this.super(firstTime);

            if (firstTime) {
                var self = this;
                if (this.comparePropertyName)
                    this._compareValues = function(x, y) {
                        return x[self.comparePropertyName] == y[self.comparePropertyName];
                    };
                else if (this.valuePropertyName)
                    this._compareValues = function(x, y) {
                        return x == y[self.valuePropertyName];
                    };
                else
                    this._compareValues = function(x, y) {
                        return x == y;
                    };

                this.defineBindings({
                    "_selected": {
                        "<->": "value",
                        convert: function(value) {
                            if (value !== undefined && value !== null && self.content) {
                                for (var i = 0; i < self.content.length; i++){
                                    if (self.content[i] && self._compareValues(value, self.content[i])){
                                        return self.content[i];
                                    }
                                }
                                console.warn('"' + self._label(value) + '" not in possible values.');
                            }

                            if (self.allowsNull){
                                return null;
                            }

                            if(self.content){
                                return self.content[0];
                            }

                            return null;
                        },
                        revert: function(value) {
                            if (value === undefined || value === null){
                                return null;
                            }

                            if (self.valuePropertyName) {
                                return value[self.valuePropertyName];
                            } else {
                                return value;
                            }
                        }
                    }
                });
            }
        }
    },

    _compareValues: {
        value: null
    },

    _selected: {
        value: null
    },

    _label: {
        value: function(item) {
            if (this.labelPropertyName){
                return item[this.labelPropertyName];
            }
            return item;
        }
    },

    captureEntryAction: {
        value: function(event) {
            this._selected = event.detail.entry;
            this.dropdown.hide();
        }
    }
});
<|endoftext|>


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

import Keyboard from './Keyboard';

class KeyboardedInput extends React.Component {
  static propTypes = {
    name: PropTypes.any,
    containerClassName: PropTypes.any,
    inputClassName: PropTypes.any,
    keyboardClassName: PropTypes.any,
    placeholder: PropTypes.any,
    value: PropTypes.any.isRequired,
    type: PropTypes.any,
    min: PropTypes.any,
    max: PropTypes.any,
    step: PropTypes.any,
    pattern: PropTypes.any,
    readOnly: PropTypes.any,
    enabled: PropTypes.any,
    defaultKeyboard: PropTypes.any,
    secondaryKeyboard: PropTypes.any,
    opacity: PropTypes.any,
    isDraggable: PropTypes.any,
    isFirstLetterUppercase: PropTypes.any,
    uppercaseAfterSpace: PropTypes.any,
    dataset: PropTypes.any,
    onChange: PropTypes.func,
    showNumericRow: PropTypes.bool,
    showShift: PropTypes.bool,
    showSymbols: PropTypes.bool,
    showSpacebar: PropTypes.bool,
  };

  constructor(props) {
    super(props);
    this.focus = this.focus.bind(this);
    this.handleFocus = this.handleFocus.bind(this);
    this.handleFocusLost = this.handleFocusLost.bind(this);
    this.handleChange = this.handleChange.bind(this);
    this.hideKeyboard = this.hideKeyboard.bind(this);

    this.state = {
      showKeyboard: false,
      input: null,
    };
  }

  componentDidMount() {
    this.input.addEventListener('input', this.handleChange);
  }

  componentWillUnmount() {
    this.input.removeEventListener('input', this.handleChange);
  }

  focus() {
    this.input.focus();
  }

  handleChange(event) {
    this.props.onChange(event.target.value);
  }

  handleFocus() {
    const that = this;
    // Prevent blinking of the keyboard if opaque
    setTimeout(() => {
      if (that.input && typeof (that.props.value) !== 'undefined') {
        that.input.focus();
        that.input.select();
        that.input.setSelectionRange(that.props.value.length, that.props.value.length);
        that.setState({ ...this.state, showKeyboard: true });
      }
    }, 0);
  }

  handleFocusLost() {
    const that = this;
    setTimeout(() => {
      // console.error(document.activeElement.classList);
      console.error(window.event);
      if (!document.activeElement.classList.contains('keyboard-button')
        && !document.activeElement.classList.contains('keyboard')
        && !document.activeElement.classList.contains('keyboard-row')
        && !document.activeElement.classList.contains('react-draggable-transparent-selection')) {
        that.setState({ ...that.state, showKeyboard: false });
      }
    }, 0);
  }

  hideKeyboard() {
    this.setState({ ...this.state, showKeyboard: false });
  }

  render() {
    return (

        <input
          name={this.props.name}
          className={this.props.inputClassName}
          placeholder={this.props.placeholder}
          value={this.props.value}
          type={this.props.type}
          onFocus={this.handleFocus}
          onBlur={this.handleFocusLost}
          min={this.props.min}
          max={this.props.max}
          step={this.props.step}
          pattern={this.props.pattern}
          onChange={this.handleChange}
          readOnly={this.props.readOnly === true}
          ref={(e) => { this.input = e; }}
        />
        {this.state.showKeyboard && this.props.enabled && this.props.readOnly !== true &&
        <Keyboard
          hideKeyboard={this.hideKeyboard}
          defaultKeyboard={this.props.defaultKeyboard}
          secondaryKeyboard={this.props.secondaryKeyboard}
          inputNode={this.input}
          dataset={this.props.dataset}
          opacity={this.props.opacity}
          isDraggable={this.props.isDraggable}
          isFirstLetterUppercase={this.props.isFirstLetterUppercase}
          uppercaseAfterSpace={this.props.uppercaseAfterSpace}
          keyboardClassName={this.props.keyboardClassName}
          showNumericRow={this.props.showNumericRow}
          showShift={this.props.showShift}
          showSymbols={this.props.showSymbols}
          showSpacebar={this.props.showSpacebar}
        />
        }

    );
  }
}

export default KeyboardedInput;
<commit_msg>Remove old debug code<commit_after>import React from 'react';
import PropTypes from 'prop-types';

import Keyboard from './Keyboard';

class KeyboardedInput extends React.Component {
  static propTypes = {
    name: PropTypes.any,
    containerClassName: PropTypes.any,
    inputClassName: PropTypes.any,
    keyboardClassName: PropTypes.any,
    placeholder: PropTypes.any,
    value: PropTypes.any.isRequired,
    type: PropTypes.any,
    min: PropTypes.any,
    max: PropTypes.any,
    step: PropTypes.any,
    pattern: PropTypes.any,
    readOnly: PropTypes.any,
    enabled: PropTypes.any,
    defaultKeyboard: PropTypes.any,
    secondaryKeyboard: PropTypes.any,
    opacity: PropTypes.any,
    isDraggable: PropTypes.any,
    isFirstLetterUppercase: PropTypes.any,
    uppercaseAfterSpace: PropTypes.any,
    dataset: PropTypes.any,
    onChange: PropTypes.func,
    showNumericRow: PropTypes.bool,
    showShift: PropTypes.bool,
    showSymbols: PropTypes.bool,
    showSpacebar: PropTypes.bool,
  };

  constructor(props) {
    super(props);
    this.focus = this.focus.bind(this);
    this.handleFocus = this.handleFocus.bind(this);
    this.handleFocusLost = this.handleFocusLost.bind(this);
    this.handleChange = this.handleChange.bind(this);
    this.hideKeyboard = this.hideKeyboard.bind(this);

    this.state = {
      showKeyboard: false,
      input: null,
    };
  }

  componentDidMount() {
    this.input.addEventListener('input', this.handleChange);
  }

  componentWillUnmount() {
    this.input.removeEventListener('input', this.handleChange);
  }

  focus() {
    this.input.focus();
  }

  handleChange(event) {
    this.props.onChange(event.target.value);
  }

  handleFocus() {
    const that = this;
    // Prevent blinking of the keyboard if opaque
    setTimeout(() => {
      if (that.input && typeof (that.props.value) !== 'undefined') {
        that.input.focus();
        that.input.select();
        that.input.setSelectionRange(that.props.value.length, that.props.value.length);
        that.setState({ ...this.state, showKeyboard: true });
      }
    }, 0);
  }

  handleFocusLost() {
    const that = this;
    setTimeout(() => {
      if (!document.activeElement.classList.contains('keyboard-button')
        && !document.activeElement.classList.contains('keyboard')
        && !document.activeElement.classList.contains('keyboard-row')
        && !document.activeElement.classList.contains('react-draggable-transparent-selection')) {
        that.setState({ ...that.state, showKeyboard: false });
      }
    }, 0);
  }

  hideKeyboard() {
    this.setState({ ...this.state, showKeyboard: false });
  }

  render() {
    return (

        <input
          name={this.props.name}
          className={this.props.inputClassName}
          placeholder={this.props.placeholder}
          value={this.props.value}
          type={this.props.type}
          onFocus={this.handleFocus}
          onBlur={this.handleFocusLost}
          min={this.props.min}
          max={this.props.max}
          step={this.props.step}
          pattern={this.props.pattern}
          onChange={this.handleChange}
          readOnly={this.props.readOnly === true}
          ref={(e) => { this.input = e; }}
        />
        {this.state.showKeyboard && this.props.enabled && this.props.readOnly !== true &&
        <Keyboard
          hideKeyboard={this.hideKeyboard}
          defaultKeyboard={this.props.defaultKeyboard}
          secondaryKeyboard={this.props.secondaryKeyboard}
          inputNode={this.input}
          dataset={this.props.dataset}
          opacity={this.props.opacity}
          isDraggable={this.props.isDraggable}
          isFirstLetterUppercase={this.props.isFirstLetterUppercase}
          uppercaseAfterSpace={this.props.uppercaseAfterSpace}
          keyboardClassName={this.props.keyboardClassName}
          showNumericRow={this.props.showNumericRow}
          showShift={this.props.showShift}
          showSymbols={this.props.showSymbols}
          showSpacebar={this.props.showSpacebar}
        />
        }

    );
  }
}

export default KeyboardedInput;
<|endoftext|>


<commit_before>const Yodot = require('../../lib/yodot');
const _ = require('lodash');
const chalk = require('chalk');
const Git = require('simple-git/promise');
const path = require('path');
const pkg = require('../../package.json');
const yosay = require('yosay');

const git = new Git();

module.exports = class extends Yodot {
	greet() {
		this.log(yosay(`Welcome to the ${chalk.red(pkg.name)} generator!`));
	}

	async ask() {
		const answers = await this.prompt([ {
			name: 'name',
			type: 'input',
			message: 'Project name?',
			default: path.basename(process.cwd())
		}, {
			name: 'author',
			type: 'input',
			message: 'Author?',
			default: await getGitUser(),
			store: true
		}, {
			name: 'modules',
			type: 'checkbox',
			message: 'Modules?',
			choices: this.getModules(),
			store: true
		} ]);
		_.assign(this.ctx, answers);

		this.config.set('name', answers.name);
	}

	main() {
		super.main();
		for (const module of this.ctx.modules) super.main({ ns: module });
	}
};

async function getGitUser() {
	return git.raw('config --get user.name'.split(' '))
		.then((result) => result.trim());
}
<commit_msg>Removed an unnecessary async.<commit_after>const Yodot = require('../../lib/yodot');
const _ = require('lodash');
const chalk = require('chalk');
const Git = require('simple-git/promise');
const path = require('path');
const pkg = require('../../package.json');
const yosay = require('yosay');

const git = new Git();

module.exports = class extends Yodot {
	greet() {
		this.log(yosay(`Welcome to the ${chalk.red(pkg.name)} generator!`));
	}

	async ask() {
		const answers = await this.prompt([ {
			name: 'name',
			type: 'input',
			message: 'Project name?',
			default: path.basename(process.cwd())
		}, {
			name: 'author',
			type: 'input',
			message: 'Author?',
			default: await getGitUser(),
			store: true
		}, {
			name: 'modules',
			type: 'checkbox',
			message: 'Modules?',
			choices: this.getModules(),
			store: true
		} ]);
		_.assign(this.ctx, answers);

		this.config.set('name', answers.name);
	}

	main() {
		super.main();
		for (const module of this.ctx.modules) super.main({ ns: module });
	}
};

function getGitUser() {
	return git.raw('config --get user.name'.split(' '))
		.then((result) => result.trim());
}
<|endoftext|>


<commit_before>/*global browser:false  */
'use strict';

var BillingPage = require('./billing/billing-page');

function AccountPage(){
    this.billing  = new BillingPage();
}

AccountPage.prototype.visitPage = function(){
    return browser.get('/account/');
};

module.exports = AccountPage;

<commit_msg>Fix URL<commit_after>/*global browser:false  */
'use strict';

var BillingPage = require('./billing/billing-page');

function AccountPage(){
    this.billing  = new BillingPage();
}

AccountPage.prototype.visitPage = function(){
    return browser.get('/account');
};

module.exports = AccountPage;

<|endoftext|>


<commit_before>var __testing_context__;

function defaultSubject(factory, options) {
  return factory.create(options);
}

export function moduleFor(fullName, description, callbacks, delegate) {
  callbacks = callbacks || { };

  var needs = [fullName].concat(callbacks.needs || []);
  var container = isolatedContainer(needs);

  callbacks.subject = callbacks.subject || defaultSubject;

  callbacks.setup    = callbacks.setup    || function() { };
  callbacks.teardown = callbacks.teardown || function() { };

  function factory() {
    return container.lookupFactory(fullName);
  }

  function subject(options) {
    return callbacks.subject(factory(), options);
  }

  __testing_context__ = {
    container: container,
    subject: subject,
    factory: factory,
    __setup_properties__: callbacks
  };

  if (delegate) {
    delegate(factory(), container, __testing_context__);
  }

  var context = __testing_context__;
  var _callbacks = {
    setup: function(){
      buildContextVariables(context);
      callbacks.setup.call(context, container);
    },
    teardown: function(){
      Ember.run(function(){
        container.destroy();
        // destroy all cached variables
      });

      Ember.$('#ember-testing').empty();
      // maybe destroy all the add-hoc objects

      callbacks.teardown(container);
    }
  };

  module(description, _callbacks);
}

// allow arbitrary named factories, like rspec let
function buildContextVariables(context) {
  var cache = { };
  var callbacks = context.__setup_properties__;
  var factory = context.factory;
  var container = context.container;

  Ember.keys(callbacks).filter(function(key){
    // ignore the default setup/teardown keys
    return key !== 'setup' && key !== 'teardown';
  }).forEach(function(key){
    context[key] = function(options) {
      if (cache[key]) {
        return cache[key];
      }

      var result = callbacks[key](factory(), options, container);
      cache[key] = result;
      return result;
    };
  });
}

export function test(testName, callback) {
  var context = __testing_context__; // save refence

  function wrapper() {
    var result = callback.call(context);

    function failTestOnPromiseRejection(reason) {
      ok(false, reason);
    }

    Ember.run(function(){
      stop();
      Ember.RSVP.Promise.cast(result)['catch'](failTestOnPromiseRejection)['finally'](start);
    });
  }

  QUnit.test(testName, wrapper);
}

export function moduleForModel(name, description, callbacks) {
  moduleFor('model:' + name, description, callbacks, function(factory, container, context) {
    // custom model specific awesomeness
    container.register('store:main', DS.Store);
    container.register('adapter:application', DS.FixtureAdapter);

    context.__setup_properties__.store = function(){
      return container.lookup('store:main');
    };

    if (context.__setup_properties__.subject === defaultSubject) {
      context.__setup_properties__.subject = function(options) {
        return Ember.run(function() {
          return container.lookup('store:main').createRecord(name, options);
        });
      };
    }
  });
}

export function moduleForComponent(name, description, callbacks) {
  // just a spike...
  moduleFor('component:' + name, description, callbacks, function(factory, container, context) {

    context.__setup_properties__.$ = function(selector) {
      var view = Ember.run(function(){
        return context.subject().appendTo(Ember.$('#ember-testing')[0]);
      });

      return view.$();
    };
  });
}

<commit_msg>Don’t call `factory()` before calling to `delegate()`. Allows injections to be specified in the provided `delegate()` function.<commit_after>var __testing_context__;

function defaultSubject(factory, options) {
  return factory.create(options);
}

export function moduleFor(fullName, description, callbacks, delegate) {
  callbacks = callbacks || { };

  var needs = [fullName].concat(callbacks.needs || []);
  var container = isolatedContainer(needs);

  callbacks.subject = callbacks.subject || defaultSubject;

  callbacks.setup    = callbacks.setup    || function() { };
  callbacks.teardown = callbacks.teardown || function() { };

  function factory() {
    return container.lookupFactory(fullName);
  }

  function subject(options) {
    return callbacks.subject(factory(), options);
  }

  __testing_context__ = {
    container: container,
    subject: subject,
    factory: factory,
    __setup_properties__: callbacks
  };

  if (delegate) {
    delegate(container, __testing_context__);
  }

  var context = __testing_context__;
  var _callbacks = {
    setup: function(){
      buildContextVariables(context);
      callbacks.setup.call(context, container);
    },
    teardown: function(){
      Ember.run(function(){
        container.destroy();
        // destroy all cached variables
      });

      Ember.$('#ember-testing').empty();
      // maybe destroy all the add-hoc objects

      callbacks.teardown(container);
    }
  };

  module(description, _callbacks);
}

// allow arbitrary named factories, like rspec let
function buildContextVariables(context) {
  var cache = { };
  var callbacks = context.__setup_properties__;
  var factory = context.factory;
  var container = context.container;

  Ember.keys(callbacks).filter(function(key){
    // ignore the default setup/teardown keys
    return key !== 'setup' && key !== 'teardown';
  }).forEach(function(key){
    context[key] = function(options) {
      if (cache[key]) {
        return cache[key];
      }

      var result = callbacks[key](factory(), options, container);
      cache[key] = result;
      return result;
    };
  });
}

export function test(testName, callback) {
  var context = __testing_context__; // save refence

  function wrapper() {
    var result = callback.call(context);

    function failTestOnPromiseRejection(reason) {
      ok(false, reason);
    }

    Ember.run(function(){
      stop();
      Ember.RSVP.Promise.cast(result)['catch'](failTestOnPromiseRejection)['finally'](start);
    });
  }

  QUnit.test(testName, wrapper);
}

export function moduleForModel(name, description, callbacks) {
  moduleFor('model:' + name, description, callbacks, function(container, context) {
    // custom model specific awesomeness
    container.register('store:main', DS.Store);
    container.register('adapter:application', DS.FixtureAdapter);

    context.__setup_properties__.store = function(){
      return container.lookup('store:main');
    };

    if (context.__setup_properties__.subject === defaultSubject) {
      context.__setup_properties__.subject = function(options) {
        return Ember.run(function() {
          return container.lookup('store:main').createRecord(name, options);
        });
      };
    }
  });
}

export function moduleForComponent(name, description, callbacks) {
  // just a spike...
  moduleFor('component:' + name, description, callbacks, function(container, context) {

    context.__setup_properties__.$ = function(selector) {
      var view = Ember.run(function(){
        return context.subject().appendTo(Ember.$('#ember-testing')[0]);
      });

      return view.$();
    };
  });
}

<|endoftext|>