<commit_before>"use strict"

import React from 'react'
import {StickyContainer,Sticky} from 'react-sticky'
import { connect } from 'react-redux'
import { loadMetroData, setMetroQuarter } from 'redux/modules/metroQcewData.js'
import d3 from 'd3'
import LineGraph from 'components/graphs/SimpleLineGraph/index'
import { loadNaicsKeys } from 'redux/modules/msaLookup'
import { typemap } from 'support/qcew/typemap'

import { kmgtFormatter, kmgtDollarFormatter } from '../misc/numberFormatters'

const integerFormatter = kmgtFormatter.bind(null, 0)
const floatFormatter   = kmgtFormatter.bind(null, 1)

const lineGraphNumberFormatter = kmgtFormatter.bind(null, 0)
const lineGraphDollarFormatter = kmgtDollarFormatter.bind(null, 0)

const tooltipNumberFormatter = kmgtFormatter.bind(null, 3)
const tooltipDollarFormatter = kmgtDollarFormatter.bind(null, 2)

type Props = {};

let focusedLineGraph = 'rawLinegraph'

const lineGraphFocusChanger = (lineGraph) => {
  focusedLineGraph = lineGraph
}

let yearConst = 2001

export class NaicsGraph extends React.Component<void, Props, void> {

    constructor () {
      super()

      this.state={
        data: null,
      }

      this._onMouse = this._onMouse.bind(this)
      this._process = this._process.bind(this)
    }

    _init (id) {

      if(!this.props.data || id) {
        this.props.loadData(id)
      }

      if(!this.props.naicsKeys){
        this.props.loadNaicsKeys()
      }
    }

    componentWillMount () {
      this._init(this.props.currentMetro)
    }

    componentWillReceiveProps (nextProps){
      if(this.props.currentMetro !== nextProps.currentMetro) {
        this._init(nextProps.currentMetro)
      }
    }

    renderToolTip (mData) {

      let data;

      if (!this.props.qtrData) {
        data = mData
      } else {
        data = this.props.qtrData
      }

      let naics = this.props.naicsKeys

      let innerStyle = {
        paddingBottom : 1,
        paddingTop    : 1
      }

      let valueFormatter = ((this.props.type === 'totalwages') && (focusedLineGraph === 'rawLinegraph')) ?
                            tooltipDollarFormatter : tooltipNumberFormatter

      let rows = data.sort((b,a) => a.value-b.value)
                     .map( x => {

                       let nameStyle = Object.assign({},innerStyle)

                       nameStyle.backgroundColor = x.color

                       return (

                                   {naics[x.key].title.substr(0,16)}

                               {valueFormatter(x.value)}

                        )
                     })

      return (

                    Naics
                    value

                  {rows}

      )
    }

    xmap (year, qtr) {

      var val = (4 * (parseInt(year) - yearConst)) + parseInt(qtr)

      if(!isNaN(val) || val >= 0) {
          return val
      } else {
        return 0
      }
    }

    revMap (encQ) {
      let chk = encQ % 4

      let qtr = (chk) ? 4 : (chk)

      let year = Math.floor(encQ / 4) - ((chk) ? 0 : 1)

      return year + yearConst
    }

    dataMap (data, fields, recfunc) {

      let colors = d3.scale.category20c()

      let filterfun = (x) => {

        if (this.props.filter && this.props.filter.length) {
          return this.props.filter.indexOf(x.key) >= 0
        } else {
          return x.key.split('-')[0].length === 2
        }

      }

      return data.filter(filterfun)
                 .map((industry, i) => {

                   var obj = {}

                   obj.key = industry.key
                   obj.color = colors(i%20)
                   obj.values = industry.values
                                        .map( recfunc.bind(this,fields) )
                                        .sort((a,b) => (a.values.x - b.values.x))

                   obj.values.reduce((a, b) => {
                     if (!b.values.y) {
                       b.values.y = a.values.y
                     }
                     return b
                   })

                   return obj
                 })
    }

    aggfunc (finish, fields, rec) {

      let x = this.xmap(rec.year, rec.qtr)
      let y = 0;

      if( !Array.isArray(fields) ) {
        y = parseFloat(rec[fields])
      } else {
        y = fields.map(x => parseFloat(rec[x]))
                  .reduce((sum, b) => sum + b, 0)
      }

      y = finish(y)

      let val = {
        key: x,
        values: { x, y, }
      }

      return val
  }

  _onMouse (data) {
    this.props.setQtr(data)
  }

  _process (data,agg,noagg) {

    let pdata = {}
    let fields = typemap[this.props.type]
    let lqfields = fields.map(x => 'lq_' + x)

    if(this.props.type !== 'employment'){
      pdata.data = this.dataMap(data, fields, noagg)
      pdata.lqdata = this.dataMap(data, lqfields, noagg)

      console.log(pdata)
    } else {
      pdata.data = this.dataMap(data, fields, agg)
      pdata.lqdata = this.dataMap(data, lqfields, agg)
    }

    return pdata
  }

  render () {

    if (!this.props.data || !this.props.data.length) {
      return
    }

    let metrodata = d3.nest()
                      .key(x => x.area_fips)
                      .rollup(values => values)
                      .map(this.props.data)['C'+this.props.currentMetro.substr(0,4)]

    let data = d3.nest()
                 .key(x => x.industry_code)
                 .rollup(values => values)
                 .entries(metrodata || [])

    let empfields = typemap[this.props.type]
    let noagg = this.aggfunc.bind(this, x => x)

    let agg = this.aggfunc.bind(this, x => (x / empfields.length))

    let mData = this._process(data, agg, noagg)

    let graphMargin = {
      top    : 10,
      left   : 60,
      right  : 20,
      bottom : 20,
    }

    return (

            <LineGraph
                key={this.props.field}
                data={mData.data}
                uniq={this.props.field}
                title={'Quarterly ' + this.props.title}
                yFormat={(this.props.type === 'totalwages') ? lineGraphDollarFormatter : integerFormatter}
                xScaleType={'linear'}
                yAxis={true}
                margin={graphMargin}
                tooltip={true}
                onMouse={this._onMouse}
                graphSlice={this.props.qtrData} />

            <LineGraph
                key={'lq_'+this.props.field}
                data={mData.lqdata}
                uniq={'lq_'+this.props.field}
                xFormat={(x)=>this.revMap(x)}
                yFormat={floatFormatter}
                title={'Quarterly LQ '+ this.props.title}
                xAxis={true}
                xScaleType={'linear'}
                yAxis={true}
                margin={graphMargin}
                tooltip={true}
                onMouse={this._onMouse}
                graphSlice={this.props.qtrData} />

          {this.renderToolTip(mData.data)}

    )
  }
}

const mapStateToProps = (state) => ({
  data      : state.metroQcewData.data,
  naicsKeys : state.metros.naicsKeys,
  qtrData   : state.metroQcewData.qtrData
})

export default connect((mapStateToProps), {
  loadData      : (msaId, year) => loadMetroData(msaId),
  loadNaicsKeys : () => loadNaicsKeys(),
  setQtr        : (d) => setMetroQuarter(d),
})(NaicsGraph)
<commit_msg>Wrapping up the merge.<commit_after>"use strict"

import React from 'react'
import {StickyContainer,Sticky} from 'react-sticky'
import { connect } from 'react-redux'
import { loadMetroData, setMetroQuarter } from 'redux/modules/metroQcewData.js'
import d3 from 'd3'
import LineGraph from 'components/graphs/SimpleLineGraph/index'
import { loadNaicsKeys } from 'redux/modules/msaLookup'
import { typemap } from 'support/qcew/typemap'

import { kmgtFormatter, kmgtDollarFormatter } from '../misc/numberFormatters'

const integerFormatter = kmgtFormatter.bind(null, 0)
const floatFormatter   = kmgtFormatter.bind(null, 1)

const lineGraphNumberFormatter = kmgtFormatter.bind(null, 0)
const lineGraphDollarFormatter = kmgtDollarFormatter.bind(null, 0)

const tooltipNumberFormatter = kmgtFormatter.bind(null, 3)
const tooltipDollarFormatter = kmgtDollarFormatter.bind(null, 2)

type Props = {};

let focusedLineGraph = 'rawLinegraph'

const lineGraphFocusChanger = (lineGraph) => {
  focusedLineGraph = lineGraph
}

let yearConst = 2001

export class NaicsGraph extends React.Component<void, Props, void> {

    constructor () {
      super()

      this.state={
        data: null,
      }

      this._onMouse = this._onMouse.bind(this)
      this._process = this._process.bind(this)
    }

    _init (id) {

      if(!this.props.data || id) {
        this.props.loadData(id)
      }

      if(!this.props.naicsKeys){
        this.props.loadNaicsKeys()
      }
    }

    componentWillMount () {
      this._init(this.props.currentMetro)
    }

    componentWillReceiveProps (nextProps){
      if(this.props.currentMetro !== nextProps.currentMetro) {
        this._init(nextProps.currentMetro)
      }
    }

    renderToolTip (mData) {

      let data;

      if (!this.props.qtrData) {
        data = mData
      } else {
        data = this.props.qtrData
      }

      let naics = this.props.naicsKeys

      let innerStyle = {
        paddingBottom : 1,
        paddingTop    : 1
      }

      let valueFormatter = ((this.props.type === 'totalwages') && (focusedLineGraph === 'rawLinegraph')) ?
                            tooltipDollarFormatter : tooltipNumberFormatter

      let rows = data.sort((b,a) => a.value-b.value)
                     .map( x => {

                       let nameStyle = Object.assign({},innerStyle)

                       nameStyle.backgroundColor = x.color

                       return (

                                   {naics[x.key].title.substr(0,16)}

                               {valueFormatter(x.value)}

                        )
                     })

      return (

                    Naics
                    value

                  {rows}

      )
    }

    xmap (year, qtr) {

      var val = (4 * (parseInt(year) - yearConst)) + parseInt(qtr)

      if(!isNaN(val) || val >= 0) {
          return val
      } else {
        return 0
      }
    }

    revMap (encQ) {
      let chk = encQ % 4

      let qtr = (chk) ? 4 : (chk)

      let year = Math.floor(encQ / 4) - ((chk) ? 0 : 1)

      return year + yearConst
    }

    dataMap (data, fields, recfunc) {

      let colors = d3.scale.category20c()

      let filterfun = (x) => {

        if (this.props.filter && this.props.filter.length) {
          return this.props.filter.indexOf(x.key) >= 0
        } else {
          return x.key.split('-')[0].length === 2
        }

      }

      return data.filter(filterfun)
                 .map((industry, i) => {

                   var obj = {}

                   obj.key = industry.key
                   obj.color = colors(i%20)
                   obj.values = industry.values
                                        .map( recfunc.bind(this,fields) )
                                        .sort((a,b) => (a.values.x - b.values.x))

                   obj.values.reduce((a, b) => {
                     if (!b.values.y) {
                       b.values.y = a.values.y
                     }
                     return b
                   })

                   return obj
                 })
    }

    aggfunc (finish, fields, rec) {

      let x = this.xmap(rec.year, rec.qtr)
      let y = 0;

      if( !Array.isArray(fields) ) {
        y = parseFloat(rec[fields])
      } else {
        y = fields.map(x => parseFloat(rec[x]))
                  .reduce((sum, b) => sum + b, 0)
      }

      y = finish(y)

      let val = {
        key: x,
        values: { x, y, }
      }

      return val
  }

  _onMouse (data) {
    this.props.setQtr(data)
  }

  _process (data,agg,noagg) {

    let pdata = {}
    let fields = typemap[this.props.type]
    let lqfields = fields.map(x => 'lq_' + x)

    if(this.props.type !== 'employment'){
      pdata.data = this.dataMap(data, fields, noagg)
      pdata.lqdata = this.dataMap(data, lqfields, noagg)

      console.log(pdata)
    } else {
      pdata.data = this.dataMap(data, fields, agg)
      pdata.lqdata = this.dataMap(data, lqfields, agg)
    }

    return pdata
  }

  render () {

    if (!this.props.data || !this.props.data.length) {
      return
    }

    let metrodata = d3.nest()
                      .key(x => x.area_fips)
                      .rollup(values => values)
                      .map(this.props.data)['C'+this.props.currentMetro.substr(0,4)]

    let data = d3.nest()
                 .key(x => x.industry_code)
                 .rollup(values => values)
                 .entries(metrodata || [])

    let empfields = typemap[this.props.type]
    let noagg = this.aggfunc.bind(this, x => x)

    let agg = this.aggfunc.bind(this, x => (x / empfields.length))

    let mData = this._process(data, agg, noagg)

    let graphMargin = {
      top    : 10,
      left   : 60,
      right  : 20,
      bottom : 20,
    }

    return (

            <LineGraph
                key={this.props.field}
                data={mData.data}
                uniq={this.props.field}
                title={'Quarterly ' + this.props.title}
                yFormat={(this.props.type === 'totalwages') ? lineGraphDollarFormatter : integerFormatter}
                xScaleType={'linear'}
                yAxis={true}
                margin={graphMargin}
                tooltip={true}
                onMouse={this._onMouse}
                graphSlice={this.props.qtrData} />

            <LineGraph
                key={'lq_'+this.props.field}
                data={mData.lqdata}
                uniq={'lq_'+this.props.field}
                xFormat={(x)=>this.revMap(x)}
                yFormat={floatFormatter}
                title={'Quarterly LQ '+ this.props.title}
                xAxis={true}
                xScaleType={'linear'}
                yAxis={true}
                margin={graphMargin}
                tooltip={true}
                onMouse={this._onMouse}
                graphSlice={this.props.qtrData} />

          {this.renderToolTip(mData.data)}

    )
  }
}

const mapStateToProps = (state) => ({
  data      : state.metroQcewData.data,
  naicsKeys : state.metros.naicsKeys,
  qtrData   : state.metroQcewData.qtrData
})

export default connect((mapStateToProps), {
  loadData      : (msaId, year) => loadMetroData(msaId),
  loadNaicsKeys : () => loadNaicsKeys(),
  setQtr        : (d) => setMetroQuarter(d),
})(NaicsGraph)
<|endoftext|>


<commit_before>import React from 'react';
import {
  StyleSheet,
  AsyncStorage,
  TouchableHighlight,
  Image
} from 'react-native';
import { Font } from 'exponent';
import { Container, Header, Title, Content, Footer, Button } from 'native-base';
import { Ionicons } from '@exponent/vector-icons';

var STORAGE_KEY = 'id_token';

export default class Memories extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      image: {},
      imageList: [],
      fontLoaded: false
    };
  }

  async componentDidMount() {
    await Font.loadAsync({
      'pacifico': require('./assets/fonts/Pacifico.ttf'),
    });
    this.setState({ fontLoaded: true });
    this.fetchMemories();
  }

  _navigate(image) {
    this.props.navigator.push({
      name: 'Memory',
      passProps: {
        'image': {uri: image.uri},
        'id': image.id,
        'prevScene': 'Memories'
      }
    });
  }

  _navigateHome() {
    this.props.navigator.push({
      name: 'Homescreen',
      passProps: {
        'username': this.props.username
      }
    });
  }

  async fetchMemories() {
    var context = this;
    try {
      var token =  await AsyncStorage.getItem(STORAGE_KEY);
    } catch (error) {
      console.log('AsyncStorage error: ' + error.message);
    }

    fetch('https://invalid-memories-greenfield.herokuapp.com/api/memories/all', {
      method: 'GET',
      headers: {
        'Authorization': 'Bearer ' + token
      }
    })
    .then(function(memories) {
      var memoryArray = JSON.parse(memories['_bodyInit']);
      var images = memoryArray.map(memory => {
        return {
          id: memory._id,
          uri: memory.filePath
        };
      });
      context.setState({imageList: images});
    });
  }

  render() {
    return (
      <Container>
        {
          this.state.fontLoaded ? (
        <Header>
          <Button transparent onPress={() => this.props.navigator.pop()}>
            <Ionicons name="ios-arrow-back" size={32} style={{color: '#25a2c3', marginTop: 5}}/>
          </Button>
          <Title style={styles.headerText}>{this.props.username}'s Memories</Title>
          <Button transparent onPress={this._navigateHome.bind(this)}>
            <Ionicons name="ios-home" size={35} color="#444" />
          </Button>
        </Header>
          ) : null
        }
        <Content contentContainerStyle={{
          flexWrap: 'wrap',
          flexDirection: 'row',
          justifyContent: 'center',
          alignItems: 'center'
        }}>
          {
            this.state.imageList.map(image =>
              <TouchableHighlight onPress={this._navigate.bind(this, image)}>
                <Image style={styles.thumbnail} resizeMode={Image.resizeMode.contain} source={{uri: image.uri}}/>
              </TouchableHighlight>
            )
          }
        </Content>
      </Container>
    );
  }
}

const styles = StyleSheet.create({
  headerText: {
    ...Font.style('pacifico'),
    fontSize: 30,
    color: '#444',
    paddingTop: 25
  },

  thumbnail: {
    width: 90,
    height: 90,
    margin: 1
  }
});
<commit_msg>(fix) Pass on username through all navigations1:w<commit_after>import React from 'react';
import {
  StyleSheet,
  AsyncStorage,
  TouchableHighlight,
  Image
} from 'react-native';
import { Font } from 'exponent';
import { Container, Header, Title, Content, Footer, Button } from 'native-base';
import { Ionicons } from '@exponent/vector-icons';

var STORAGE_KEY = 'id_token';

export default class Memories extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      image: {},
      imageList: [],
      fontLoaded: false
    };
  }

  async componentDidMount() {
    await Font.loadAsync({
      'pacifico': require('./assets/fonts/Pacifico.ttf'),
    });
    this.setState({ fontLoaded: true });
    this.fetchMemories();
  }

  _navigate(image) {
    this.props.navigator.push({
      name: 'Memory',
      passProps: {
        'image': {uri: image.uri},
        'id': image.id,
        'username': this.props.username,
        'prevScene': 'Memories'
      }
    });
  }

  _navigateHome() {
    this.props.navigator.push({
      name: 'Homescreen',
      passProps: {
        'username': this.props.username
      }
    });
  }

  async fetchMemories() {
    var context = this;
    try {
      var token =  await AsyncStorage.getItem(STORAGE_KEY);
    } catch (error) {
      console.log('AsyncStorage error: ' + error.message);
    }

    fetch('https://invalid-memories-greenfield.herokuapp.com/api/memories/all', {
      method: 'GET',
      headers: {
        'Authorization': 'Bearer ' + token
      }
    })
    .then(function(memories) {
      var memoryArray = JSON.parse(memories['_bodyInit']);
      var images = memoryArray.map(memory => {
        return {
          id: memory._id,
          uri: memory.filePath
        };
      });
      context.setState({imageList: images});
    });
  }

  render() {
    return (
      <Container>
        {
          this.state.fontLoaded ? (
        <Header>
          <Button transparent onPress={() => this.props.navigator.pop()}>
            <Ionicons name="ios-arrow-back" size={32} style={{color: '#25a2c3', marginTop: 5}}/>
          </Button>
          <Title style={styles.headerText}>{this.props.username}'s Memories</Title>
          <Button transparent onPress={this._navigateHome.bind(this)}>
            <Ionicons name="ios-home" size={35} color="#444" />
          </Button>
        </Header>
          ) : null
        }
        <Content contentContainerStyle={{
          flexWrap: 'wrap',
          flexDirection: 'row',
          justifyContent: 'center',
          alignItems: 'center'
        }}>
          {
            this.state.imageList.map(image =>
              <TouchableHighlight onPress={this._navigate.bind(this, image)}>
                <Image style={styles.thumbnail} resizeMode={Image.resizeMode.contain} source={{uri: image.uri}}/>
              </TouchableHighlight>
            )
          }
        </Content>
      </Container>
    );
  }
}

const styles = StyleSheet.create({
  headerText: {
    ...Font.style('pacifico'),
    fontSize: 30,
    color: '#444',
    paddingTop: 25
  },

  thumbnail: {
    width: 90,
    height: 90,
    margin: 1
  }
});
<|endoftext|>


<commit_before>import $ from '../../utils/dom';
import Utils from '../../utils/utils';

const Parallax = {
  setTransform(el, progress) {
    const swiper = this;
    const { rtl } = swiper;

    const $el = $(el);
    const rtlFactor = rtl ? -1 : 1;

    const p = $el.attr('data-swiper-parallax') || '0';
    let x = $el.attr('data-swiper-parallax-x');
    let y = $el.attr('data-swiper-parallax-y');
    const scale = $el.attr('data-swiper-parallax-scale');
    const opacity = $el.attr('data-swiper-parallax-opacity');

    if (x || y) {
      x = x || '0';
      y = y || '0';
    } else if (swiper.isHorizontal()) {
      x = p;
      y = '0';
    } else {
      y = p;
      x = '0';
    }

    if ((x).indexOf('%') >= 0) {
      x = `${parseInt(x, 10) * progress * rtlFactor}%`;
    } else {
      x = `${x * progress * rtlFactor}px`;
    }
    if ((y).indexOf('%') >= 0) {
      y = `${parseInt(y, 10) * progress}%`;
    } else {
      y = `${y * progress}px`;
    }

    if (typeof opacity !== 'undefined' && opacity !== null) {
      const currentOpacity = opacity - ((opacity - 1) * (1 - Math.abs(progress)));
      $el[0].style.opacity = currentOpacity;
    }
    if (typeof scale === 'undefined' || scale === null) {
      $el.transform(`translate3d(${x}, ${y}, 0px)`);
    } else {
      const currentScale = scale - ((scale - 1) * (1 - Math.abs(progress)));
      $el.transform(`translate3d(${x}, ${y}, 0px) scale(${currentScale})`);
    }
  },
  setTranslate() {
    const swiper = this;
    const {
      $el, slides, progress, snapGrid,
    } = swiper;
    $el.children('[data-swiper-parallax], [data-swiper-parallax-x], [data-swiper-parallax-y]')
      .each((index, el) => {
        swiper.parallax.setTransform(el, progress);
      });
    slides.each((slideIndex, slideEl) => {
      let slideProgress = slideEl.progress;
      if (swiper.params.slidesPerGroup > 1 && swiper.params.slidesPerView !== 'auto') {
        slideProgress += Math.ceil(slideIndex / 2) - (progress * (snapGrid.length - 1));
      }
      slideProgress = Math.min(Math.max(slideProgress, -1), 1);
      $(slideEl).find('[data-swiper-parallax], [data-swiper-parallax-x], [data-swiper-parallax-y]')
        .each((index, el) => {
          swiper.parallax.setTransform(el, slideProgress);
        });
    });
  },
  setTransition(duration = this.params.speed) {
    const swiper = this;
    const { $el } = swiper;
    $el.find('[data-swiper-parallax], [data-swiper-parallax-x], [data-swiper-parallax-y]')
      .each((index, parallaxEl) => {
        const $parallaxEl = $(parallaxEl);
        let parallaxDuration = parseInt($parallaxEl.attr('data-swiper-parallax-duration'), 10) || duration;
        if (duration === 0) parallaxDuration = 0;
        $parallaxEl.transition(parallaxDuration);
      });
  },
};

export default {
  name: 'parallax',
  params: {
    parallax: {
      enabled: false,
    },
  },
  create() {
    const swiper = this;
    Utils.extend(swiper, {
      parallax: {
        setTransform: Parallax.setTransform.bind(swiper),
        setTranslate: Parallax.setTranslate.bind(swiper),
        setTransition: Parallax.setTransition.bind(swiper),
      },
    });
  },
  on: {
    beforeInit() {
      const swiper = this;
      if (!swiper.params.parallax.enabled) return;
      swiper.params.watchSlidesProgress = true;
      swiper.originalParams.watchSlidesProgress = true;
    },
    init() {
      const swiper = this;
      if (!swiper.params.parallax) return;
      swiper.parallax.setTranslate();
    },
    setTranslate() {
      const swiper = this;
      if (!swiper.params.parallax) return;
      swiper.parallax.setTranslate();
    },
    setTransition(duration) {
      const swiper = this;
      if (!swiper.params.parallax) return;
      swiper.parallax.setTransition(duration);
    },
  },
};
<commit_msg>Fix parallax still being applied when disabled<commit_after>import $ from '../../utils/dom';
import Utils from '../../utils/utils';

const Parallax = {
  setTransform(el, progress) {
    const swiper = this;
    const { rtl } = swiper;

    const $el = $(el);
    const rtlFactor = rtl ? -1 : 1;

    const p = $el.attr('data-swiper-parallax') || '0';
    let x = $el.attr('data-swiper-parallax-x');
    let y = $el.attr('data-swiper-parallax-y');
    const scale = $el.attr('data-swiper-parallax-scale');
    const opacity = $el.attr('data-swiper-parallax-opacity');

    if (x || y) {
      x = x || '0';
      y = y || '0';
    } else if (swiper.isHorizontal()) {
      x = p;
      y = '0';
    } else {
      y = p;
      x = '0';
    }

    if ((x).indexOf('%') >= 0) {
      x = `${parseInt(x, 10) * progress * rtlFactor}%`;
    } else {
      x = `${x * progress * rtlFactor}px`;
    }
    if ((y).indexOf('%') >= 0) {
      y = `${parseInt(y, 10) * progress}%`;
    } else {
      y = `${y * progress}px`;
    }

    if (typeof opacity !== 'undefined' && opacity !== null) {
      const currentOpacity = opacity - ((opacity - 1) * (1 - Math.abs(progress)));
      $el[0].style.opacity = currentOpacity;
    }
    if (typeof scale === 'undefined' || scale === null) {
      $el.transform(`translate3d(${x}, ${y}, 0px)`);
    } else {
      const currentScale = scale - ((scale - 1) * (1 - Math.abs(progress)));
      $el.transform(`translate3d(${x}, ${y}, 0px) scale(${currentScale})`);
    }
  },
  setTranslate() {
    const swiper = this;
    const {
      $el, slides, progress, snapGrid,
    } = swiper;
    $el.children('[data-swiper-parallax], [data-swiper-parallax-x], [data-swiper-parallax-y]')
      .each((index, el) => {
        swiper.parallax.setTransform(el, progress);
      });
    slides.each((slideIndex, slideEl) => {
      let slideProgress = slideEl.progress;
      if (swiper.params.slidesPerGroup > 1 && swiper.params.slidesPerView !== 'auto') {
        slideProgress += Math.ceil(slideIndex / 2) - (progress * (snapGrid.length - 1));
      }
      slideProgress = Math.min(Math.max(slideProgress, -1), 1);
      $(slideEl).find('[data-swiper-parallax], [data-swiper-parallax-x], [data-swiper-parallax-y]')
        .each((index, el) => {
          swiper.parallax.setTransform(el, slideProgress);
        });
    });
  },
  setTransition(duration = this.params.speed) {
    const swiper = this;
    const { $el } = swiper;
    $el.find('[data-swiper-parallax], [data-swiper-parallax-x], [data-swiper-parallax-y]')
      .each((index, parallaxEl) => {
        const $parallaxEl = $(parallaxEl);
        let parallaxDuration = parseInt($parallaxEl.attr('data-swiper-parallax-duration'), 10) || duration;
        if (duration === 0) parallaxDuration = 0;
        $parallaxEl.transition(parallaxDuration);
      });
  },
};

export default {
  name: 'parallax',
  params: {
    parallax: {
      enabled: false,
    },
  },
  create() {
    const swiper = this;
    Utils.extend(swiper, {
      parallax: {
        setTransform: Parallax.setTransform.bind(swiper),
        setTranslate: Parallax.setTranslate.bind(swiper),
        setTransition: Parallax.setTransition.bind(swiper),
      },
    });
  },
  on: {
    beforeInit() {
      const swiper = this;
      if (!swiper.params.parallax.enabled) return;
      swiper.params.watchSlidesProgress = true;
      swiper.originalParams.watchSlidesProgress = true;
    },
    init() {
      const swiper = this;
      if (!swiper.params.parallax.enabled) return;
      swiper.parallax.setTranslate();
    },
    setTranslate() {
      const swiper = this;
      if (!swiper.params.parallax.enabled) return;
      swiper.parallax.setTranslate();
    },
    setTransition(duration) {
      const swiper = this;
      if (!swiper.params.parallax.enabled) return;
      swiper.parallax.setTransition(duration);
    },
  },
};
<|endoftext|>


<commit_before>import React from 'react';
import ChevronLeft from 'material-ui/svg-icons/navigation/chevron-left';
import ChevronRight from 'material-ui/svg-icons/navigation/chevron-right';
import FilterList from 'material-ui/svg-icons/content/filter-list';
import EventIcon from 'material-ui/svg-icons/action/event';
import Checkbox from 'material-ui/Checkbox';
import classNames from 'classnames';
import moment from 'moment';
import {default as MaterialDatePicker} from 'material-ui/DatePicker';

import './FilterMenu.css';

class FilterMenu extends React.Component {

  constructor(props) {
    super(props);

    this.state = {
      date: new Date(),
    };
  }

  _handleDatePickerOpen() {
    this.refs.bookingDatePicker.openDialog();
  }

  _handleDatePickerChange(nil, d) {
    this.setState({
      date: d,
    });
  }

  render() {
    return (

          <FilterList className='filter-list-icon-svg' />

            {moment(this.state.date).format('ddd, MMM Do, YYYY')}

            <EventIcon className='filter-date-picker-svg' />

            <ChevronLeft className='filter-chevron-svg' />

            TODAY

            <ChevronRight className='filter-chevron-svg' />

        <MaterialDatePicker
          id='booking-date-picker'
          style={{display: 'none'}}
          ref='bookingDatePicker'
          autoOk={true}
          minDate={new Date()}
          maxDate={new Date(2050, 0, 0, 0, 0, 0, 0)}
          disableYearSelection={false}
          onChange={this._handleDatePickerChange.bind(this)}
        />

    );
  }
}

export default FilterMenu;<commit_msg>Rig up date navigators<commit_after>import React from 'react';
import ChevronLeft from 'material-ui/svg-icons/navigation/chevron-left';
import ChevronRight from 'material-ui/svg-icons/navigation/chevron-right';
import FilterList from 'material-ui/svg-icons/content/filter-list';
import EventIcon from 'material-ui/svg-icons/action/event';
import Checkbox from 'material-ui/Checkbox';
import classNames from 'classnames';
import moment from 'moment';
import {default as MaterialDatePicker} from 'material-ui/DatePicker';

import './FilterMenu.css';

class FilterMenu extends React.Component {

  constructor(props) {
    super(props);

    this.state = {
      date: new Date(),
    };
  }

  _handleDatePickerOpen() {
    this.refs.bookingDatePicker.openDialog();
  }

  _handleDatePickerChange(nil, d) {
    this.setState({
      date: d,
    });
  }

  _backOne() {
    // TODO: alternative behaviour for week/month
    let newDate = new Date(this.state.date);
    newDate.setDate(newDate.getDate() - 1);
    this.setState({
      date: newDate,
    });
  }

  _forwardsOne() {
    // TODO: alternative behaviour for week/month
    let newDate = new Date(this.state.date);
    newDate.setDate(newDate.getDate() + 1);
    this.setState({
      date: newDate,
    });
  }

  _jumpToToday() {
    this.setState({
      date: new Date(),
    });
  }

  render() {
    return (

          <FilterList className='filter-list-icon-svg' />

            {moment(this.state.date).format('ddd, MMM Do, YYYY')}

            <EventIcon className='filter-date-picker-svg' />

            <ChevronLeft className='filter-chevron-svg' />

            TODAY

            <ChevronRight className='filter-chevron-svg' />

        <MaterialDatePicker
          id='booking-date-picker'
          style={{display: 'none'}}
          ref='bookingDatePicker'
          autoOk={true}
          minDate={new Date()}
          maxDate={new Date(2050, 0, 0, 0, 0, 0, 0)}
          disableYearSelection={false}
          onChange={this._handleDatePickerChange.bind(this)}
        />

    );
  }
}

export default FilterMenu;<|endoftext|>


<commit_before>/**
* Copyright 2012-2016, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var annAttrs = require('../annotations/attributes');
var scatterAttrs = require('../../traces/scatter/attributes');
var extendFlat = require('../../lib/extend').extendFlat;

var scatterLineAttrs = scatterAttrs.line;

module.exports = {
    _isLinkedToArray: true,

    type: {
        valType: 'enumerated',
        values: ['circle', 'rect', 'path', 'line'],
        role: 'info',
        description: [
            'Specifies the shape type to be drawn.',

            'If *line*, a line is drawn from (`x0`,`y0`) to (`x1`,`y1`)',

            'If *circle*, a circle is drawn from',
            '((`x0`+`x1`)/2, (`y0`+`y1`)/2))',
            'with radius',
            '(|(`x0`+`x1`)/2 - `x0`|, |(`y0`+`y1`)/2 -`y0`)|)',

            'If *rect*, a rectangle is drawn linking',
            '(`x0`,`y0`), (`x1`,`y0`), (`x1`,`y1`), (`x0`,`y1`), (`x0`,`y0`)',

            'If *path*, draw a custom SVG path using `path`.'
        ].join(' ')
    },

    layer: {
        valType: 'enumerated',
        values: ['below', 'above'],
        dflt: 'above',
        role: 'info',
        description: 'Specifies whether shapes are drawn below or above traces.'
    },

    xref: extendFlat({}, annAttrs.xref, {
        description: [
            'Sets the shape\'s x coordinate axis.',
            'If set to an x axis id (e.g. *x* or *x2*), the `x` position',
            'refers to an x coordinate',
            'If set to *paper*, the `x` position refers to the distance from',
            'the left side of the plotting area in normalized coordinates',
            'where *0* (*1*) corresponds to the left (right) side.'
        ].join(' ')
    }),
    x0: {
        valType: 'any',
        role: 'info',
        description: [
            'Sets the shape\'s starting x position.',
            'See `type` for more info.'
        ].join(' ')
    },
    x1: {
        valType: 'any',
        role: 'info',
        description: [
            'Sets the shape\'s end x position.',
            'See `type` for more info.'
        ].join(' ')
    },

    yref: extendFlat({}, annAttrs.yref, {
        description: [
            'Sets the annotation\'s y coordinate axis.',
            'If set to an y axis id (e.g. *y* or *y2*), the `y` position',
            'refers to an y coordinate',
            'If set to *paper*, the `y` position refers to the distance from',
            'the bottom of the plotting area in normalized coordinates',
            'where *0* (*1*) corresponds to the bottom (top).'
        ].join(' ')
    }),
    y0: {
        valType: 'any',
        role: 'info',
        description: [
            'Sets the shape\'s starting y position.',
            'See `type` for more info.'
        ].join(' ')
    },
    y1: {
        valType: 'any',
        role: 'info',
        description: [
            'Sets the shape\'s end y position.',
            'See `type` for more info.'
        ].join(' ')
    },

    path: {
        valType: 'string',
        role: 'info',
        description: [
            'For `type` *path* - a valid SVG path but with the pixel values',
            'replaced by data values. There are a few restrictions / quirks',
            'only absolute instructions, not relative. So the allowed segments',
            'are: M, L, H, V, Q, C, T, S, and Z',
            'arcs (A) are not allowed because radius rx and ry are relative.',

            'In the future we could consider supporting relative commands,',
            'but we would have to decide on how to handle date and log axes.',
            'Note that even as is, Q and C Bezier paths that are smooth on',
            'linear axes may not be smooth on log, and vice versa.',
            'no chained "polybezier" commands - specify the segment type for',
            'each one.',

            'On category axes, values are numbers scaled to the serial numbers',
            'of categories because using the categories themselves there would',
            'be no way to describe fractional positions',
            'On data axes: because space and T are both normal components of path',
            'strings, we can\'t use either to separate date from time parts.',
            'Therefore we\'ll use underscore for this purpose:',
            '2015-02-21_13:45:56.789'
        ].join(' ')
    },

    opacity: {
        valType: 'number',
        min: 0,
        max: 1,
        dflt: 1,
        role: 'info',
        description: 'Sets the opacity of the shape.'
    },
    line: {
        color: scatterLineAttrs.color,
        width: scatterLineAttrs.width,
        dash: scatterLineAttrs.dash,
        role: 'info'
    },
    fillcolor: {
        valType: 'color',
        dflt: 'rgba(0,0,0,0)',
        role: 'info',
        description: [
            'Sets the color filling the shape\'s interior.'
        ].join(' ')
    }
};
<commit_msg>Copy over information about x-axis data type to shape attributes<commit_after>/**
* Copyright 2012-2016, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var annAttrs = require('../annotations/attributes');
var scatterAttrs = require('../../traces/scatter/attributes');
var extendFlat = require('../../lib/extend').extendFlat;

var scatterLineAttrs = scatterAttrs.line;

module.exports = {
    _isLinkedToArray: true,

    type: {
        valType: 'enumerated',
        values: ['circle', 'rect', 'path', 'line'],
        role: 'info',
        description: [
            'Specifies the shape type to be drawn.',

            'If *line*, a line is drawn from (`x0`,`y0`) to (`x1`,`y1`)',

            'If *circle*, a circle is drawn from',
            '((`x0`+`x1`)/2, (`y0`+`y1`)/2))',
            'with radius',
            '(|(`x0`+`x1`)/2 - `x0`|, |(`y0`+`y1`)/2 -`y0`)|)',

            'If *rect*, a rectangle is drawn linking',
            '(`x0`,`y0`), (`x1`,`y0`), (`x1`,`y1`), (`x0`,`y1`), (`x0`,`y0`)',

            'If *path*, draw a custom SVG path using `path`.',
        ].join(' ')
    },

    layer: {
        valType: 'enumerated',
        values: ['below', 'above'],
        dflt: 'above',
        role: 'info',
        description: 'Specifies whether shapes are drawn below or above traces.'
    },

    xref: extendFlat({}, annAttrs.xref, {
        description: [
            'Sets the shape\'s x coordinate axis.',
            'If set to an x axis id (e.g. *x* or *x2*), the `x` position',
            'refers to an x coordinate',
            'If set to *paper*, the `x` position refers to the distance from',
            'the left side of the plotting area in normalized coordinates',
            'where *0* (*1*) corresponds to the left (right) side.',
            'If the axis `type` is *log*, then you must take the',
            'log of your desired range.',
            'If the axis `type` is *date*, then you must convert',
            'the date to unix time in milliseconds.'
        ].join(' ')
    }),
    x0: {
        valType: 'any',
        role: 'info',
        description: [
            'Sets the shape\'s starting x position.',
            'See `type` for more info.'
        ].join(' ')
    },
    x1: {
        valType: 'any',
        role: 'info',
        description: [
            'Sets the shape\'s end x position.',
            'See `type` for more info.'
        ].join(' ')
    },

    yref: extendFlat({}, annAttrs.yref, {
        description: [
            'Sets the annotation\'s y coordinate axis.',
            'If set to an y axis id (e.g. *y* or *y2*), the `y` position',
            'refers to an y coordinate',
            'If set to *paper*, the `y` position refers to the distance from',
            'the bottom of the plotting area in normalized coordinates',
            'where *0* (*1*) corresponds to the bottom (top).'
        ].join(' ')
    }),
    y0: {
        valType: 'any',
        role: 'info',
        description: [
            'Sets the shape\'s starting y position.',
            'See `type` for more info.'
        ].join(' ')
    },
    y1: {
        valType: 'any',
        role: 'info',
        description: [
            'Sets the shape\'s end y position.',
            'See `type` for more info.'
        ].join(' ')
    },

    path: {
        valType: 'string',
        role: 'info',
        description: [
            'For `type` *path* - a valid SVG path but with the pixel values',
            'replaced by data values. There are a few restrictions / quirks',
            'only absolute instructions, not relative. So the allowed segments',
            'are: M, L, H, V, Q, C, T, S, and Z',
            'arcs (A) are not allowed because radius rx and ry are relative.',

            'In the future we could consider supporting relative commands,',
            'but we would have to decide on how to handle date and log axes.',
            'Note that even as is, Q and C Bezier paths that are smooth on',
            'linear axes may not be smooth on log, and vice versa.',
            'no chained "polybezier" commands - specify the segment type for',
            'each one.',

            'On category axes, values are numbers scaled to the serial numbers',
            'of categories because using the categories themselves there would',
            'be no way to describe fractional positions',
            'On data axes: because space and T are both normal components of path',
            'strings, we can\'t use either to separate date from time parts.',
            'Therefore we\'ll use underscore for this purpose:',
            '2015-02-21_13:45:56.789'
        ].join(' ')
    },

    opacity: {
        valType: 'number',
        min: 0,
        max: 1,
        dflt: 1,
        role: 'info',
        description: 'Sets the opacity of the shape.'
    },
    line: {
        color: scatterLineAttrs.color,
        width: scatterLineAttrs.width,
        dash: scatterLineAttrs.dash,
        role: 'info'
    },
    fillcolor: {
        valType: 'color',
        dflt: 'rgba(0,0,0,0)',
        role: 'info',
        description: [
            'Sets the color filling the shape\'s interior.'
        ].join(' ')
    }
};
<|endoftext|>


<commit_before>
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */

function position(page_element_id, default_mode) {

    "use strict";

    /* Default mode can be "basic" or "column" */

    var page = document.getElementById(page_element_id);
    var isso = document.getElementById("isso-thread");
    var first_call = true;

    this.column = function() {
        if (first_call) {
            isso.style.position = "fixed";
        }
        else {
            var handler = function() {
                isso.style.position = "fixed";
                page.removeEventListener("transitionend", handler);
            };
            page.addEventListener("transitionend", handler);
        }
        page.style.marginLeft = "5%";
        isso.style.left = "calc(" + page.clientWidth + "px + 10%)";
        isso.style.right = "5%";
        isso.style.top = "5%";
        isso.style.bottom = "0";
    };

    this.basic = function() {
        isso.style.position = "static";
        page.style.marginLeft = (window.innerWidth - page.clientWidth) / 2 + "px";
    };

    /* Switch to default mode before setting a transition */
    if (default_mode == "column") {
        this.column();
    }
    else {
        this.basic();
    }
    first_call = false;

    page.style.transition = "margin-left 1s";
};

<commit_msg>center isso vertically<commit_after>
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */

function position(page_element_id, default_mode) {

    "use strict";

    /* Default mode can be "basic" or "column" */

    var page = document.getElementById(page_element_id);
    var isso = document.getElementById("isso-thread");
    var first_call = true;

    this.column = function() {
        if (first_call) {
            isso.style.position = "fixed";
        }
        else {
            var handler = function() {
                isso.style.position = "fixed";
                page.removeEventListener("transitionend", handler);
            };
            page.addEventListener("transitionend", handler);
        }
        page.style.marginLeft = "5%";
        isso.style.left = "calc(" + page.clientWidth + "px + 10%)";
        isso.style.right = "5%";
        isso.style.top = "5%";
        isso.style.bottom = "5%";
    };

    this.basic = function() {
        isso.style.position = "static";
        page.style.marginLeft = (window.innerWidth - page.clientWidth) / 2 + "px";
    };

    /* Switch to default mode before setting a transition */
    if (default_mode == "column") {
        this.column();
    }
    else {
        this.basic();
    }
    first_call = false;

    page.style.transition = "margin-left 1s";
};

<|endoftext|>


<commit_before>import React from 'react';
import TestUtils from 'react-dom/test-utils';
import { shallow, mount } from 'enzyme';
import { elementsTagTest, rootTagTest } from '../../utils/helpers/tags/tags-specs';
import Textarea from './textarea';

describe('Textarea', () => {
  let baseWrapper, expandableWrapper, overLimitWrapper, notOverLimitWrapper,
      baseInstance, expandableInstance;
  let spy = jasmine.createSpy('spy');

  beforeEach(() => {
    baseWrapper = mount(
      <Textarea
        id='Dummy Area'
        value={ 'foo' }
        label={ 'Label' }
        cols={10}
        rows={10}
        onChange={ spy }
      />
    );
    baseInstance = baseWrapper.instance();

    expandableWrapper = mount(
      <Textarea
        value={ 'foo' }
        label={ 'Label' }
        expandable={ true }
        cols={10}
        rows={10}
        characterLimit='100'
        onChange={ spy }
      />
    );
    expandableInstance = expandableWrapper.instance();

    overLimitWrapper = shallow(
      <Textarea
        name="Dummy Area"
        value={ 'foofoofoofoo' }
        label={ 'Label' }
        warnOverLimit={ true }
        cols={10}
        rows={10}
        characterLimit='10'
        onChange={ spy }
      />
    );

    notOverLimitWrapper = shallow(
      <Textarea
        name="Dummy Area"
        value={ 'foofoofoo' }
        label={ 'Label' }
        warnOverLimit={ true }
        cols={10}
        rows={10}
        characterLimit='10'
        onChange={ spy }
    />);
  });

  describe('componentDidMount', () => {
    describe('when textarea can be expanded', () => {

      it('adds a event listener to the window', () => {
        spyOn(window, 'addEventListener');
        expandableInstance.componentDidMount();
        expect(window.addEventListener).toHaveBeenCalledWith(
          'resize', expandableInstance.expandTextarea
        );
      });

      it('sets the minHeight to the rendered client height', () => {
        expect(expandableInstance.minHeight).toEqual(
          expandableInstance._input.clientHeight
        );
      });

      it('calls expandTextarea', () => {
        spyOn(expandableInstance, 'expandTextarea');
        expandableInstance.componentDidMount();
        expect(expandableInstance.expandTextarea).toHaveBeenCalled();
      });
    });

    describe('when textarea cannot be expanded', () => {
      it('does not setup the textarea for expanding', () => {
        spyOn(window, 'addEventListener');
        spyOn(baseInstance, 'expandTextarea');
        baseInstance.componentDidMount();
        expect(window.addEventListener).not.toHaveBeenCalled();
        expect(baseInstance.expandTextarea).not.toHaveBeenCalled();
      });
    });
  });

  describe('componentWillUnmount', () => {
    beforeEach(() => {
      spyOn(window, 'removeEventListener');
    });

    describe('when textarea can be expanded', () => {
      let wrapper = mount(
        <Textarea
          value={ 'foo' }
          label={ 'Label' }
          expandable={ true }
          cols={10}
          rows={10}
          characterLimit='100'
          onChange={ spy }
        />
      );

      it('removes the event listener from the window', () => {
        wrapper.unmount();
        expect(window.removeEventListener).toHaveBeenCalledWith(
          'resize',jasmine.any(Function)
        );
      });
    });

    describe('when textarea cannot be expanded', () => {
      let wrapper = shallow(
        <Textarea
          id='Dummy Area'
          value={ 'foo' }
          label={ 'Label' }
          cols={10}
          rows={10}
          onChange={ spy }
        />
      );

      it('does not remove event listener from the window', () => {
        wrapper.unmount();
        expect(window.removeEventListener).not.toHaveBeenCalled();
      });
    });
  });

  describe('componentDidUpdate', () => {
    describe('when textarea can be expanded', () => {
      beforeEach(() => {
        spyOn(expandableInstance, 'expandTextarea');
      });
      it('should call to resize the textarea', () => {
        expandableInstance.valLength = 2000;
        expandableInstance.componentDidUpdate({});
        expect(expandableInstance.expandTextarea).toHaveBeenCalled();
      });
    });

    describe('when textarea cannot be expanded', () => {
      beforeEach(() => {
        spyOn(baseInstance, 'expandTextarea');
        baseInstance.valLength = 2000;
        baseInstance.componentDidUpdate({});
      });

      it('does not resize the textarea', () => {
        expect(baseInstance.expandTextarea).not.toHaveBeenCalled();
      });
    });
  });

  describe('expandTextarea', () => {
    describe('when scrollHeight is greater than the min height', () => {
      it('sets the textareas height to fit the content', () => {
        expandableInstance._input = {
          scrollHeight: 100,
          value: 'foo',
          style: { height: 0 }
        }
        expandableInstance.expandTextarea();
        expect(expandableInstance._input.style.height).toEqual('100px');
      });
    });

    describe('when the scrollHeight is less than the minHeight', () => {
      it('does not update the textarea', () => {
        expandableInstance._input = {
          scrollHeight: 5,
          value: 'foo',
          style: { height: 0 }
        }
        expandableInstance.minHeight = 20;
        expandableInstance.expandTextarea();
        expect(expandableInstance._input.style.height).toEqual(0);
      });
    });
  });

  describe('mainClasses', () => {
    it('returns carbon-textarea and additional decorated classes', () => {
      expect(baseWrapper.find('.carbon-textarea.common-input').exists()).toBeTruthy();
    });
  });

  describe('inputClasses', () => {
    it('returns carbon-textarea__input and additional decorated classes', () => {
      expect(baseWrapper.find('.carbon-textarea__input.common-input__input').exists()).toBeTruthy();
    });

    describe('if the textarea is expandable', () => {
      it('returns an additional disable-scroll class', () => {
        expect(expandableWrapper.find('.carbon-textarea__input.carbon-textarea__input--disable-scroll.common-input__input').exists()).toBeTruthy();
      });
    });
  });

  describe('textAreaClasses', () => {
    it('returns carbon-textarea__character-limit class', () => {
      expect(notOverLimitWrapper.find('.carbon-textarea__character-limit').exists()).toBeTruthy();
    });

    describe('overlimit', () => {
      describe('if the textarea char count is over limit', () => {
        it('returns an additional over-limit class', () => {
          expect(overLimitWrapper.find('.carbon-textarea__character-limit.over-limit').exists()).toBeTruthy();
        });
      });

      describe('if the textarea value is empty', () => {
        it('does not add a extra class', () => {
          overLimitWrapper.setProps({ value: '' });
          expect(overLimitWrapper.find('.carbon-textarea__character-limit.over-limit').exists()).toBeFalsy();
        });
      });

      describe('if the textarea value is under the limit', () => {
        it('does not add a extra class', () => {
          overLimitWrapper.setProps({ value: 'foo' });
          expect(overLimitWrapper.find('.carbon-textarea__character-limit.over-limit').exists()).toBeFalsy();
        });
      });
    });
  });

  describe('characterCount', () => {
    describe('when characterLimit is set', () => {
      it('returns character limit div', () => {
        let counter = TestUtils.findRenderedDOMComponentWithClass(expandableInstance, 'carbon-textarea__character-limit');
        expect(counter.textContent).toEqual('You have used 3 of 100 characters');
      });
    });

    describe('when characterLimit is not set', () => {
      it('returns null', () => {
        expect(baseInstance.characterCount).toBeNull();
      });
    });
  });

  describe('render', () => {
    it('renders a parent div', () => {
      let textareaNode = TestUtils.scryRenderedDOMComponentsWithTag(baseInstance, 'div')[0];
      expect(textareaNode.classList[0]).toEqual('carbon-textarea');
    });

    it('renders with a visible input with rows and columns', () => {
      let input = TestUtils.findRenderedDOMComponentWithTag(baseInstance, 'textarea')
      expect(input.rows).toBe(10);
      expect(input.cols).toBe(10);
    });

    it('is decorated with a label', () => {
      let label = TestUtils.findRenderedDOMComponentWithTag(baseInstance, 'label')
      expect(label.getAttribute('for')).toEqual('Dummy Area');
    });

    it('is decorated with a validation if a error is present', () => {
      baseInstance.setState({errorMessage: 'Error', valid: false});
      let errorDiv = TestUtils.findRenderedDOMComponentWithClass(baseInstance, 'common-input__message--error')
      expect(errorDiv.textContent).toEqual('Error')
    });

    describe('when characterLimit is set', () => {
      describe('and enforceCharacterLimit is true', () => {
        it('sets a maxLength on the input', () => {
          let input = TestUtils.findRenderedDOMComponentWithTag(expandableInstance, 'textarea')
          expect(input.maxLength).toEqual(100);
        });
      });

      describe('and enforceCharacterLimit is false', () => {
        it('does not set a maxLength on the input', () => {
          let instance = TestUtils.renderIntoDocument(
            <Textarea
              label={ 'Label' }
              characterLimit='100'
              enforceCharacterLimit={ false }
            />
          );
          let input = TestUtils.findRenderedDOMComponentWithTag(instance, 'textarea')
          // https://github.com/tmpvar/jsdom/issues/522
          // JSDom defaults to 0 instead of -1
          expect(input.maxLength).toEqual(0);
        });
      });
    });
  });

  describe('mainClasses', () => {
    it('returns carbon-textarea and additional decorated classes', () => {
      expect(baseInstance.mainClasses).toEqual('carbon-textarea common-input');
    });
  });

  describe('inputClasses', () => {
    it('returns carbon-textarea__input and additional decorated classes', () => {
      expect(baseInstance.inputClasses).toEqual('carbon-textarea__input common-input__input');
    });
  });

  describe('Passing a custom onChange', () => {
    it('triggers the custom function', () => {
      let input = TestUtils.findRenderedDOMComponentWithTag(baseInstance, 'textarea');
      TestUtils.Simulate.change(input);
      expect(spy).toHaveBeenCalled();
    });
  });

  describe('component tags', () => {
    let wrapper = shallow(
      <Textarea
        id='Dummy Area'
        value={ 'foo' }
        label={ 'Label' }
        cols={10}
        rows={10}
        onChange={ spy }
        characterLimit={ 100 }
        data-element='bar'
        data-role='baz'
      />
    );

    describe('on component', () => {
      it('includes correct component, element and role data tags', () => {
        rootTagTest(wrapper, 'textarea', 'bar', 'baz');
      });
    });

    describe("on internal elements", () => {
      it("adds element tags to it's children", () => {
        elementsTagTest(wrapper, ['character-limit']);
      });
    });
  });
});
<commit_msg>Remove the it block from the test<commit_after>import React from 'react';
import TestUtils from 'react-dom/test-utils';
import { shallow, mount } from 'enzyme';
import { elementsTagTest, rootTagTest } from '../../utils/helpers/tags/tags-specs';
import Textarea from './textarea';

describe('Textarea', () => {
  let baseWrapper, expandableWrapper, overLimitWrapper, notOverLimitWrapper,
      baseInstance, expandableInstance;
  let spy = jasmine.createSpy('spy');

  beforeEach(() => {
    baseWrapper = mount(
      <Textarea
        id='Dummy Area'
        value={ 'foo' }
        label={ 'Label' }
        cols={10}
        rows={10}
        onChange={ spy }
      />
    );
    baseInstance = baseWrapper.instance();

    expandableWrapper = mount(
      <Textarea
        value={ 'foo' }
        label={ 'Label' }
        expandable={ true }
        cols={10}
        rows={10}
        characterLimit='100'
        onChange={ spy }
      />
    );
    expandableInstance = expandableWrapper.instance();

    overLimitWrapper = shallow(
      <Textarea
        name="Dummy Area"
        value={ 'foofoofoofoo' }
        label={ 'Label' }
        warnOverLimit={ true }
        cols={10}
        rows={10}
        characterLimit='10'
        onChange={ spy }
      />
    );

    notOverLimitWrapper = shallow(
      <Textarea
        name="Dummy Area"
        value={ 'foofoofoo' }
        label={ 'Label' }
        warnOverLimit={ true }
        cols={10}
        rows={10}
        characterLimit='10'
        onChange={ spy }
    />);
  });

  describe('componentDidMount', () => {
    describe('when textarea can be expanded', () => {

      it('adds a event listener to the window', () => {
        spyOn(window, 'addEventListener');
        expandableInstance.componentDidMount();
        expect(window.addEventListener).toHaveBeenCalledWith(
          'resize', expandableInstance.expandTextarea
        );
      });

      it('sets the minHeight to the rendered client height', () => {
        expect(expandableInstance.minHeight).toEqual(
          expandableInstance._input.clientHeight
        );
      });

      it('calls expandTextarea', () => {
        spyOn(expandableInstance, 'expandTextarea');
        expandableInstance.componentDidMount();
        expect(expandableInstance.expandTextarea).toHaveBeenCalled();
      });
    });

    describe('when textarea cannot be expanded', () => {
      it('does not setup the textarea for expanding', () => {
        spyOn(window, 'addEventListener');
        spyOn(baseInstance, 'expandTextarea');
        baseInstance.componentDidMount();
        expect(window.addEventListener).not.toHaveBeenCalled();
        expect(baseInstance.expandTextarea).not.toHaveBeenCalled();
      });
    });
  });

  describe('componentWillUnmount', () => {
    beforeEach(() => {
      spyOn(window, 'removeEventListener');
    });

    describe('when textarea can be expanded', () => {
      let wrapper = mount(
        <Textarea
          value={ 'foo' }
          label={ 'Label' }
          expandable={ true }
          cols={10}
          rows={10}
          characterLimit='100'
          onChange={ spy }
        />
      );

      it('removes the event listener from the window', () => {
        wrapper.unmount();
        expect(window.removeEventListener).toHaveBeenCalledWith(
          'resize',jasmine.any(Function)
        );
      });
    });

    describe('when textarea cannot be expanded', () => {
      let wrapper = shallow(
        <Textarea
          id='Dummy Area'
          value={ 'foo' }
          label={ 'Label' }
          cols={10}
          rows={10}
          onChange={ spy }
        />
      );

      it('does not remove event listener from the window', () => {
        wrapper.unmount();
        expect(window.removeEventListener).not.toHaveBeenCalled();
      });
    });
  });

  describe('componentDidUpdate', () => {
    describe('when textarea can be expanded', () => {
      beforeEach(() => {
        spyOn(expandableInstance, 'expandTextarea');
      });
      it('should call to resize the textarea', () => {
        expandableInstance.valLength = 2000;
        expandableInstance.componentDidUpdate({});
        expect(expandableInstance.expandTextarea).toHaveBeenCalled();
      });
    });

    describe('when textarea cannot be expanded', () => {
      beforeEach(() => {
        spyOn(baseInstance, 'expandTextarea');
        baseInstance.valLength = 2000;
        baseInstance.componentDidUpdate({});
      });

      it('does not resize the textarea', () => {
        expect(baseInstance.expandTextarea).not.toHaveBeenCalled();
      });
    });
  });

  describe('expandTextarea', () => {
    describe('when scrollHeight is greater than the min height', () => {
      it('sets the textareas height to fit the content', () => {
        expandableInstance._input = {
          scrollHeight: 100,
          value: 'foo',
          style: { height: 0 }
        }
        expandableInstance.expandTextarea();
        expect(expandableInstance._input.style.height).toEqual('100px');
      });
    });

    describe('when the scrollHeight is less than the minHeight', () => {
      it('does not update the textarea', () => {
        expandableInstance._input = {
          scrollHeight: 5,
          value: 'foo',
          style: { height: 0 }
        }
        expandableInstance.minHeight = 20;
        expandableInstance.expandTextarea();
        expect(expandableInstance._input.style.height).toEqual(0);
      });
    });
  });

  describe('mainClasses', () => {
    it('returns carbon-textarea and additional decorated classes', () => {
      expect(baseWrapper.find('.carbon-textarea.common-input').exists()).toBeTruthy();
    });
  });

  describe('inputClasses', () => {
    it('returns carbon-textarea__input and additional decorated classes', () => {
      expect(baseWrapper.find('.carbon-textarea__input.common-input__input').exists()).toBeTruthy();
    });

    describe('if the textarea is expandable', () => {
      it('returns an additional disable-scroll class', () => {
        expect(expandableWrapper.find('.carbon-textarea__input.carbon-textarea__input--disable-scroll.common-input__input').exists()).toBeTruthy();
      });
    });
  });

  describe('textAreaClasses', () => {
    it('returns carbon-textarea__character-limit class', () => {
      expect(notOverLimitWrapper.find('.carbon-textarea__character-limit').exists()).toBeTruthy();
    });

    describe('overlimit', () => {
      describe('if the textarea char count is over limit', () => {
        it('returns an additional over-limit class', () => {
          expect(overLimitWrapper.find('.carbon-textarea__character-limit.over-limit').exists()).toBeTruthy();
        });
      });

      describe('if the textarea value is empty', () => {
        it('does not add a extra class', () => {
          overLimitWrapper.setProps({ value: '' });
          expect(overLimitWrapper.find('.carbon-textarea__character-limit.over-limit').exists()).toBeFalsy();
        });
      });

      describe('if the textarea value is under the limit', () => {
        it('does not add a extra class', () => {
          overLimitWrapper.setProps({ value: 'foo' });
          expect(overLimitWrapper.find('.carbon-textarea__character-limit.over-limit').exists()).toBeFalsy();
        });
      });
    });
  });

  describe('characterCount', () => {
    describe('when characterLimit is set', () => {
      it('returns character limit div', () => {
        let counter = TestUtils.findRenderedDOMComponentWithClass(expandableInstance, 'carbon-textarea__character-limit');
        expect(counter.textContent).toEqual('You have used 3 of 100 characters');
      });
    });

    describe('when characterLimit is not set', () => {
      it('returns null', () => {
        expect(baseInstance.characterCount).toBeNull();
      });
    });
  });

  describe('render', () => {
    it('renders a parent div', () => {
      let textareaNode = TestUtils.scryRenderedDOMComponentsWithTag(baseInstance, 'div')[0];
      expect(textareaNode.classList[0]).toEqual('carbon-textarea');
    });

    it('renders with a visible input with rows and columns', () => {
      let input = TestUtils.findRenderedDOMComponentWithTag(baseInstance, 'textarea')
      expect(input.rows).toBe(10);
      expect(input.cols).toBe(10);
    });

    it('is decorated with a label', () => {
      let label = TestUtils.findRenderedDOMComponentWithTag(baseInstance, 'label')
      expect(label.getAttribute('for')).toEqual('Dummy Area');
    });

    it('is decorated with a validation if a error is present', () => {
      baseInstance.setState({errorMessage: 'Error', valid: false});
      let errorDiv = TestUtils.findRenderedDOMComponentWithClass(baseInstance, 'common-input__message--error')
      expect(errorDiv.textContent).toEqual('Error')
    });

    describe('when characterLimit is set', () => {
      describe('and enforceCharacterLimit is true', () => {
        it('sets a maxLength on the input', () => {
          let input = TestUtils.findRenderedDOMComponentWithTag(expandableInstance, 'textarea')
          expect(input.maxLength).toEqual(100);
        });
      });

      describe('and enforceCharacterLimit is false', () => {
        it('does not set a maxLength on the input', () => {
          let instance = TestUtils.renderIntoDocument(
            <Textarea
              label={ 'Label' }
              characterLimit='100'
              enforceCharacterLimit={ false }
            />
          );
          let input = TestUtils.findRenderedDOMComponentWithTag(instance, 'textarea')
          // https://github.com/tmpvar/jsdom/issues/522
          // JSDom defaults to 0 instead of -1
          expect(input.maxLength).toEqual(0);
        });
      });
    });
  });

  describe('mainClasses', () => {
    it('returns carbon-textarea and additional decorated classes', () => {
      expect(baseInstance.mainClasses).toEqual('carbon-textarea common-input');
    });
  });

  describe('inputClasses', () => {
    it('returns carbon-textarea__input and additional decorated classes', () => {
      expect(baseInstance.inputClasses).toEqual('carbon-textarea__input common-input__input');
    });
  });

  describe('Passing a custom onChange', () => {
    it('triggers the custom function', () => {
      let input = TestUtils.findRenderedDOMComponentWithTag(baseInstance, 'textarea');
      TestUtils.Simulate.change(input);
      expect(spy).toHaveBeenCalled();
    });
  });

  describe('component tags', () => {
    let wrapper = shallow(
      <Textarea
        id='Dummy Area'
        value={ 'foo' }
        label={ 'Label' }
        cols={10}
        rows={10}
        onChange={ spy }
        characterLimit={ 100 }
        data-element='bar'
        data-role='baz'
      />
    );

    describe('on component', () => {
      it('includes correct component, element and role data tags', () => {
        rootTagTest(wrapper, 'textarea', 'bar', 'baz');
      });
    });

    describe("on internal elements", () => {
      elementsTagTest(wrapper, ['character-limit']);
    });
  });
});
<|endoftext|>


<commit_before>import Sequelize from 'sequelize';
import {DIALECTS} from './app/constants/constants';
import parse from './parse';
import {merge} from 'ramda';

const APP_NOT_CONNECTED_MESSAGE = 'There seems to be no connection at the moment.' +
    ' Please try connecting the application to your database.';

const PREBUILT_QUERY = {
    SHOW_DATABASES: 'SHOW_DATABASES',
    SHOW_TABLES: 'SHOW_TABLES',
    SHOW5ROWS: 'SHOW5ROWS'
};

const timestamp = () => (new Date()).toTimeString();

const EMPTY_TABLE = {
    columnnames: ['NA'],
    rows: [['empty table']],
    ncols: 1,
    nrows: 1
};

const isEmpty = (table) => {
    return table.length === 0;
};

const intoArray = (objects) => {
    return objects.map(obj => obj[Object.keys(obj)]);
};

function assembleTablesPreviewMessage(tablePreviews) {
    /*
        topRows is an array of one or many responses of top 5 rows queries
        [ {'table1':[top5rows]}, {'table2': [top5rows]} ...]
    */
    let parsedRows;
    return tablePreviews.map( (tablePreview) => {
        const tableName = Object.keys(tablePreview);
        const rawData = tablePreview[tableName];

        parsedRows = (isEmpty(rawData)) ? EMPTY_TABLE : parse(rawData);

        return {[tableName]: parsedRows};
    });
}

export default class SequelizeManager {
    constructor(log) {
        this.log = log;
    }

    getDialect() {
        return this.connection.options.dialect;
    }

    setQueryType(type) {
        // set sequelize's query property type
        // helps sequelize to predict what kind of response it will get
        return {type: this.connection.QueryTypes[type]};
    }

    intoTablesArray(results) {
        // helper function to
        let tables;
        if (this.getDialect() === DIALECTS.SQLITE) {
            // sqlite returns an array by default
            tables = results;
        } else {
            // others return list of objects
            tables = intoArray(results);
        }
        return tables;
    }

    login({username, password, database, port, dialect, storage, host}) {
        this.connection = new Sequelize(database, username, password, {
            dialect,
            host,
            port,
            storage
        });

        if (this.connection.config.dialect === 'mssql') {
            this.connection.config.dialectOptions = {encrypt: true};
        }

        return this.connection.authenticate();
    }

    check_connection(callback) {
        // when already logged in and simply want to check connection
        if (!this.connection) {
			this.raiseError(
                merge(
                    {message: APP_NOT_CONNECTED_MESSAGE},
                    {type: 'connection'}),
                callback
			);
		} else {
            return this.connection.authenticate();
        }
    }

    raiseError(errorMessage, callback) {
        const errorLog = merge(errorMessage, {timestamp: timestamp()});
        callback({error: errorLog});
    }

    showDatabases(callback) {
        const query = this.getPresetQuery(PREBUILT_QUERY.SHOW_DATABASES);
        const dialect = this.getDialect();

        // deal with sqlite -> has no databases list
        if (dialect === DIALECTS.SQLITE) {
            callback({
                databases: ['SQLITE database accessed'],
                error: null,
                tables: null
            });
            // skip SHOW_DATABASES query and send SHOW_TABLES query right away
            return this.showTables(callback);
        }

        return () => this.connection.query(query, this.setQueryType('SELECT'))
        .then(results => {
            callback({
                databases: intoArray(results),
                error: null,
                /*
                    if user wants to see all databases/schemes, clear
                    tables from previously selected database/schemes
                */
                tables: null
            });
        });
    }

    // built-in query to show available tables in a database/scheme
    showTables(callback) {
        const showtables = this.getPresetQuery(PREBUILT_QUERY.SHOW_TABLES);

        return () => this.connection
        .query(showtables, this.setQueryType('SELECT'))
        .then(results => {
            const tables = this.intoTablesArray(results);

            // construct prmises of table previews (top 5 rows)
            const promises = tables.map(table => {
                const show5rows = this.getPresetQuery(
                    PREBUILT_QUERY.SHOW5ROWS, table
                );
                // sends the query for a single table
                return this.connection
                .query(show5rows, this.setQueryType('SELECT'))
                .then(selectTableResults => {
                    return {
                        [table]: selectTableResults
                    };
                });
            });

            return Promise.all(promises)
            .then(tablePreviews => {
                callback({
                    error: null,
                    tables: assembleTablesPreviewMessage(tablePreviews)
                });
            });
        });
    }

    sendQuery(query, callback) {
        return this.connection.query(query, this.setQueryType('SELECT'))
        .then((results) => {
            callback(merge(parse(results), {error: null}));
        });
    }

    disconnect(callback) {
        /*
            this.connection.close() does not return a promise for now.
            open issue here:
            https://github.com/sequelize/sequelize/pull/5776
        */

        this.connection.close();
        callback({databases: null, error: null, tables: null});
    }

    getPresetQuery(showQuerySelector, table = null) {
        const dialect = this.getDialect();
        switch (showQuerySelector) {
            case PREBUILT_QUERY.SHOW_DATABASES:
                switch (dialect) {
                    case DIALECTS.MYSQL:
                    case DIALECTS.SQLITE:
                    case DIALECTS.MARIADB:
                        return 'SHOW DATABASES';
                    case DIALECTS.POSTGRES:
                        return 'SELECT datname AS database FROM ' +
                        'pg_database WHERE datistemplate = false;';
                    case DIALECTS.MSSQL:
                        return 'SELECT name FROM Sys.Databases';
                    default:
                        throw new Error('could not build a presetQuery');
                }

            case PREBUILT_QUERY.SHOW_TABLES:
                switch (dialect) {
                    case DIALECTS.MYSQL:
                    case DIALECTS.MARIADB:
                        return 'SHOW TABLES';
                    case DIALECTS.POSTGRES:
                        return 'SELECT table_name FROM ' +
                            'information_schema.tables WHERE ' +
                            'table_schema = \'public\'';
                    case DIALECTS.MSSQL:
                        return 'SELECT TABLE_NAME FROM ' +
                            'information_schema.tables';
                    case DIALECTS.SQLITE:
                        return 'SELECT name FROM ' +
                        'sqlite_master WHERE type="table"';
                    default:
                        throw new Error('could not build a presetQuery');
                }

            case PREBUILT_QUERY.SHOW5ROWS:
                switch (dialect) {
                    case DIALECTS.MYSQL:
                    case DIALECTS.SQLITE:
                    case DIALECTS.MARIADB:
                    case DIALECTS.POSTGRES:
                        return `SELECT * FROM ${table} LIMIT 5`;
                    case DIALECTS.MSSQL:
                        return 'SELECT TOP 5 * FROM ' +
                            `${this.connection.config.database}.dbo.${table}`;
                    default:
                        throw new Error('could not build a presetQuery');
                }

            default: {
                throw new Error('could not build a presetQuery');
            }
        }
    }
}
<commit_msg>:wrench: implement configpath<commit_after>import Sequelize from 'sequelize';
import {DIALECTS} from './app/constants/constants';
import parse from './parse';
import {merge} from 'ramda';
import {ARGS} from './args';

export const OPTIONS = ARGS;
const CONFIG = require(ARGS.configpath);
console.log(CONFIG);

const APP_NOT_CONNECTED_MESSAGE = 'There seems to be no connection at the moment.' +
    ' Please try connecting the application to your database.';

const PREBUILT_QUERY = {
    SHOW_DATABASES: 'SHOW_DATABASES',
    SHOW_TABLES: 'SHOW_TABLES',
    SHOW5ROWS: 'SHOW5ROWS'
};

const timestamp = () => (new Date()).toTimeString();

const EMPTY_TABLE = {
    columnnames: ['NA'],
    rows: [['empty table']],
    ncols: 1,
    nrows: 1
};

const isEmpty = (table) => {
    return table.length === 0;
};

const intoArray = (objects) => {
    return objects.map(obj => obj[Object.keys(obj)]);
};

function assembleTablesPreviewMessage(tablePreviews) {
    /*
        topRows is an array of one or many responses of top 5 rows queries
        [ {'table1':[top5rows]}, {'table2': [top5rows]} ...]
    */
    let parsedRows;
    return tablePreviews.map( (tablePreview) => {
        const tableName = Object.keys(tablePreview);
        const rawData = tablePreview[tableName];

        parsedRows = (isEmpty(rawData)) ? EMPTY_TABLE : parse(rawData);

        return {[tableName]: parsedRows};
    });
}

export class SequelizeManager {
    constructor(log) {
        this.log = log;
    }

    getDialect() {
        return this.connection.options.dialect;
    }

    setQueryType(type) {
        // set sequelize's query property type
        // helps sequelize to predict what kind of response it will get
        return {type: this.connection.QueryTypes[type]};
    }

    intoTablesArray(results) {
        // helper function to
        let tables;
        if (this.getDialect() === DIALECTS.SQLITE) {
            // sqlite returns an array by default
            tables = results;
        } else {
            // others return list of objects
            tables = intoArray(results);
        }
        return tables;
    }

    login({username, password, database, port, dialect, storage, host}) {
        if (OPTIONS.headless) {
            const {username, password, database,
            port, dialect, storage, host} = CONFIG;
        }
        this.connection = new Sequelize(database, username, password, {
            dialect,
            host,
            port,
            storage
        });

        if (this.connection.config.dialect === 'mssql') {
            this.connection.config.dialectOptions = {encrypt: true};
        }

        return this.connection.authenticate();
    }

    check_connection(callback) {
        // when already logged in and simply want to check connection
        if (!this.connection) {
			this.raiseError(
                merge(
                    {message: APP_NOT_CONNECTED_MESSAGE},
                    {type: 'connection'}),
                callback
			);
		} else {
            return this.connection.authenticate();
        }
    }

    raiseError(errorMessage, callback) {
        const errorLog = merge(errorMessage, {timestamp: timestamp()});
        callback({error: errorLog});
    }

    showDatabases(callback) {
        const query = this.getPresetQuery(PREBUILT_QUERY.SHOW_DATABASES);
        const dialect = this.getDialect();

        // deal with sqlite -> has no databases list
        if (dialect === DIALECTS.SQLITE) {
            callback({
                databases: ['SQLITE database accessed'],
                error: null,
                tables: null
            });
            // skip SHOW_DATABASES query and send SHOW_TABLES query right away
            return this.showTables(callback);
        }

        return () => this.connection.query(query, this.setQueryType('SELECT'))
        .then(results => {
            callback({
                databases: intoArray(results),
                error: null,
                /*
                    if user wants to see all databases/schemes, clear
                    tables from previously selected database/schemes
                */
                tables: null
            });
        });
    }

    // built-in query to show available tables in a database/scheme
    showTables(callback) {
        const showtables = this.getPresetQuery(PREBUILT_QUERY.SHOW_TABLES);

        return () => this.connection
        .query(showtables, this.setQueryType('SELECT'))
        .then(results => {
            const tables = this.intoTablesArray(results);

            // construct prmises of table previews (top 5 rows)
            const promises = tables.map(table => {
                const show5rows = this.getPresetQuery(
                    PREBUILT_QUERY.SHOW5ROWS, table
                );
                // sends the query for a single table
                return this.connection
                .query(show5rows, this.setQueryType('SELECT'))
                .then(selectTableResults => {
                    return {
                        [table]: selectTableResults
                    };
                });
            });

            return Promise.all(promises)
            .then(tablePreviews => {
                callback({
                    error: null,
                    tables: assembleTablesPreviewMessage(tablePreviews)
                });
            });
        });
    }

    sendQuery(query, callback) {
        return this.connection.query(query, this.setQueryType('SELECT'))
        .then((results) => {
            callback(merge(parse(results), {error: null}));
        });
    }

    disconnect(callback) {
        /*
            this.connection.close() does not return a promise for now.
            open issue here:
            https://github.com/sequelize/sequelize/pull/5776
        */

        this.connection.close();
        callback({databases: null, error: null, tables: null});
    }

    getPresetQuery(showQuerySelector, table = null) {
        const dialect = this.getDialect();
        switch (showQuerySelector) {
            case PREBUILT_QUERY.SHOW_DATABASES:
                switch (dialect) {
                    case DIALECTS.MYSQL:
                    case DIALECTS.SQLITE:
                    case DIALECTS.MARIADB:
                        return 'SHOW DATABASES';
                    case DIALECTS.POSTGRES:
                        return 'SELECT datname AS database FROM ' +
                        'pg_database WHERE datistemplate = false;';
                    case DIALECTS.MSSQL:
                        return 'SELECT name FROM Sys.Databases';
                    default:
                        throw new Error('could not build a presetQuery');
                }

            case PREBUILT_QUERY.SHOW_TABLES:
                switch (dialect) {
                    case DIALECTS.MYSQL:
                    case DIALECTS.MARIADB:
                        return 'SHOW TABLES';
                    case DIALECTS.POSTGRES:
                        return 'SELECT table_name FROM ' +
                            'information_schema.tables WHERE ' +
                            'table_schema = \'public\'';
                    case DIALECTS.MSSQL:
                        return 'SELECT TABLE_NAME FROM ' +
                            'information_schema.tables';
                    case DIALECTS.SQLITE:
                        return 'SELECT name FROM ' +
                        'sqlite_master WHERE type="table"';
                    default:
                        throw new Error('could not build a presetQuery');
                }

            case PREBUILT_QUERY.SHOW5ROWS:
                switch (dialect) {
                    case DIALECTS.MYSQL:
                    case DIALECTS.SQLITE:
                    case DIALECTS.MARIADB:
                    case DIALECTS.POSTGRES:
                        return `SELECT * FROM ${table} LIMIT 5`;
                    case DIALECTS.MSSQL:
                        return 'SELECT TOP 5 * FROM ' +
                            `${this.connection.config.database}.dbo.${table}`;
                    default:
                        throw new Error('could not build a presetQuery');
                }

            default: {
                throw new Error('could not build a presetQuery');
            }
        }
    }
}
<|endoftext|>


<commit_before>import tape from "tape"

import configurator from ".."

tape("statinamic/lib/configurator", (test) => {

  const pkg = {
    homepage: "https://localhost:8080/statinamic",
  }
  const config = configurator(pkg)
  test.equal(
    typeof config.baseUrl,
    "object",
    "should return an 'baseUrl' object in the config"
  )
  test.equal(
    config.baseUrl.hostname,
    "localhost",
    "should contain 'hostname' in 'baseUrl'"
  )
  test.equal(
    config.baseUrl.port,
    "8080",
    "should contain 'port' in 'baseUrl'"
  )
  test.equal(
    config.baseUrl.pathname,
    "/statinamic",
    "should contain 'pathname' in 'baseUrl'"
  )

  test.equal(
    typeof config.consts,
    "object",
    "should return an 'consts' object in the config"
  )

  test.end()
})
<commit_msg>Fixed: configurator tests<commit_after>import tape from "tape"

import configurator from ".."

tape("statinamic/lib/configurator", (test) => {

  const pkg = {
    homepage: "https://localhost:8080/statinamic",
  }
  const config = configurator(pkg, [ "--production" ])
  test.equal(
    typeof config.baseUrl,
    "object",
    "should return an 'baseUrl' object in the config"
  )
  test.equal(
    config.baseUrl.hostname,
    "localhost",
    "should contain 'hostname' in 'baseUrl'"
  )
  test.equal(
    config.baseUrl.port,
    "8080",
    "should contain 'port' in 'baseUrl'"
  )
  test.equal(
    config.baseUrl.pathname,
    "/statinamic/",
    "should contain 'pathname' in 'baseUrl'"
  )

  test.equal(
    typeof config.consts,
    "object",
    "should return an 'consts' object in the config"
  )

  test.end()
})
<|endoftext|>


<commit_before>var things = null;

function Movable(id, x, y) {
  this.currentX = x;
  this.currentY = y;
  this.id = id;

  this.htmlObj = document.getElementById(id);
  this.htmlObj.style.left = (this.currentX + "px");
  this.htmlObj.style.top = (this.currentY + "px");
//  console.log('Movable() id=' + id + '  currentX = ' + this.currentX + "px    currentX =" + this.currentY + "px");
}

Movable.prototype.move = function(x, y)
{
  destX = destX + x;
  destY = destY + y;
}

Movable.prototype.MoveUp = function(x, y)
{
  move(this.destX, this.destY - 10);
}

Movable.prototype.MoveDown = function(x, y)
{
  move(this.destX, this.destY + 10);
}

Movable.prototype.MoveLeft = function(x, y)
{
  move(this.destX - 10, this.destY);
}

Movable.prototype.MoveRight = function(x, y)
{
  move(this.destX + 10, this.destY);
}

Movable.prototype.InitialScale = function()
{
  console.log('in InitialScale()');
  console.log('In InitialScale().   this.htmlObj.style.width=' + this.htmlObj.style.width + '   id=' /*+ this.id*/);
  console.log('In InitialScale().   DAD id=' + dad.id);
  console.log('In InitialScale().   this.htmlObj.style id=' + this.htmlObj.id);

//  this.htmlObj = document.getElementById(id);
//  this.htmlObj.style.width = (this.currentX + "px");
}

function ScaleObjects()
{
  console.log('In GameInitilize2().   things.length=' + things.length);
  console.log('In GameInitilize2().   things.[length].id=' + things[0].id);
  console.log('in ScaleObjects()');
  for (var thisThing in things)  {  thisThing.InitialScale();  }
  console.log('Done ScaleObjects()');
}

function GameInitilize2(e)
{
//  console.log('in GameInitialize2()');
  dad = new Movable("Dad", 3, 5);
  mom = new Movable("Mom", 5, 59);
  jordan = new Movable("Jordan", 40, 20);
  house = new Movable("House", 60, 5);
  candyhouse = new Movable("CandyHouse", 60, 75);
//  console.log('Finished GameInitialize2()');

  things = new Array(dad, mom, jordan, house, candyhouse);

  dad.InitialScale();
//  console.log('GameInitilize2: id=' + things[0].id);
  ScaleObjects();
}

function GameInitilize(e)
{
//  console.log('In GameInitialize()');
//  window.document.onload = GameInitilize2;
  $(document).ready(GameInitilize2);
}

// console.log('Running Game.js global code.');
GameInitilize();

<commit_msg>Update Game.js<commit_after>var things = null;

function Movable(id, x, y) {
  this.currentX = x;
  this.currentY = y;
  this.id = id;

  this.htmlObj = document.getElementById(id);
  this.htmlObj.style.left = (this.currentX + "px");
  this.htmlObj.style.top = (this.currentY + "px");
//  console.log('Movable() id=' + id + '  currentX = ' + this.currentX + "px    currentX =" + this.currentY + "px");
}

Movable.prototype.move = function(x, y)
{
  destX = destX + x;
  destY = destY + y;
}

Movable.prototype.MoveUp = function(x, y)
{
  move(this.destX, this.destY - 10);
}

Movable.prototype.MoveDown = function(x, y)
{
  move(this.destX, this.destY + 10);
}

Movable.prototype.MoveLeft = function(x, y)
{
  move(this.destX - 10, this.destY);
}

Movable.prototype.MoveRight = function(x, y)
{
  move(this.destX + 10, this.destY);
}

Movable.prototype.InitialScale = function()
{
  console.log('in InitialScale()');
  console.log('In InitialScale().   this.htmlObj.style.width=' + this.htmlObj.style.width + '   id=' /*+ this.id*/);
  console.log('In InitialScale().   DAD id=' + dad.id);
  console.log('In InitialScale().   this.htmlObj.style id=' + this.htmlObj.id);

//  this.htmlObj = document.getElementById(id);
//  this.htmlObj.style.width = (this.currentX + "px");
}

function ScaleObjects()
{
  console.log('In ScaleObjects().   things.length=' + things.length);
  console.log('In ScaleObjects().   things.[length].id=' + things[0].id);
  console.log('in ScaleObjects()');
  for (var thisThing in things)  {
      console.log('In ScaleObjects().   thisThing.id=' + thisThing.id);
    thisThing.InitialScale();  }
  console.log('Done ScaleObjects()');
}

function GameInitilize2(e)
{
//  console.log('in GameInitialize2()');
  dad = new Movable("Dad", 3, 5);
  mom = new Movable("Mom", 5, 59);
  jordan = new Movable("Jordan", 40, 20);
  house = new Movable("House", 60, 5);
  candyhouse = new Movable("CandyHouse", 60, 75);
//  console.log('Finished GameInitialize2()');

  things = new Array(dad, mom, jordan, house, candyhouse);

  dad.InitialScale();
//  console.log('GameInitilize2: id=' + things[0].id);
  ScaleObjects();
}

function GameInitilize(e)
{
//  console.log('In GameInitialize()');
//  window.document.onload = GameInitilize2;
  $(document).ready(GameInitilize2);
}

// console.log('Running Game.js global code.');
GameInitilize();

<|endoftext|>


<commit_before>import { connect } from 'react-redux';
import IceboxList from '../components/iceboxList';
import { SORT_EXPIRATION, SORT_FOODGROUP, SORT_FOODNAME, ASCENDING, DESCENDING } from '../constants/sorts';
import _sortBy from 'lodash/sortBy';

const orderIceboxItems = (items, sortBy, sortOrder) => {
	let sorted;
	switch (sortBy) {
		case SORT_EXPIRATION:
			if(sortOrder === ASCENDING){
				sorted = _sortBy(items, (item) => item.expiration);
				return sorted;
			} else {
				sorted = _sortBy(items, (item) => item.expiration);

				return sorted.reverse();
			}
		case SORT_FOODGROUP:
			if(sortOrder === ASCENDING){
				sorted = _sortBy(items, (item) => item.foodGroup);
				return sorted;
			} else {
				sorted = _sortBy(items, (item) => item.foodGroup);
				return sorted.reverse();
			}
		case SORT_FOODNAME:
			if(sortOrder === ASCENDING){
				sorted = _sortBy(items, (item) => item.name);
				return sorted;
			} else {
				sorted = _sortBy(items, (item) => item.name);
				return sorted.reverse();
			}

	}
}

function mapStateToProps(state) {
	return { contents: orderIceboxItems(state.icebox, state.sortBy, state.sortOrder) };
}

const VisibleIceboxList = connect(mapStateToProps)(IceboxList);

export default VisibleIceboxList;<commit_msg>[pull] creates search functionality in visibleIceboxList HOC<commit_after>import { connect } from 'react-redux';
import IceboxList from '../components/iceboxList';
import { SORT_EXPIRATION, SORT_FOODGROUP, SORT_FOODNAME, ASCENDING, DESCENDING } from '../constants/sorts';
// import _chain from 'lodash/chain';
// import _sortBy from 'lodash/sortBy';
import _ from 'lodash'

const orderIceboxItems = (items, sortBy, sortOrder, searchTerm) => {
	let sorted;
	switch (sortBy) {
		case SORT_EXPIRATION:
			return itemSorter(items, "expiration", sortOrder, searchTerm);
		case SORT_FOODGROUP:
			return itemSorter(items, "foodGroup", sortOrder, searchTerm);
		case SORT_FOODNAME:
			return itemSorter(items, "name", sortOrder, searchTerm);
	}
}

const itemSorter = (array, sortBy, sortOrder, searchTerm) => {
	if(sortOrder === ASCENDING){
		return _.chain(array)
			.sortBy((item) => item[sortBy])
			.filter((item) => {
				return !searchTerm ? true : (!!~item.name.toLowerCase().indexOf(searchTerm.toLowerCase()) || !!~item.foodGroup.toLowerCase().indexOf(searchTerm.toLowerCase())) ? true : false;
			})
			.value()
	} else {
		return _.chain(array)
			.sortBy((item) => item[sortBy])
			.filter((item) => {
				return !searchTerm ? true : (!!~item.name.toLowerCase().indexOf(searchTerm.toLowerCase()) || !!~item.foodGroup.toLowerCase().indexOf(searchTerm.toLowerCase())) ? true : false;
			})
			.reverse()
			.value()
	}
}

function mapStateToProps(state) {
	return { contents: orderIceboxItems(state.icebox, state.sortBy, state.sortOrder, state.iceboxSearch) };
}

const VisibleIceboxList = connect(mapStateToProps)(IceboxList);

export default VisibleIceboxList;<|endoftext|>


<commit_before>module.exports=`<pb n="660"/>

一、說一切有部的修行位次
<svg src="M023.p660-1.svg">
修行位次 賢 五 停 心
三　賢（外凡） 七加行
別相念住 總相念住 煖
四善根（內凡）頂 忍
世第一法 聖
預　流 向
見道
有學 果
修道 一　來
向 果 不　還
向 果 阿羅漢 向 果
無學道 無學
</svg>

二、八忍八智（見道位十五心及修道位第十六心）
<svg src="M023.p660-2.svg">
上下八諦
欲界
苦諦
苦法智忍－無間道－第 一 心
苦 法 智－解脫道－第 二 心
苦諦
苦類智忍－無間道－第 三 心
苦 類 智－解脫道－第 四 心
集諦
集法智忍－無間道－第 五 心
集 法 智－解脫道－第 六 心
集諦
集類智忍－無間道－第 七 心
集 類 智－解脫道－第 八 心
見道
上界
滅諦
滅法智忍－無間道－第 九 心
滅 法 智－解脫道－第 十 心
滅諦
滅類智忍－無間道－第十一心
滅 類 智－解脫道－第十二心
道諦
道法智忍－無間道－第十三心
道 法 智－解脫道－第十四心
道諦
道類智忍－無間道－第十五心
道 類 智－解脫道－第十六心
修道
</svg>

三、四諦十六行相

（一）苦諦：無常、苦、空、無我。

（二）集諦：集、因、生、緣。

（三）滅諦：滅、靜、妙、離。

（四）道諦：道、如、行、出。
</file>`;<commit_msg>remove extra <file><commit_after>module.exports=`<pb n="660"/>

一、說一切有部的修行位次
<svg src="M023.p660-1.svg">
修行位次 賢 五 停 心
三　賢（外凡） 七加行
別相念住 總相念住 煖
四善根（內凡）頂 忍
世第一法 聖
預　流 向
見道
有學 果
修道 一　來
向 果 不　還
向 果 阿羅漢 向 果
無學道 無學
</svg>

二、八忍八智（見道位十五心及修道位第十六心）
<svg src="M023.p660-2.svg">
上下八諦
欲界
苦諦
苦法智忍－無間道－第 一 心
苦 法 智－解脫道－第 二 心
苦諦
苦類智忍－無間道－第 三 心
苦 類 智－解脫道－第 四 心
集諦
集法智忍－無間道－第 五 心
集 法 智－解脫道－第 六 心
集諦
集類智忍－無間道－第 七 心
集 類 智－解脫道－第 八 心
見道
上界
滅諦
滅法智忍－無間道－第 九 心
滅 法 智－解脫道－第 十 心
滅諦
滅類智忍－無間道－第十一心
滅 類 智－解脫道－第十二心
道諦
道法智忍－無間道－第十三心
道 法 智－解脫道－第十四心
道諦
道類智忍－無間道－第十五心
道 類 智－解脫道－第十六心
修道
</svg>

三、四諦十六行相

（一）苦諦：無常、苦、空、無我。

（二）集諦：集、因、生、緣。

（三）滅諦：滅、靜、妙、離。

（四）道諦：道、如、行、出。
`;<|endoftext|>