<commit_before>require('./connect')
require('./multiple')
require('./data-size')
require('./references')
require('./subscription')
require('./switch')
require('./client')
require('./types')
require('./context')

// missing auto remove of context
setTimeout(() => {
  console.log('force a wait.. or something?')
}, 15e3)<commit_msg>try more<commit_after>require('./connect')
// require('./multiple')
// require('./data-size')
// require('./references')
// require('./subscription')
// require('./switch')
// require('./client')
// require('./types')
// require('./context')

// missing auto remove of context
setTimeout(() => {
  console.log('force a wait.. or something?')
}, 15e3)<|endoftext|>


<commit_before>import _ from 'lodash';
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { ListView, View } from 'react-native';
import CountryItem from './CountryItem';
import HeaderEmbeddedSearchBar from './HeaderEmbeddedSearchBar';
import { Spinner } from './common';
import {
    countriesFetch,
    updateCountriesFilter,
    changeHomeCountry,
    fetchIconUri
} from '../actions';

class CountryList extends Component {

    componentWillMount() {
        this.props.countriesFetch();
        this.createDataSource(this.props);
    }

    componentWillReceiveProps(nextProps) {
        this.createDataSource(nextProps);
        this.setHomeCountry(nextProps);
    }

    onSearchChangeText(text) {
        this.props.updateCountriesFilter(text);
    }

    setHomeCountry(nextProps) {
        const { countries, homeCountry } = nextProps;
        if (isEmpty(homeCountry)) {
            const us = countries.find(c => c.name === 'United States of America');
            this.props.changeHomeCountry(us);
        }
    }

    createDataSource({ countries }) {
        const ds = new ListView.DataSource({
            rowHasChanged: (r1, r2) => r1 !== r2
        });
        this.dataSource = ds.cloneWithRows(countries);
    }

    renderRow(country) {
        if (country.uid === this.props.homeCountry.uid) {
            return <CountryItem country={country} selected />;
        }
        return <CountryItem country={country} />;
    }

    render() {
        if (this.props.isLoading) {
            return <Spinner size="large" />;
        }
        return (
            <View style={{ flex: 1 }}>
                <HeaderEmbeddedSearchBar
                    headerText='Talk2Go'
                    onSearchChangeText={this.onSearchChangeText.bind(this)}
                    onRightIconPress={() => console.log('settings pressed')}
                    textColor='white'
                    backgroundColor='#1f94d0'
                />
                <ListView
                    enableEmptySections
                    dataSource={this.dataSource}
                    renderRow={this.renderRow.bind(this)}
                />
            </View>
        );
    }
}

const mapStateToProps = (state) => {
    const { filter, isLoading } = state.countries;
    const countries = _.map(state.countries.data, (val, uid) => {
        return { ...val, uid };
    });

    if (filter) {
        return {
            countries: countries.filter(c => c.name.startsWith(filter)),
            homeCountry: state.homeCountry
        };
    }
    return { countries, isLoading, homeCountry: state.homeCountry };
};

const isEmpty = (obj) => {
    return !Object.keys(obj).length;
};

export default connect(mapStateToProps, {
    countriesFetch,
    updateCountriesFilter,
    changeHomeCountry,
    fetchIconUri
})(CountryList);
<commit_msg>talk2go: adding from sub header<commit_after>import _ from 'lodash';
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { ListView, View, Text } from 'react-native';
import CountryItem from './CountryItem';
import HeaderEmbeddedSearchBar from './HeaderEmbeddedSearchBar';
import { Spinner } from './common';
import {
    countriesFetch,
    updateCountriesFilter,
    changeHomeCountry,
    fetchIconUri
} from '../actions';

class CountryList extends Component {

    componentWillMount() {
        this.props.countriesFetch();
        this.createDataSource(this.props);
    }

    componentWillReceiveProps(nextProps) {
        this.createDataSource(nextProps);
        this.setHomeCountry(nextProps);
    }

    onSearchChangeText(text) {
        this.props.updateCountriesFilter(text);
    }

    setHomeCountry(nextProps) {
        const { countries, homeCountry } = nextProps;
        if (isEmpty(homeCountry)) {
            const us = countries.find(c => c.name === 'United States of America');
            this.props.changeHomeCountry(us);
        }
    }

    createDataSource({ countries }) {
        const ds = new ListView.DataSource({
            rowHasChanged: (r1, r2) => r1 !== r2
        });
        this.dataSource = ds.cloneWithRows(countries);
    }

    renderRow(country) {
        if (country.uid === this.props.homeCountry.uid) {
            return <CountryItem country={country} selected />;
        }
        return <CountryItem country={country} />;
    }

    render() {
        if (this.props.isLoading) {
            return <Spinner size="large" />;
        }
        return (
            <View style={{ flex: 1 }}>
                <HeaderEmbeddedSearchBar
                    headerText='Talk2Go'
                    onSearchChangeText={this.onSearchChangeText.bind(this)}
                    onRightIconPress={() => console.log('settings pressed')}
                    textColor='white'
                    backgroundColor='#1f94d0'
                />
                <View style={styles.fromViewStyle}>
                    <Text style={styles.fromTextStyle}>
                        I'm from {this.props.homeCountry.name}
                    </Text>
                </View>
                <ListView
                    enableEmptySections
                    dataSource={this.dataSource}
                    renderRow={this.renderRow.bind(this)}
                />
            </View>
        );
    }
}

const mapStateToProps = (state) => {
    const { filter, isLoading } = state.countries;
    const countries = _.map(state.countries.data, (val, uid) => {
        return { ...val, uid };
    });

    if (filter) {
        return {
            countries: countries.filter(c => c.name.startsWith(filter)),
            homeCountry: state.homeCountry
        };
    }
    return { countries, isLoading, homeCountry: state.homeCountry };
};

const isEmpty = (obj) => {
    return !Object.keys(obj).length;
};

const styles = {
	fromViewStyle: {
		backgroundColor: '#F8F8F8',
		justifyContent: 'center',
		alignItems: 'flex-start',
		height: 30,
        paddingLeft: 5,
		shadowColor: '#000',
		shadowOffset: { width: 0, height: 2 },
		shadowOpacity: 0.2,
		elevation: 2,
		position: 'relative'
	},
	fromTextStyle: {
        fontSize: 14,
        color: '#1f94d0',
        fontWeight: '500'
	}
};

export default connect(mapStateToProps, {
    countriesFetch,
    updateCountriesFilter,
    changeHomeCountry,
    fetchIconUri
})(CountryList);
<|endoftext|>


<commit_before>/* jshint expr: true, unused: false */
/* global describe, it, before, after, beforeEach, afterEach */

var async      = require('async')
  , mongoose   = require('mongoose')
  , cachegoose = require('../')
  , should     = require('should')
  , mongoose   = require('mongoose')
  , Schema     = mongoose.Schema
  , RecordSchema
  , Record
  , cache
  , db
  ;

describe('cachegoose', function() {
  before(function(done) {
    cachegoose(mongoose, {
      engine: 'redis',
      port: 6379,
      host: 'localhost'
    });

    cache = cachegoose._cache;

    mongoose.connect('mongodb://127.0.0.1/mongoose-cachegoose-testing');
    db = mongoose.connection;

    db.on('error', done);
    db.on('open', done);

    RecordSchema = new Schema({
      num: Number,
      date: {
        type: Date,
        default: Date.now
      }
    });

    Record = mongoose.model('Record', RecordSchema);
  });

  beforeEach(function(done) {
    generate(10, done);
  });

  afterEach(function(done) {
    Record.remove(function() {
      cache.clear(done);
    });
  });

  it('should have cache method after initialization', function () {
    Record.find({}).cache.should.be.a.Function;
  });

  it('should cache a simple query that uses callbacks', function(done) {
    getAll(60e3, function(err, res) {
      res.length.should.equal(10);
      Boolean(res._fromCache).should.be.false;

      getAll(60e3, function(err, res) {
        res.length.should.equal(10);
        Boolean(res._fromCache).should.be.true;
        done();
      });
    });
  });

  it('should cache a simple query that uses promises', function(done) {
    getAll(60e3).then(function(res) {
      res.length.should.equal(10);
      Boolean(res._fromCache).should.be.false;

      getAll(60e3).then(function(res) {
        res.length.should.equal(10);
        Boolean(res._fromCache).should.be.true;
        done();
      });
    });
  });

  it('should return a Mongoose model from cached and non-cached results', function(done) {
    getAll(60e3, function(err, res) {
      var first = res[0];

      getAll(60e3, function(err2, res2) {
        var cachedFirst = res2[0];
        first.constructor.name.should.equal('model');
        cachedFirst.constructor.name.should.equal('model');

        res[0].isNew.should.be.false;
        res2[0].isNew.should.be.false;

        done();
      });
    });
  });

  it('should return lean models from cached and non-cached results', function(done) {
    getAllLean(10e3, function(err, res) {
      res.length.should.equal(10);
      Boolean(res._fromCache).should.be.false;

      getAllLean(10e3, function(err, res2) {
        res2.length.should.equal(10);
        Boolean(res2._fromCache).should.be.true;
        res[0].constructor.name.should.not.equal('model');
        res2[0].constructor.name.should.not.equal('model');
        done();
      });
    });
  });

  it('should distinguish between lean and non lean for the same conditions', function(done) {
    getAll(10e3, function(err, res) {
      getAll(10e3, function(err, res2) {
        res2.length.should.equal(10);
        Boolean(res2._fromCache).should.be.true;
        res2[0].constructor.name.should.equal('model');

        getAllLean(function(err, res3) {
          Boolean(res3._fromCache).should.be.false;
          res3[0].constructor.name.should.not.equal('model');
          done();
        });
      });
    });
  });

  it('should cache a query rerun many times', function(done) {
    getAll(60e3).then(function(res) {
      res.length.should.equal(10);
      Boolean(res._fromCache).should.be.false;

      async.series(
        new Array(20).join('.').split('').map(function() {
          return function(done) {
            getAll(60e3, done);
          };
        })
      , function() {
        getAll(60e3, function(err, res) {
          res.length.should.equal(10);
          Boolean(res._fromCache).should.be.true;
          done();
        });
      });
    });
  });

  it('should expire the cache', function(done) {
    getAll(1, function() {
      setTimeout(function() {
        getAll(1, function(err, res) {
          Boolean(res._fromCache).should.be.false;
          done();
        });
      }, 1200);
    });
  });
});

function getAll(ttl, cb) {
  return Record.find({}).cache(ttl).exec(cb);
}

function getAllLean(ttl, cb) {
  return Record.find({}).lean().cache(ttl).exec(cb);
}

function generate (amount, cb) {
  var records = [];
  var count = 0;
  while (count < amount) {
    records.push({
      num: count
    });
    count++;
  }

  Record.create(records, cb);
}

<commit_msg>Verify equivalent query with no ttl is not cached<commit_after>/* jshint expr: true, unused: false */
/* global describe, it, before, after, beforeEach, afterEach */

var async      = require('async')
  , mongoose   = require('mongoose')
  , cachegoose = require('../')
  , should     = require('should')
  , mongoose   = require('mongoose')
  , Schema     = mongoose.Schema
  , RecordSchema
  , Record
  , cache
  , db
  ;

describe('cachegoose', function() {
  before(function(done) {
    cachegoose(mongoose, {
      engine: 'redis',
      port: 6379,
      host: 'localhost'
    });

    cache = cachegoose._cache;

    mongoose.connect('mongodb://127.0.0.1/mongoose-cachegoose-testing');
    db = mongoose.connection;

    db.on('error', done);
    db.on('open', done);

    RecordSchema = new Schema({
      num: Number,
      date: {
        type: Date,
        default: Date.now
      }
    });

    Record = mongoose.model('Record', RecordSchema);
  });

  beforeEach(function(done) {
    generate(10, done);
  });

  afterEach(function(done) {
    Record.remove(function() {
      cache.clear(done);
    });
  });

  it('should have cache method after initialization', function () {
    Record.find({}).cache.should.be.a.Function;
  });

  it('should cache a simple query that uses callbacks', function(done) {
    getAll(60e3, function(err, res) {
      res.length.should.equal(10);
      Boolean(res._fromCache).should.be.false;

      getAll(60e3, function(err, res) {
        res.length.should.equal(10);
        Boolean(res._fromCache).should.be.true;
        done();
      });
    });
  });

  it('should cache a simple query that uses promises', function(done) {
    getAll(60e3).then(function(res) {
      res.length.should.equal(10);
      Boolean(res._fromCache).should.be.false;

      getAll(60e3).then(function(res) {
        res.length.should.equal(10);
        Boolean(res._fromCache).should.be.true;
        done();
      });
    });
  });

  it('should not cache the same query w/out a ttl defined', function(done) {
    getAll(60e3).then(function(res) {
      getAllNoCache(function(err, res) {
        Boolean(res._fromCache).should.be.false;
        done();
      });
    });
  });

  it('should return a Mongoose model from cached and non-cached results', function(done) {
    getAll(60e3, function(err, res) {
      var first = res[0];

      getAll(60e3, function(err2, res2) {
        var cachedFirst = res2[0];
        first.constructor.name.should.equal('model');
        cachedFirst.constructor.name.should.equal('model');

        res[0].isNew.should.be.false;
        res2[0].isNew.should.be.false;

        done();
      });
    });
  });

  it('should return lean models from cached and non-cached results', function(done) {
    getAllLean(10e3, function(err, res) {
      res.length.should.equal(10);
      Boolean(res._fromCache).should.be.false;

      getAllLean(10e3, function(err, res2) {
        res2.length.should.equal(10);
        Boolean(res2._fromCache).should.be.true;
        res[0].constructor.name.should.not.equal('model');
        res2[0].constructor.name.should.not.equal('model');
        done();
      });
    });
  });

  it('should distinguish between lean and non lean for the same conditions', function(done) {
    getAll(10e3, function(err, res) {
      getAll(10e3, function(err, res2) {
        res2.length.should.equal(10);
        Boolean(res2._fromCache).should.be.true;
        res2[0].constructor.name.should.equal('model');

        getAllLean(function(err, res3) {
          Boolean(res3._fromCache).should.be.false;
          res3[0].constructor.name.should.not.equal('model');
          done();
        });
      });
    });
  });

  it('should cache a query rerun many times', function(done) {
    getAll(60e3).then(function(res) {
      res.length.should.equal(10);
      Boolean(res._fromCache).should.be.false;

      async.series(
        new Array(20).join('.').split('').map(function() {
          return function(done) {
            getAll(60e3, done);
          };
        })
      , function() {
        getAll(60e3, function(err, res) {
          res.length.should.equal(10);
          Boolean(res._fromCache).should.be.true;
          done();
        });
      });
    });
  });

  it('should expire the cache', function(done) {
    getAll(1, function() {
      setTimeout(function() {
        getAll(1, function(err, res) {
          Boolean(res._fromCache).should.be.false;
          done();
        });
      }, 1200);
    });
  });
});

function getAll(ttl, cb) {
  return Record.find({}).cache(ttl).exec(cb);
}

function getAllNoCache(cb) {
  return Record.find({}).exec(cb);
}

function getAllLean(ttl, cb) {
  return Record.find({}).lean().cache(ttl).exec(cb);
}

function generate (amount, cb) {
  var records = [];
  var count = 0;
  while (count < amount) {
    records.push({
      num: count
    });
    count++;
  }

  Record.create(records, cb);
}

<|endoftext|>


<commit_before>// (C) Copyright 2014-2016 Hewlett Packard Enterprise Development LP

import React, { Component, PropTypes } from 'react';
import Section from 'grommet/components/Section';
import Header from 'grommet/components/Header';
import Menu from 'grommet/components/Menu';
import Anchor from 'grommet/components/Anchor';
import Button from 'grommet/components/Button';
import CheckBox from 'grommet/components/CheckBox';
import PreviousIcon from 'grommet/components/icons/base/Previous';
import NextIcon from 'grommet/components/icons/base/Next';
import LinkPreviousIcon from 'grommet/components/icons/base/LinkPrevious';
import KeyboardAccelerators from 'grommet/utils/KeyboardAccelerators';
import DocsArticle from './DocsArticle';

export default class ExamplesDoc extends Component {

  constructor () {
    super();
    this._onNext = this._onNext.bind(this);
    this._onPrevious = this._onPrevious.bind(this);
    this._onChangePropertyValue = this._onChangePropertyValue.bind(this);
    this._onTogglePropertyValue = this._onTogglePropertyValue.bind(this);
    this.state = { index: 0, dark: false, propertyValue: undefined };
  }

  componentDidMount () {
    this._keys = {left: this._onPrevious, right: this._onNext};
    KeyboardAccelerators.startListeningToKeyboard(this, this._keys);
    // load index from location
    const index = parseInt(window.location.hash.slice(1), 10);
    this.setState({ index: index || 0 });
  }

  componentWillUnmount () {
    KeyboardAccelerators.stopListeningToKeyboard(this, this._keys);
  }

  _select (index) {
    this.setState({ index: index });
    window.location.hash = index;
  }

  _onNext () {
    const { examples } = this.props;
    const { index } = this.state;
    this._select((index < (examples.length - 1) ? index + 1 : 0));
  }

  _onPrevious () {
    const { examples } = this.props;
    const { index } = this.state;
    this._select((index > 0 ? index - 1 : examples.length - 1));
  }

  _onChangePropertyValue (event) {
    this.setState({ propertyValue: event.target.value });
  }

  _onTogglePropertyValue (event) {
    this.setState({ propertyValue: ! this.state.propertyValue });
  }

  render () {
    const { context, examples, property, title } = this.props;
    const { index, dark, propertyValue } = this.state;
    const example = examples[index];

    const items = examples.map((item, index) => (
      <Anchor key={index} label={item.label}
        onClick={() => this._select(index)} />
    ));

    let propertySelector;
    let props = {};
    if (property) {
      if (property.values) {
        const options = property.values.map(value => (
          <option key={value}>{value}</option>
        ));
        options.unshift(<option key="NoNe"></option>);
        propertySelector = (
          <select value={propertyValue} onChange={this._onChangePropertyValue} >
            {options}
          </select>
        );
      } else {
        propertySelector = (
          <CheckBox checked={propertyValue || false} toggle={true}
            label={property.name}
            onChange={this._onTogglePropertyValue} />
        );
      }
      if (propertyValue) {
        props[property.name] = propertyValue;
      }
    }

    const Component = example.component;
    props = { ...(example.props || {}), ...props };

    let contextSection;
    if (context) {
      const link = React.cloneElement(context,
        { primary: true, icon: <LinkPreviousIcon /> });
      contextSection = (

          {link}

      );
    }

    let previous, next, menu, pad;
    if (items.length > 1) {
      menu = (
        <Menu label={examples[index].label} inline={false} size="large">
          {items}
        </Menu>
      );
      previous = (
        <Button icon={<PreviousIcon />} onClick={this._onPrevious} />
      );
      next = (
        <Button icon={<NextIcon />} onClick={this._onNext} />
      );
    } else {
      pad = { horizontal: 'large' };
    }

    return (
      <DocsArticle context={context} title={title} colorIndex="neutral-3"
        full={true}>

          {menu}
          {propertySelector}
          <CheckBox checked={dark} toggle={true} label="dark"
            onChange={() => this.setState({ dark: ! dark })} />

          {previous}
          <Component {...props} />
          {next}

        {contextSection}

      </DocsArticle>
    );
  }
};

ExamplesDoc.propTypes = {
  context: PropTypes.element,
  examples: PropTypes.arrayOf(PropTypes.shape({
    label: PropTypes.string,
    component: PropTypes.func,
    props: PropTypes.object
  })),
  property: PropTypes.shape({
    name: PropTypes.string.isRequired,
    values: PropTypes.arrayOf(PropTypes.string)
  }),
  title: PropTypes.string
};
<commit_msg>Don't loop ExamplesDoc navigation.<commit_after>// (C) Copyright 2014-2016 Hewlett Packard Enterprise Development LP

import React, { Component, PropTypes } from 'react';
import Section from 'grommet/components/Section';
import Header from 'grommet/components/Header';
import Menu from 'grommet/components/Menu';
import Anchor from 'grommet/components/Anchor';
import Button from 'grommet/components/Button';
import CheckBox from 'grommet/components/CheckBox';
import PreviousIcon from 'grommet/components/icons/base/Previous';
import NextIcon from 'grommet/components/icons/base/Next';
import LinkPreviousIcon from 'grommet/components/icons/base/LinkPrevious';
import KeyboardAccelerators from 'grommet/utils/KeyboardAccelerators';
import DocsArticle from './DocsArticle';

export default class ExamplesDoc extends Component {

  constructor () {
    super();
    this._onNext = this._onNext.bind(this);
    this._onPrevious = this._onPrevious.bind(this);
    this._onChangePropertyValue = this._onChangePropertyValue.bind(this);
    this._onTogglePropertyValue = this._onTogglePropertyValue.bind(this);
    this.state = { index: 0, dark: false, propertyValue: undefined };
  }

  componentDidMount () {
    this._keys = {left: this._onPrevious, right: this._onNext};
    KeyboardAccelerators.startListeningToKeyboard(this, this._keys);
    // load index from location
    const index = parseInt(window.location.hash.slice(1), 10);
    this.setState({ index: index || 0 });
  }

  componentWillUnmount () {
    KeyboardAccelerators.stopListeningToKeyboard(this, this._keys);
  }

  _select (index) {
    this.setState({ index: index });
    window.location.hash = index;
  }

  _onNext () {
    const { examples } = this.props;
    const { index } = this.state;
    this._select((index < (examples.length - 1) ? index + 1 :
      (examples.length - 1)));
  }

  _onPrevious () {
    const { index } = this.state;
    this._select((index > 0 ? index - 1 : 0));
  }

  _onChangePropertyValue (event) {
    this.setState({ propertyValue: event.target.value });
  }

  _onTogglePropertyValue (event) {
    this.setState({ propertyValue: ! this.state.propertyValue });
  }

  render () {
    const { context, examples, property, title } = this.props;
    const { index, dark, propertyValue } = this.state;
    const example = examples[index];

    const items = examples.map((item, index) => (
      <Anchor key={index} label={item.label}
        onClick={() => this._select(index)} />
    ));

    let propertySelector;
    let props = {};
    if (property) {
      if (property.values) {
        const options = property.values.map(value => (
          <option key={value}>{value}</option>
        ));
        options.unshift(<option key="NoNe"></option>);
        propertySelector = (
          <select value={propertyValue} onChange={this._onChangePropertyValue} >
            {options}
          </select>
        );
      } else {
        propertySelector = (
          <CheckBox checked={propertyValue || false} toggle={true}
            label={property.name}
            onChange={this._onTogglePropertyValue} />
        );
      }
      if (propertyValue) {
        props[property.name] = propertyValue;
      }
    }

    const Component = example.component;
    props = { ...(example.props || {}), ...props };

    let contextSection;
    if (context) {
      const link = React.cloneElement(context,
        { primary: true, icon: <LinkPreviousIcon /> });
      contextSection = (

          {link}

      );
    }

    let previous, next, menu, pad;
    if (items.length > 1) {
      menu = (
        <Menu label={examples[index].label} inline={false} size="large">
          {items}
        </Menu>
      );
      if (index > 0) {
        previous = (
          <Button icon={<PreviousIcon />} onClick={this._onPrevious} />
        );
      }
      if (index < (items.length - 1)) {
        next = (
          <Button icon={<NextIcon />} onClick={this._onNext} />
        );
      }
    } else {
      pad = { horizontal: 'large' };
    }

    return (
      <DocsArticle context={context} title={title} colorIndex="neutral-3"
        full={true}>

          {menu}
          {propertySelector}
          <CheckBox checked={dark} toggle={true} label="dark"
            onChange={() => this.setState({ dark: ! dark })} />

          {previous}
          <Component {...props} />
          {next}

        {contextSection}

      </DocsArticle>
    );
  }
};

ExamplesDoc.propTypes = {
  context: PropTypes.element,
  examples: PropTypes.arrayOf(PropTypes.shape({
    label: PropTypes.string,
    component: PropTypes.func,
    props: PropTypes.object
  })),
  property: PropTypes.shape({
    name: PropTypes.string.isRequired,
    values: PropTypes.arrayOf(PropTypes.string)
  }),
  title: PropTypes.string
};
<|endoftext|>


<commit_before>var ts = require('..')
var assert = require('assert')

var l = 1000
var prev = 0
//assert that timestamps are strictly increasing!
while (l--) {
  var t = ts()
  assert(prev < t)
  prev = t
}

<commit_msg>strengthen test<commit_after>var ts = require('..')
var assert = require('assert')

var l = 1000000
var prev = 0
//assert that timestamps are strictly increasing!
while (l--) {
  var t = ts()
  if(prev >= t) {
    console.log('collision', prev, t)
    assert(prev < t)
  }
  prev = t
}

<|endoftext|>


<commit_before>import { test } from 'tap';

test('ok', (t) => {
    t.end();
});
<commit_msg>Add initial tests<commit_after>import { test } from 'tap';
import fs from 'fs';
import path from 'path';
import jsdom from 'jsdom';

const document = jsdom.jsdom(undefined, {
    virtualConsole: jsdom.createVirtualConsole().sendTo(console)
});
const window = document.defaultView;

global.document = document;
global.window = window;
global.navigator = window.navigator;

const treeData = Object.freeze(require('./fixtures/tree.json'));
const InfiniteTree = require('../src');

const getTreeElement = () => {
    while (document.body.firstChild) {
        document.body.removeChild(document.body.firstChild);
    }

    const el = document.createElement('div');
    el.setAttribute('id', 'tree');
    document.body.appendChild(el);

    return el;
};

test('Close all nodes on tree initialization', (t) => {
    const el = getTreeElement();
    const tree = new InfiniteTree(el, {
        autoOpen: false,
        data: { ...treeData }
    });

    t.same(tree.nodes.length, 1);
    t.same(tree.rows.length, 1);
    t.end();
});

test('Open all nodes on tree initialization', (t) => {
    const el = getTreeElement();
    const tree = new InfiniteTree(el, {
        autoOpen: true,
        data: { ...treeData }
    });

    t.same(tree.nodes.length, 12);
    t.same(tree.rows.length, 12);
    t.end();
});

test('It should generate expected output for empty result', (t) => {
    const el = getTreeElement();
    const options = {
        noDataClass: 'my-no-data-class',
        noDataText: 'My no data text'
    };
    const tree = new InfiniteTree(el, options);
    const innerHTML = `

${options.noDataText}

`;

    t.same(window.document.body.innerHTML, innerHTML);
    t.same(tree.nodes.length, 0);
    t.same(tree.rows.length, 0);
    t.end();
});
<|endoftext|>


<commit_before>import React, { Component } from 'react'
import { Link } from 'react-router-dom'
import {
  Card,
  CardHeader,
  CardMedia,
  CardTitle,
  CardText,
  CardActions
} from 'material-ui/Card'

export class GenericCard extends Component {
  render () {
    const { link, className } = this.props

    const CardContent = ({
      actions,
      cardSubtitle,
      cardTitle,
      children,
      classes,
      headerAvatar,
      headerSubtitle,
      headerTitle,
      hoverable,
      mediaImgAlt,
      mediaImgSrc,
      overlay,
      zDepth
    }) =>
      <Card
        className={`${classes} card z-depth-1`}
        style={{ boxShadow: 'none' }}>
          {(headerTitle || headerAvatar) && (
            <CardHeader
              title={headerTitle}
              subtitle={headerSubtitle}
              avatar={headerAvatar}
            />
          )}

          {mediaImgSrc && (
            <CardMedia className='img-container' overlay={overlay}>

            </CardMedia>
          )}
          {cardTitle &&

            <CardTitle
              title={cardTitle}
              subtitle={cardSubtitle}
              style={{ paddingBottom: '0' }}
              />}
          <CardText style={{ fontSize: '16px',  paddingTop: '0' }}>{children}</CardText>
          {actions && (
            <CardActions className='card-actions'>{actions}</CardActions>
          )}
      </Card>

    const isInternal = link && link[0] === '/'

    const jsx = link
      ? isInternal
        ? <Link to={link}>
            <CardContent {...this.props} />
          </Link>
         :

            <CardContent {...this.props} />

        : <CardContent {...this.props} />

    return jsx
  }
}

export default GenericCard
<commit_msg>change<commit_after>import React, { Component } from 'react'
import { Link } from 'react-router-dom'
import {
  Card,
  CardHeader,
  CardMedia,
  CardTitle,
  CardText,
  CardActions
} from 'material-ui/Card'

export class GenericCard extends Component {
  render () {
    const { link, className } = this.props

    const CardContent = ({
      actions,
      cardSubtitle,
      cardTitle,
      children,
      headerAvatar,
      headerSubtitle,
      headerTitle,
      mediaImgAlt,
      mediaImgSrc,
      overlay
    }) =>
      <Card
        className={`${className} card z-depth-1`}
        style={{ boxShadow: 'none' }}>
          {(headerTitle || headerAvatar) && (
            <CardHeader
              title={headerTitle}
              subtitle={headerSubtitle}
              avatar={headerAvatar}
            />
          )}

          {mediaImgSrc && (
            <CardMedia className='img-container' overlay={overlay}>

            </CardMedia>
          )}
          {cardTitle &&

            <CardTitle
              title={cardTitle}
              subtitle={cardSubtitle}
              style={{ paddingBottom: '0' }}
              />}
          <CardText style={{ fontSize: '16px',  paddingTop: '0' }}>{children}</CardText>
          {actions && (
            <CardActions className='card-actions'>{actions}</CardActions>
          )}
      </Card>

    const isInternal = link && link[0] === '/'

    const jsx = link
      ? isInternal
        ? <Link to={link}>
            <CardContent {...this.props} />
          </Link>
         :

            <CardContent {...this.props} />

        : <CardContent {...this.props} />

    return jsx
  }
}

export default GenericCard
<|endoftext|>


<commit_before>var fs = require('fs')
var assert = require('assert')
var sinon = require('sinon')
var rmrf = require('rimraf')
var low = require('../src')
var disk = require('../src/disk')

/* global beforeEach, afterEach, describe, it */

var tempDir = __dirname + '/../tmp'
var syncFile = tempDir + '/sync.json'
var asyncFile = tempDir + '/async.json'

describe('LowDB', function () {

  var db

  beforeEach(function () {
    rmrf.sync(tempDir)
    fs.mkdirSync(tempDir)
  })

  describe('CRUD', function () {

    beforeEach(function () {
      db = low()
    })

    it('creates', function () {
      db('foo').push({ a: 1 })
      assert.equal(db('foo').size(), 1)
      assert.deepEqual(db.object, { foo: [{ a: 1 }]})
    })

    it('reads', function () {
      db('foo').push({ a: 1 })
      assert.deepEqual(db('foo').find({ a: 1 }), { a: 1 })
    })

    it('updates', function () {
      db('foo').push({ a: 1 })
      db('foo')
        .chain()
        .find({ a: 1 })
        .assign({ a: 2 })
        .value()
      assert(!db('foo').chain().find({ a: 2 }).isUndefined().value())
    })

    it('deletes', function () {
      db('foo').push({ a: 1 })
      db('foo').remove({ a: 1 })
      assert(db('foo').isEmpty())
    })

  })

  describe('Async', function () {

    beforeEach(function () {
      db = low(asyncFile)
    })

    // Since it's async need to wait between each test

    describe('Autosave', function () {
      beforeEach(function (done) {
        db('foo').push({ a: 1 })
        setTimeout(done, 10)
      })

      it('saves automatically to file', function (done) {
        assert.deepEqual(
          JSON.parse(fs.readFileSync(asyncFile)),
          { foo: [{ a: 1 }] }
        )
        setTimeout(done, 10)
      })
    })

    describe('#save()', function () {
      beforeEach(function (done) {
        db.object.foo = [ { a: 1 } ]
        db.save()
        setTimeout(done, 10)
      })

      it('saves database', function (done) {
        assert.deepEqual(
          JSON.parse(fs.readFileSync(asyncFile)),
          { foo: [{ a: 1 }] }
        )
        setTimeout(done, 10)
      })
    })

  })

  describe('sync', function () {

    beforeEach(function () {
      fs.writeFileSync(syncFile, JSON.stringify({ foo: [{ a: 1 }] }))
      db = low(syncFile, { async: false })
    })

    describe('Autoload', function () {
      it('loads automatically file', function () {
        assert.deepEqual(db('foo').value(), [{ a: 1 }])
      })
    })

    describe('Autosave with short syntax', function () {
      beforeEach(function () {
        db('foo').chain().find({ a: 1 }).assign({ a: 2 }).value()
      })

      it('saves automatically to file', function () {
        assert.deepEqual(
          JSON.parse(fs.readFileSync(syncFile)),
          { foo: [{ a: 2 }] }
        )
      })
    })

    describe('Autosave with chain syntax', function () {
      beforeEach(function () {
        db('foo').chain().find({ a: 1 }).assign({ a: 2 }).value()
      })

      it('saves automatically to file', function () {
        assert.deepEqual(
          JSON.parse(fs.readFileSync(syncFile)),
          { foo: [{ a: 2 }] }
        )
      })
    })

    describe('Autosave checksum', function () {

      it('writes to disk only if db.object has changed', function () {
        var spy = sinon.spy(disk, 'writeSync')
        var songs = db('songs')
        assert(spy.calledOnce)
        spy.reset()

        songs.find()
        assert(!spy.calledOnce)
        spy.reset()

        songs.push({ a: 1 })
        assert(spy.calledOnce)
        spy.reset()

        songs.chain().push({ a: 1}).value()
        assert(spy.calledOnce)
      })

    })

    describe('#saveSync()', function () {
      beforeEach(function () {
        db.object.foo = [ { b: 2 } ]
        db.saveSync()
      })

      it('saves database', function () {
        assert.deepEqual(
          JSON.parse(fs.readFileSync(syncFile)),
          { foo: [{ b: 2 }] }
        )
      })

      it('saves to another file if a parameter is provided', function () {
        var copy = tempDir + '/copy.json'
        db.saveSync(copy)
        assert(fs.existsSync(copy))
        assert(fs.readFileSync(copy), fs.readFileSync(syncFile))
      })
    })

  })

  describe('mixin', function () {

    beforeEach(function () {
      db = low(syncFile, { async: false })
      db.mixin({
        hello: function (array, word) {
          array.push('hello ' + word)
        }
      })
    })

    it('adds functions', function () {
      db('foo').hello('world')
      assert.deepEqual(JSON.parse(fs.readFileSync(syncFile)), { foo: [ 'hello world' ] })
    })

  })

  describe('stringify and parse', function () {

    var stringify = low.stringify
    var parse = low.parse

    beforeEach(function () {
      low.stringify = function () { return '{ "foo": [] }' }
      low.parse = function () { return { bar: [] } }
      fs.writeFileSync(syncFile, '{}')
      db = low(syncFile, { async: false })
    })

    afterEach(function () {
      low.stringify = stringify
      low.parse = parse
    })

    it('can be overriden', function () {
      assert.deepEqual(db.object, { bar: [] })
      db.saveSync() // will stringify object
      assert.equal(fs.readFileSync(syncFile, 'utf-8'), '{ "foo": [] }')
    })

  })

  describe('empty database', function () {

    it('loads an empty file', function () {
      fs.writeFileSync(syncFile, '')
      assert.doesNotThrow(low(syncFile, { async: false }))
    })

    it('loads a file with whitespaces', function () {
      fs.writeFileSync(syncFile, '\n\t ')
      assert.doesNotThrow(low(syncFile, { async: false }))
    })

  })
})

describe('underscore-db', function () {

  var db

  beforeEach(function () {
    db = low(syncFile)
    db.mixin(require('underscore-db'))
  })

  it('is supported', function () {
    var id = db('foo').insert({ a: 1 }).id
    assert(db('foo').getById(id).a, 1)
  })

})
<commit_msg>Wrong test<commit_after>var fs = require('fs')
var assert = require('assert')
var sinon = require('sinon')
var rmrf = require('rimraf')
var low = require('../src')
var disk = require('../src/disk')

/* global beforeEach, afterEach, describe, it */

var tempDir = __dirname + '/../tmp'
var syncFile = tempDir + '/sync.json'
var asyncFile = tempDir + '/async.json'

describe('LowDB', function () {

  var db

  beforeEach(function () {
    rmrf.sync(tempDir)
    fs.mkdirSync(tempDir)
  })

  describe('CRUD', function () {

    beforeEach(function () {
      db = low()
    })

    it('creates', function () {
      db('foo').push({ a: 1 })
      assert.equal(db('foo').size(), 1)
      assert.deepEqual(db.object, { foo: [{ a: 1 }]})
    })

    it('reads', function () {
      db('foo').push({ a: 1 })
      assert.deepEqual(db('foo').find({ a: 1 }), { a: 1 })
    })

    it('updates', function () {
      db('foo').push({ a: 1 })
      db('foo')
        .chain()
        .find({ a: 1 })
        .assign({ a: 2 })
        .value()
      assert(!db('foo').chain().find({ a: 2 }).isUndefined().value())
    })

    it('deletes', function () {
      db('foo').push({ a: 1 })
      db('foo').remove({ a: 1 })
      assert(db('foo').isEmpty())
    })

  })

  describe('Async', function () {

    beforeEach(function () {
      db = low(asyncFile)
    })

    // Since it's async need to wait between each test

    describe('Autosave', function () {
      beforeEach(function (done) {
        db('foo').push({ a: 1 })
        setTimeout(done, 10)
      })

      it('saves automatically to file', function (done) {
        assert.deepEqual(
          JSON.parse(fs.readFileSync(asyncFile)),
          { foo: [{ a: 1 }] }
        )
        setTimeout(done, 10)
      })
    })

    describe('#save()', function () {
      beforeEach(function (done) {
        db.object.foo = [ { a: 1 } ]
        db.save()
        setTimeout(done, 10)
      })

      it('saves database', function (done) {
        assert.deepEqual(
          JSON.parse(fs.readFileSync(asyncFile)),
          { foo: [{ a: 1 }] }
        )
        setTimeout(done, 10)
      })
    })

  })

  describe('sync', function () {

    beforeEach(function () {
      fs.writeFileSync(syncFile, JSON.stringify({ foo: [{ a: 1 }] }))
      db = low(syncFile, { async: false })
    })

    describe('Autoload', function () {
      it('loads automatically file', function () {
        assert.deepEqual(db('foo').value(), [{ a: 1 }])
      })
    })

    describe('Autosave with short syntax', function () {
      beforeEach(function () {
        db('foo').push({ b: 2 })
      })

      it('saves automatically to file', function () {
        assert.deepEqual(
          JSON.parse(fs.readFileSync(syncFile)),
          { foo: [{ a: 1 }, { b: 2 }] }
        )
      })
    })

    describe('Autosave with chain syntax', function () {
      beforeEach(function () {
        db('foo').chain().find({ a: 1 }).assign({ a: 2 }).value()
      })

      it('saves automatically to file', function () {
        assert.deepEqual(
          JSON.parse(fs.readFileSync(syncFile)),
          { foo: [{ a: 2 }] }
        )
      })
    })

    describe('Autosave checksum', function () {

      it('writes to disk only if db.object has changed', function () {
        var spy = sinon.spy(disk, 'writeSync')
        var songs = db('songs')
        assert(spy.calledOnce)
        spy.reset()

        songs.find()
        assert(!spy.calledOnce)
        spy.reset()

        songs.push({ a: 1 })
        assert(spy.calledOnce)
        spy.reset()

        songs.chain().push({ a: 1}).value()
        assert(spy.calledOnce)
      })

    })

    describe('#saveSync()', function () {
      beforeEach(function () {
        db.object.foo = [ { b: 2 } ]
        db.saveSync()
      })

      it('saves database', function () {
        assert.deepEqual(
          JSON.parse(fs.readFileSync(syncFile)),
          { foo: [{ b: 2 }] }
        )
      })

      it('saves to another file if a parameter is provided', function () {
        var copy = tempDir + '/copy.json'
        db.saveSync(copy)
        assert(fs.existsSync(copy))
        assert(fs.readFileSync(copy), fs.readFileSync(syncFile))
      })
    })

  })

  describe('mixin', function () {

    beforeEach(function () {
      db = low(syncFile, { async: false })
      db.mixin({
        hello: function (array, word) {
          array.push('hello ' + word)
        }
      })
    })

    it('adds functions', function () {
      db('foo').hello('world')
      assert.deepEqual(JSON.parse(fs.readFileSync(syncFile)), { foo: [ 'hello world' ] })
    })

  })

  describe('stringify and parse', function () {

    var stringify = low.stringify
    var parse = low.parse

    beforeEach(function () {
      low.stringify = function () { return '{ "foo": [] }' }
      low.parse = function () { return { bar: [] } }
      fs.writeFileSync(syncFile, '{}')
      db = low(syncFile, { async: false })
    })

    afterEach(function () {
      low.stringify = stringify
      low.parse = parse
    })

    it('can be overriden', function () {
      assert.deepEqual(db.object, { bar: [] })
      db.saveSync() // will stringify object
      assert.equal(fs.readFileSync(syncFile, 'utf-8'), '{ "foo": [] }')
    })

  })

  describe('empty database', function () {

    it('loads an empty file', function () {
      fs.writeFileSync(syncFile, '')
      assert.doesNotThrow(low(syncFile, { async: false }))
    })

    it('loads a file with whitespaces', function () {
      fs.writeFileSync(syncFile, '\n\t ')
      assert.doesNotThrow(low(syncFile, { async: false }))
    })

  })
})

describe('underscore-db', function () {

  var db

  beforeEach(function () {
    db = low(syncFile)
    db.mixin(require('underscore-db'))
  })

  it('is supported', function () {
    var id = db('foo').insert({ a: 1 }).id
    assert(db('foo').getById(id).a, 1)
  })

})
<|endoftext|>


<commit_before>import React from 'react';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import vis from 'vis';

import s from './Graph.css';
const options = {
  groups: {
    usergroups: {
      shape: 'icon',
      icon: {
        face: 'Ionicons',
        code: '\uf47c',
        size: 50,
        color: '#57169a',
      }
    },
    users: {
      shape: 'icon',
      icon: {
        face: 'Ionicons',
        code: '\uf47e',
        size: 50,
        color: '#aa00ff'
      }
    }
  }
};
const rel_color={"WORKS": "red", "COMPETITOR": "green"};
class Graph extends React.Component {
  componentDidMount(): void {
    const { data: dump_data } = this.props;
    const nods = dump_data.nodes.map(n => {
      const t =  ({id: n.id, label: n.labels[0], properties: n.properties});
      if (t.label ==='Person') {
        t.group = 'users';
        return t;
      }
      if (t.label = 'Organization') {
        t.shape  = 'icon';
        t.icon = { face: 'Ionicons',code: '\uf276',  size: 50, color: '#f0a30a'}
        return t;
      }

    });

    console.log(nods);
    const rels = dump_data.relationships.map(r => ({from: Number(r.startNode), to: Number(r.endNode), label: r.type, width: 5, color:{color:rel_color[r.type]},  properties: r.properties}));

    // create an array with edges
    const nodes = new vis.DataSet(nods);
    const edges = new vis.DataSet(rels);
    const data = {
      nodes,
      edges,
    };
    // const options = {};
    // eslint-disable-next-line no-unused-vars
    const network = new vis.Network(this.container, data, options);
    network.on("click", ((NODES) => function (params) {
        params.event = "[original event]";
        const nodeId = params.nodes[0];
        const clickedNode = NODES.filter(n => n.id === nodeId)[0];
        document.getElementById('node-selected').innerHTML = '
Detailed information:
' +
        'facebook_url:'+ clickedNode.properties.facebook_url + '' +
        '
cb_url: ' + clickedNode.properties.cb_url + '';
        //JSON.stringify(clickedNode, null, 4);
      })(nods));
  }
  container: null;
  render() {
    return
 { this.container = r; }} />;
  }
}

export default withStyles(s)(Graph);
<commit_msg>added diff relationships props<commit_after>import React from 'react';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import vis from 'vis';

import s from './Graph.css';
const options = {
  groups: {
    usergroups: {
      shape: 'icon',
      icon: {
        face: 'Ionicons',
        code: '\uf47c',
        size: 50,
        color: '#57169a',
      },
    },
    users: {
      shape: 'icon',
      icon: {
        face: 'Ionicons',
        code: '\uf47e',
        size: 50,
        color: '#aa00ff',
      },
    },
  },
};
const rel_color = { WORKS: 'red', COMPETITOR: 'green', INVESTED_IN: 'black', ACQUIRED: 'blue' };
class Graph extends React.Component {
  componentDidMount(): void {
    const { data: dump_data } = this.props;
    const nods = dump_data.nodes.map(n => {
      const t = ({ id: n.id, type: n.labels[0], properties: n.properties });
      if (t.type === 'Person') {
        t.label = `${t.properties.first_name} ${t.properties.last_name}`;
        t.group = 'users';
        return t;
      }
      if (t.type = 'Organization') {
        t.shape = 'icon';
        t.label = t.properties.company_name;
        t.icon = { face: 'Ionicons', code: '\uf276', size: 50, color: '#f0a30a' };
        return t;
      }
    });

    console.log(nods);
    const rels = dump_data.relationships.map(r => ({ from: Number(r.startNode), to: Number(r.endNode), arrows: 'to', label: r.type, width: 5, color: { color: rel_color[r.type] }, properties: r.properties }));

    // create an array with edges
    const nodes = new vis.DataSet(nods);
    const edges = new vis.DataSet(rels);
    const data = {
      nodes,
      edges,
    };
    // const options = {};
    // eslint-disable-next-line no-unused-vars
    const network = new vis.Network(this.container, data, options);
    network.on('click', ((NODES) => function (params) {
      params.event = '[original event]';
      const nodeId = params.nodes[0];
      const clickedNode = NODES.filter(n => n.id === nodeId)[0];
      document.getElementById('node-selected').innerHTML = `${'
Detailed information:
' +
        'facebook_url:${clickedNode.properties.facebook_url}` +
        `<br />cb_url: <a href="${clickedNode.properties.cb_url}">${clickedNode.properties.cb_url}</a>`;
        // JSON.stringify(clickedNode, null, 4);
    })(nods));
  }
  container: null;
  render() {
    return
 { this.container = r; }} />;
  }
}

export default withStyles(s)(Graph);
<|endoftext|>


<commit_before>function test(name, path) {
    describe(name, function () {
        require(path);
    });
}

describe('#dl-module', function (done) {
    this.timeout(2 * 60000);

    // Auth
    test('@AUTH/ACCOUNT', './auth/account');
    test('@AUTH/ROLE', './auth/role');
    test('@AUTH/API-ENDPOINT', './auth/api-endpoint');

    // // Migration Log
    test('@Migration Log/Migration Log', './migration-log/migration-log');

    //Etl
    test('@ETL/DIM-BUYER', './etl/dim/dim-buyer');
    test('@ETL/DIM-CATEGORY', './etl/dim/dim-category');
    test('@ETL/DIM-DIVISION', './etl/dim/dim-division');
    test('@ETL/DIM-SUPPLIER', './etl/dim/dim-supplier');
    test('@ETL/DIM-MACHINE', './etl/dim/dim-machine');
    test('@ETL/DIM-UNIT', './etl/dim/dim-unit');
    test('@ETL/DIM-PROCESS-TYPE', './etl/dim/dim-process-type');
    test('@ETL/DIM-ORDER-TYPE', './etl/dim/dim-order-type');
    test('@ETL/DIM-PRODUCT', './etl/dim/dim-product');
    test('@ETL/DIM-STORAGE', './etl/dim/dim-storage');
    test('@ETL/DIM-STAFF', './etl/dim/dim-staff');
    test('@ETL/DIM-COMPANY', './etl/dim/dim-company');
    test('@ETL/DIM-CONTACT', './etl/dim/dim-contact');
    test('@ETL/DIM-DURATION-ESTIMATION', './etl/dim/dim-duration-estimation');
    test('@ETL/DIM-BUDGET', './etl/dim/dim-budget');
    test('@ETL/FACT-TOTAL-HUTANG', './etl/purchasing/fact-total-hutang');
    test('@ETL/FACT-PURCHASING', './etl/purchasing/fact-purchasing');
    test('@ETL/FACT-MONITORING-EVENT', './etl/production/fact-monitoring-event');
    test('@ETL/FACT-PRODUCTION-ORDER', './etl/production/fact-production-order');
    test('@ETL/FACT-PRODUCTION-ORDER-STATUS', './etl/sales/fact-production-order-status');
    test('@ETL/FACT-WEAVING-SALES-CONTRACT', './etl/sales/fact-weaving-sales-contract');
    test('@ETL/FACT-FINISHING-PRINTING-SALES-CONTRACT', './etl/sales/fact-finishing-printing-sales-contract');
    test('@ETL/FACT-SPINNING-SALES-CONTRACT', './etl/sales/fact-spinning-sales-contract');
    test('@ETL/FACT-DAILY-OPERATIONS', './etl/production/fact-daily-operations');
    test('@ETL/FACT-KANBAN', './etl/production/fact-kanban');
    test('@ETL/FACT-QUALITY-CONTROL', './etl/production/fact-fabric-quality-control');
    test('@ETL/FACT-INVENTORY-MOVEMENT', './etl/inventory/fact-inventory-movement');
    test('@ETL/FACT-INVENTORY-SUMMARY', './etl/inventory/fact-inventory-summary');
    test('@ETL/garment-purchase-request', './etl/garment/garment-purchase-request');
    test('@ETL/FACT-GARMENT-PURCHASING', './etl/garment/purchasing/fact-purchasing');
    test('@ETL/FACT-FP-PACKING-RECEIPT', './etl/inventory/fact-fp-packing-receipt');
    test('@ETL/FACT-FP-SHIPMENT-DOCUMENT', './etl/inventory/fact-fp-shipment-document');
    test('@ETL/FACT-DEAL-TRACKING-BOARD', './etl/sales/fact-deal-tracking-board');
    test('@ETL/FACT-DEAL-TRACKING-STAGE', './etl/sales/fact-deal-tracking-stage');
    test('@ETL/FACT-DEAL-TRACKING-DEAL', './etl/sales/fact-deal-tracking-deal');
    test('@ETL/FACT-DEAL-TRACKING-ACTIVITY', './etl/sales/fact-deal-tracking-activity');
    test('@ETL/FACT-INSPECTION-LOT-COLOR', './etl/production/fact-inspection-lot-color');

    // Master
    test('@MASTER/ACCOUNT-BANK', './master/account-bank');
    test('@MASTER/BUDGET', './master/budget');
    test('@MASTER/BUYER', './master/buyer');
    test('@MASTER/GARMENT-BUYER', './master/garment-buyer');
    test('@MASTER/CATEGORY', './master/category');
    test('@MASTER/GARMENT-CATEGORY', './master/garment-category');
    test('@MASTER/CURRENCY', './master/currency');
    test('@MASTER/DIVISION', './master/division');
    test('@MASTER/LAMP-STANDARD', './master/lamp-standard');
    test('@MASTER/LOT-MACHINE', './master/lot-machine');
    test('@MASTER/MACHINE', './master/machine');
    test('@MASTER/PRODUCT', './master/product');
    test('@MASTER/GARMENT-PRODUCT', './master/garment-product');
    test('@MASTER/SUPPLIER', './master/supplier');
    test('@MASTER/GARMENT-SUPPLIER', './master/garment-supplier');
    test('@MASTER/THREAD-SPECIFICATION', './master/thread-specification');
    test('@MASTER/UNIT', './master/unit');
    test('@MASTER/UOM', './master/uom');
    test('@MASTER/USTER', './master/uster');
    test('@MASTER/VAT', './master/vat');
    test('@MASTER/YARN-EQUIVALENT-CONVERSION', './master/yarn-equivalent-coversion');
    test('@MASTER/ORDER-TYPE', './master/order-type');
    test('@MASTER/PROCESS-TYPE', './master/process-type');
    test('@MASTER/COLOR-TYPE', './master/color-type');
    test('@MASTER/INSTRUCTION', './master/instruction');

    // test('@MASTER/MONITORING-EVENT-TYPE', './master/monitoring-event-type');
    test('@MASTER/STEP', './master/step');
    //test('@MASTER/MACHINE-TYPE', './master/machine-type');
    test('@MASTER/MACHINE-SPESIFICATION-STANDARD', './master/machine-spesification-standard');
    test('@MASTER/MATERIAL-CONSTRUCTION', './master/material-construction');
    test('@MASTER/YARN-MATERIAL', './master/yarn-material');
    test('@MASTER/STANDARD-TEST', './master/standard-test');
    test('@MASTER/FINISH-TYPE', './master/finish-type');
    test('@MASTER/COMODITY', './master/comodity');
    test('@MASTER/QUALITY', './master/quality');
    test('@MASTER/TERM OF PAYMENT', './master/term-of-payment');
    test('@MASTER/DESIGN-MOTIVE', './master/design-motive');
    test('@MASTER/STORAGE', './master/storage');
    test('@MASTER/COMPANY', './master/company');
    test('@MASTER/CONTACT', './master/contact');
    test('@MASTER/BAD OUTPUT REASON', './master/bad-output-reason');
    test('@MASTER/FINISHING PRINTING DURATION ESTIMATION', './master/fp-duration-estimation');
    test('@MASTER/DEAL TRACKING REASON', './master/deal-tracking-reason');

    //Purchasing
    test('@PURCHASING/PURCHASE REQUEST', './purchasing/purchase-request');
    test('@PURCHASING/PURCHASE ORDER', './purchasing/purchase-order');
    test('@PURCHASING/PURCHASE ORDER EXTERNAL', './purchasing/purchase-order-external');
    test('@PURCHASING/DELIVERY ORDER', './purchasing/delivery-order');
    test('@PURCHASING/UNIT RECEIPT NOTE', './purchasing/unit-receipt-note');
    test('@PURCHASING/UNIT PAYMENT ORDER', './purchasing/unit-payment-order');
    test('@PURCHASING/UNIT PAYMENT PRICE CORRECTION', './purchasing/unit-payment-price-correction-note');
    test('@PURCHASING/UNIT PAYMENT QUANTITY CORRECTION', './purchasing/unit-payment-quantity-correction-note');
    test('@purchasing/purchase-order/report', './purchasing/purchase-order/report/report');
    test('@purchasing/purchase-order/report', './purchasing/duration-report');

    //Garmet Purchasing
    test('@GARMENT PURCHASING/PURCHASE REQUEST', './garment-purchasing/purchase-request');
    test('@GARMENT PURCHASING/PURCHASE ORDER', './garment-purchasing/purchase-order');
    test('@GARMENT PURCHASING/PURCHASE ORDER EXTERNAL', './garment-purchasing/purchase-order-external');
    test('@GARMENT PURCHASING/DELIVERY ORDER', './garment-purchasing/delivery-order');
    test('@GARMENT PURCHASING/CUSTOMS', './garment-purchasing/customs');
    test('@GARMENT PURCHASING/INVOICE NOTE', './garment-purchasing/invoice-note');
    test('@GARMENT PURCHASING/PURCHASE PRICE CORRECTION', './garment-purchasing/purchase-price-correction');
    test('@GARMENT PURCHASING/UNIT RECEIPT NOTE', './garment-purchasing/unit-receipt-note');
    test('@GARMENT PURCHASING/INTERN NOTE', './garment-purchasing/intern-note');
    test('@GARMENT PURCHASING/PURCHASE QUANTITY CORRECTION', './garment-purchasing/purchase-quantity-correction');
    test('@GARMENT PURCHASING/garment currency', './garment-purchasing/garment-currency');

    //Sales
    test('@SALES/PRODUCTION-ORDER', './sales/production-order');
    test('@SALES/FINISHING PRINTING SALES CONTRACT', './sales/finishing-printing-sales-contract');
    test('@SALES/SPINNING SALES CONTRACT', './sales/spinning-sales-contract');
    test('@SALES/WEAVING SALES CONTRACT', './sales/weaving-sales-contract');
    test('@SALES/DEAL TRACKING BOARD', './sales/deal-tracking-board');
    test('@SALES/DEAL TRACKING STAGE', './sales/deal-tracking-stage');
    test('@SALES/DEAL TRACKING DEAL', './sales/deal-tracking-deal');
    test('@SALES/DEAL TRACKING ACTIVITY', './sales/deal-tracking-activity');

    //Production
    test('@PRODUCTION/FINISHING-PRINTING/KANBAN', './production/finishing-printing/kanban');
    test('@PRODUCTION/FINISHING-PRINTING/FABRIC-QUALITY-CONTROL', './production/finishing-printing/fabric-quality-control');
    test('@PRODUCTION/FINISHING-PRINTING/PACKING', './production/finishing-printing/packing');
    test('@PRODUCTION/DAILY OPERATION', './production/finishing-printing/daily-operation');
    test('@PRODUCTION/FINISHING-PRINTING/MONITORING-SPECIFICATION-MACHINE', './production/finishing-printing/monitoring-specification-machine');
    test('@PRODUCTION/FINISHING-PRINTING/MONITORING-EVENT', './production/finishing-printing/monitoring-event');
    test('@PRODUCTION/INSPECTION LOT COLOR', './production/finishing-printing/inspection-lot-color');

    // test('@production/winding-quality-sampling-manager', './production/spinning/winding/winding-quality-sampling-manager-test');
    // test('@production/winding-production-output-manager', './production/spinning/winding/winding-production-output-manager-test');

    //Inventory
    test('@INVENTORY/FINISHING-PRINTING/PACKING-RECEIPT', './inventory/finishing-printing/packing-receipt');
    test('@INVENTORY/FINISHING-PRINTING/RETUR-TO-QC', './inventory/finishing-printing/fp-retur-to-qc-doc');
    test('@INVENTORY/FINISHING-PRINTING/SHIPMENT-DOCUMENT', './inventory/finishing-printing/shipment-document');
    test('@INVENTORY/INVENTORY-SUMMARY', './inventory/inventory-summary');
    test('@INVENTORY/INVENTORY-MOVEMENT', './inventory/inventory-movement');
    test('@INVENTORY/INVENTORY-DOCUMENT', './inventory/inventory-document');
    test('@INVENTORY/FINISHING-PRINTING/RETUR-FROM-BUYER', './inventory/finishing-printing/fp-retur-fr-byr-doc');

    //GarmentInventory
    test('@GARMENTINVENTORY/GARMENT-INVENTORY-SUMMARY', './inventory-garment/garment-inventory-summary');
    test('@GARMENTINVENTORY/GARMENT-INVENTORY-MOVEMENT', './inventory-garment/garment-inventory-movement');
    test('@GARMENTINVENTORY/GARMENT-INVENTORY-DOCUMENT', './inventory-garment/garment-inventory-document');
});
<commit_msg>test index<commit_after>function test(name, path) {
    describe(name, function () {
        require(path);
    });
}

describe('#dl-module', function (done) {
    this.timeout(2 * 60000);

    // Auth
    test('@AUTH/ACCOUNT', './auth/account');
    test('@AUTH/ROLE', './auth/role');
    test('@AUTH/API-ENDPOINT', './auth/api-endpoint');

    // // Migration Log
    test('@Migration Log/Migration Log', './migration-log/migration-log');

    //Etl
    test('@ETL/DIM-BUYER', './etl/dim/dim-buyer');
    test('@ETL/DIM-CATEGORY', './etl/dim/dim-category');
    test('@ETL/DIM-DIVISION', './etl/dim/dim-division');
    test('@ETL/DIM-SUPPLIER', './etl/dim/dim-supplier');
    test('@ETL/DIM-MACHINE', './etl/dim/dim-machine');
    test('@ETL/DIM-UNIT', './etl/dim/dim-unit');
    test('@ETL/DIM-PROCESS-TYPE', './etl/dim/dim-process-type');
    test('@ETL/DIM-ORDER-TYPE', './etl/dim/dim-order-type');
    test('@ETL/DIM-PRODUCT', './etl/dim/dim-product');
    test('@ETL/DIM-STORAGE', './etl/dim/dim-storage');
    test('@ETL/DIM-STAFF', './etl/dim/dim-staff');
    test('@ETL/DIM-COMPANY', './etl/dim/dim-company');
    test('@ETL/DIM-CONTACT', './etl/dim/dim-contact');
    test('@ETL/DIM-DURATION-ESTIMATION', './etl/dim/dim-duration-estimation');
    test('@ETL/DIM-BUDGET', './etl/dim/dim-budget');
    test('@ETL/FACT-TOTAL-HUTANG', './etl/purchasing/fact-total-hutang');
    test('@ETL/FACT-PURCHASING', './etl/purchasing/fact-purchasing');
    test('@ETL/FACT-MONITORING-EVENT', './etl/production/fact-monitoring-event');
    test('@ETL/FACT-PRODUCTION-ORDER', './etl/production/fact-production-order');
    test('@ETL/FACT-PRODUCTION-ORDER-STATUS', './etl/sales/fact-production-order-status');
    test('@ETL/FACT-WEAVING-SALES-CONTRACT', './etl/sales/fact-weaving-sales-contract');
    test('@ETL/FACT-FINISHING-PRINTING-SALES-CONTRACT', './etl/sales/fact-finishing-printing-sales-contract');
    test('@ETL/FACT-SPINNING-SALES-CONTRACT', './etl/sales/fact-spinning-sales-contract');
    test('@ETL/FACT-DAILY-OPERATIONS', './etl/production/fact-daily-operations');
    test('@ETL/FACT-KANBAN', './etl/production/fact-kanban');
    test('@ETL/FACT-QUALITY-CONTROL', './etl/production/fact-fabric-quality-control');
    test('@ETL/FACT-INVENTORY-MOVEMENT', './etl/inventory/fact-inventory-movement');
    test('@ETL/FACT-INVENTORY-SUMMARY', './etl/inventory/fact-inventory-summary');
    test('@ETL/garment-purchase-request', './etl/garment/garment-purchase-request');
    test('@ETL/FACT-GARMENT-PURCHASING', './etl/garment/purchasing/fact-purchasing');
    test('@ETL/FACT-FP-PACKING-RECEIPT', './etl/inventory/fact-fp-packing-receipt');
    test('@ETL/FACT-FP-SHIPMENT-DOCUMENT', './etl/inventory/fact-fp-shipment-document');
    test('@ETL/FACT-DEAL-TRACKING-BOARD', './etl/sales/fact-deal-tracking-board');
    test('@ETL/FACT-DEAL-TRACKING-STAGE', './etl/sales/fact-deal-tracking-stage');
    test('@ETL/FACT-DEAL-TRACKING-DEAL', './etl/sales/fact-deal-tracking-deal');
    test('@ETL/FACT-DEAL-TRACKING-ACTIVITY', './etl/sales/fact-deal-tracking-activity');
    test('@ETL/FACT-INSPECTION-LOT-COLOR', './etl/production/fact-inspection-lot-color');

    // Master
    test('@MASTER/ACCOUNT-BANK', './master/account-bank');
    test('@MASTER/BUDGET', './master/budget');
    test('@MASTER/BUYER', './master/buyer');
    test('@MASTER/GARMENT-BUYER', './master/garment-buyer');
    test('@MASTER/CATEGORY', './master/category');
    test('@MASTER/GARMENT-CATEGORY', './master/garment-category');
    test('@MASTER/CURRENCY', './master/currency');
    test('@MASTER/DIVISION', './master/division');
    test('@MASTER/LAMP-STANDARD', './master/lamp-standard');
    test('@MASTER/SPINNING-PRODUCTION-LOT', './master/spinning-production-lot');
    test('@MASTER/MACHINE', './master/machine');
    test('@MASTER/PRODUCT', './master/product');
    test('@MASTER/GARMENT-PRODUCT', './master/garment-product');
    test('@MASTER/SUPPLIER', './master/supplier');
    test('@MASTER/GARMENT-SUPPLIER', './master/garment-supplier');
    test('@MASTER/THREAD-SPECIFICATION', './master/thread-specification');
    test('@MASTER/UNIT', './master/unit');
    test('@MASTER/UOM', './master/uom');
    test('@MASTER/USTER', './master/uster');
    test('@MASTER/VAT', './master/vat');
    test('@MASTER/YARN-EQUIVALENT-CONVERSION', './master/yarn-equivalent-coversion');
    test('@MASTER/ORDER-TYPE', './master/order-type');
    test('@MASTER/PROCESS-TYPE', './master/process-type');
    test('@MASTER/COLOR-TYPE', './master/color-type');
    test('@MASTER/INSTRUCTION', './master/instruction');

    // test('@MASTER/MONITORING-EVENT-TYPE', './master/monitoring-event-type');
    test('@MASTER/STEP', './master/step');
    //test('@MASTER/MACHINE-TYPE', './master/machine-type');
    test('@MASTER/MACHINE-SPESIFICATION-STANDARD', './master/machine-spesification-standard');
    test('@MASTER/MATERIAL-CONSTRUCTION', './master/material-construction');
    test('@MASTER/YARN-MATERIAL', './master/yarn-material');
    test('@MASTER/STANDARD-TEST', './master/standard-test');
    test('@MASTER/FINISH-TYPE', './master/finish-type');
    test('@MASTER/COMODITY', './master/comodity');
    test('@MASTER/QUALITY', './master/quality');
    test('@MASTER/TERM OF PAYMENT', './master/term-of-payment');
    test('@MASTER/DESIGN-MOTIVE', './master/design-motive');
    test('@MASTER/STORAGE', './master/storage');
    test('@MASTER/COMPANY', './master/company');
    test('@MASTER/CONTACT', './master/contact');
    test('@MASTER/BAD OUTPUT REASON', './master/bad-output-reason');
    test('@MASTER/FINISHING PRINTING DURATION ESTIMATION', './master/fp-duration-estimation');
    test('@MASTER/DEAL TRACKING REASON', './master/deal-tracking-reason');
    test('@MASTER/SPINNING YARN', './master/spinning-yarn');

    //Purchasing
    test('@PURCHASING/PURCHASE REQUEST', './purchasing/purchase-request');
    test('@PURCHASING/PURCHASE ORDER', './purchasing/purchase-order');
    test('@PURCHASING/PURCHASE ORDER EXTERNAL', './purchasing/purchase-order-external');
    test('@PURCHASING/DELIVERY ORDER', './purchasing/delivery-order');
    test('@PURCHASING/UNIT RECEIPT NOTE', './purchasing/unit-receipt-note');
    test('@PURCHASING/UNIT PAYMENT ORDER', './purchasing/unit-payment-order');
    test('@PURCHASING/UNIT PAYMENT PRICE CORRECTION', './purchasing/unit-payment-price-correction-note');
    test('@PURCHASING/UNIT PAYMENT QUANTITY CORRECTION', './purchasing/unit-payment-quantity-correction-note');
    test('@purchasing/purchase-order/report', './purchasing/purchase-order/report/report');
    test('@purchasing/purchase-order/report', './purchasing/duration-report');

    //Garmet Purchasing
    test('@GARMENT PURCHASING/PURCHASE REQUEST', './garment-purchasing/purchase-request');
    test('@GARMENT PURCHASING/PURCHASE ORDER', './garment-purchasing/purchase-order');
    test('@GARMENT PURCHASING/PURCHASE ORDER EXTERNAL', './garment-purchasing/purchase-order-external');
    test('@GARMENT PURCHASING/DELIVERY ORDER', './garment-purchasing/delivery-order');
    test('@GARMENT PURCHASING/CUSTOMS', './garment-purchasing/customs');
    test('@GARMENT PURCHASING/INVOICE NOTE', './garment-purchasing/invoice-note');
    test('@GARMENT PURCHASING/PURCHASE PRICE CORRECTION', './garment-purchasing/purchase-price-correction');
    test('@GARMENT PURCHASING/UNIT RECEIPT NOTE', './garment-purchasing/unit-receipt-note');
    test('@GARMENT PURCHASING/INTERN NOTE', './garment-purchasing/intern-note');
    test('@GARMENT PURCHASING/PURCHASE QUANTITY CORRECTION', './garment-purchasing/purchase-quantity-correction');
    test('@GARMENT PURCHASING/garment currency', './garment-purchasing/garment-currency');

    //Sales
    test('@SALES/PRODUCTION-ORDER', './sales/production-order');
    test('@SALES/FINISHING PRINTING SALES CONTRACT', './sales/finishing-printing-sales-contract');
    test('@SALES/SPINNING SALES CONTRACT', './sales/spinning-sales-contract');
    test('@SALES/WEAVING SALES CONTRACT', './sales/weaving-sales-contract');
    test('@SALES/DEAL TRACKING BOARD', './sales/deal-tracking-board');
    test('@SALES/DEAL TRACKING STAGE', './sales/deal-tracking-stage');
    test('@SALES/DEAL TRACKING DEAL', './sales/deal-tracking-deal');
    test('@SALES/DEAL TRACKING ACTIVITY', './sales/deal-tracking-activity');

    //Production
    test('@PRODUCTION/FINISHING-PRINTING/KANBAN', './production/finishing-printing/kanban');
    test('@PRODUCTION/FINISHING-PRINTING/FABRIC-QUALITY-CONTROL', './production/finishing-printing/fabric-quality-control');
    test('@PRODUCTION/FINISHING-PRINTING/PACKING', './production/finishing-printing/packing');
    test('@PRODUCTION/DAILY OPERATION', './production/finishing-printing/daily-operation');
    test('@PRODUCTION/FINISHING-PRINTING/MONITORING-SPECIFICATION-MACHINE', './production/finishing-printing/monitoring-specification-machine');
    test('@PRODUCTION/FINISHING-PRINTING/MONITORING-EVENT', './production/finishing-printing/monitoring-event');
    test('@PRODUCTION/INSPECTION LOT COLOR', './production/finishing-printing/inspection-lot-color');

    // test('@production/winding-quality-sampling-manager', './production/spinning/winding/winding-quality-sampling-manager-test');
    // test('@production/winding-production-output-manager', './production/spinning/winding/winding-production-output-manager-test');

    //Inventory
    test('@INVENTORY/FINISHING-PRINTING/PACKING-RECEIPT', './inventory/finishing-printing/packing-receipt');
    test('@INVENTORY/FINISHING-PRINTING/RETUR-TO-QC', './inventory/finishing-printing/fp-retur-to-qc-doc');
    test('@INVENTORY/FINISHING-PRINTING/SHIPMENT-DOCUMENT', './inventory/finishing-printing/shipment-document');
    test('@INVENTORY/INVENTORY-SUMMARY', './inventory/inventory-summary');
    test('@INVENTORY/INVENTORY-MOVEMENT', './inventory/inventory-movement');
    test('@INVENTORY/INVENTORY-DOCUMENT', './inventory/inventory-document');
    test('@INVENTORY/FINISHING-PRINTING/RETUR-FROM-BUYER', './inventory/finishing-printing/fp-retur-fr-byr-doc');

    //GarmentInventory
    test('@GARMENTINVENTORY/GARMENT-INVENTORY-SUMMARY', './inventory-garment/garment-inventory-summary');
    test('@GARMENTINVENTORY/GARMENT-INVENTORY-MOVEMENT', './inventory-garment/garment-inventory-movement');
    test('@GARMENTINVENTORY/GARMENT-INVENTORY-DOCUMENT', './inventory-garment/garment-inventory-document');
});
<|endoftext|>


<commit_before>// @flow
// @jsx glam
import React, { cloneElement, Component } from 'react';
import glam from 'glam';
import Fullscreen from 'react-full-screen';
import ScrollLock from 'react-scrolllock';
import focusStore from 'a11y-focus-store';
import {
  defaultModalComponents,
  type ModalComponents,
} from '../defaultComponents';
import { Fade, SlideUp } from './Animation';
import { type CarouselType, trackBaseClassName } from '../Carousel';
import { defaultModalStyles, type ModalStylesConfig } from '../../styles';
import { isTouch, className } from '../../utils';
import { headerBaseClassName } from '../Header';
import { footerBaseClassName } from '../Footer';
import { viewBaseClassName } from '../View';

type MouseOrKeyboardEvent = MouseEvent | KeyboardEvent;
export type CloseType = (event: MouseOrKeyboardEvent) => void;
export type ModalProps = {
  allowFullscreen: boolean,
  isFullscreen: boolean,
  onClose: CloseType,
  preventScroll: boolean,
  toggleFullscreen: any => void,
};

export type Props = {
  /* Enable/disable the ability to "fullscreen" the dialog */
  allowFullscreen: boolean,
  /* Carousel only supported */
  children: CarouselType,
  /* Enable/disable calling `onClose` when the backdrop is clicked */
  closeOnBackdropClick: boolean,
  /* Enable/disable calling `onClose` when the `esc` key is pressed */
  closeOnEsc: boolean,
  /* Replace any of the modal components */
  components?: ModalComponents,
  /*
    Show the component; triggers the enter or exit states
    NOTE: provided by TransitionGroup, NOT supplied by the user
  */
  in: boolean,
  /* Function called to request close of the modal */
  onClose: CloseType,
  /* Prevent scroll */
  preventScroll: Boolean,
  /* Style modifier methods */
  styles: ModalStylesConfig,
};
type State = { isFullscreen: boolean };
const defaultProps = {
  allowFullscreen: !isTouch(),
  closeOnBackdropClick: true,
  closeOnEsc: true,
  preventScroll: true,
  styles: {},
};

/** Classes that when clicked on, close the backdrop */
const backdropClassNames = new Set(
  [
    viewBaseClassName,
    headerBaseClassName,
    footerBaseClassName,
    trackBaseClassName,
  ].map(className),
);

class Modal extends Component<Props, State> {
  commonProps: any; // TODO
  components: ModalComponents;

  static defaultProps = defaultProps;

  constructor(props: Props) {
    super(props);

    this.cacheComponents(props.components);

    this.state = { isFullscreen: false };
  }

  componentDidUpdate(prevProps: Props) {
    if (prevProps.components !== this.props.components) {
      this.cacheComponents(prevProps.components);
    }
  }

  // emulate `componentDidMount` & `componentWillUnmount`
  // called on complete of enter & exit transitions respectively
  modalDidMount = () => {
    document.addEventListener('keyup', this.handleKeyUp);
    focusStore.storeFocus();
  };
  modalWillUnmount = () => {
    document.removeEventListener('keyup', this.handleKeyUp);
    focusStore.restoreFocus();
  };

  cacheComponents = (comps?: ModalComponents) => {
    this.components = defaultModalComponents(comps);
  };
  handleFullscreenChange = (isFullscreen: boolean) => {
    this.setState({ isFullscreen });
  };
  handleKeyUp = (event: KeyboardEvent) => {
    const { allowFullscreen, closeOnEsc } = this.props;
    const { isFullscreen } = this.state;
    const allowClose = event.key === 'Escape' && closeOnEsc && !isFullscreen;

    // toggle fullscreen
    if (allowFullscreen && event.key === 'f') {
      this.toggleFullscreen();
    }

    // close on escape when not fullscreen
    if (allowClose) this.handleClose(event);
  };
  handleBackdropClick = (event: MouseEvent) => {
    const hasBackdropClassName = event.target.classList.some(className =>
      backdropClassNames.has(className),
    );

    if (!hasBackdropClassName || !this.props.closeOnBackdropClick) {
      return;
    }

    this.handleClose(event);
  };
  toggleFullscreen = () => {
    this.setState(state => ({ isFullscreen: !state.isFullscreen }));
  };
  handleClose = (event: MouseOrKeyboardEvent) => {
    const { onClose } = this.props;
    const { isFullscreen } = this.state;

    // force exit fullscreen mode on close
    if (isFullscreen) {
      this.toggleFullscreen();
    }

    // call the consumer's onClose func
    onClose(event);
  };

  getStyles = (key: string, props: {}): {} => {
    const base = defaultModalStyles[key](props);
    base.boxSizing = 'border-box';
    const custom = this.props.styles[key];
    return custom ? custom(base, props) : base;
  };
  getCommonProps() {
    const { isFullscreen } = this.state;

    return {
      getStyles: this.getStyles,
      isFullscreen,
      modalProps: this.props,
    };
  }
  render() {
    const { Blanket, Positioner, Dialog } = this.components;
    const { allowFullscreen, children, preventScroll } = this.props;
    const { isFullscreen } = this.state;
    const commonProps = (this.commonProps = this.getCommonProps());

    // $FlowFixMe
    const transitionIn = this.props.in;

    // forward props to modal for use in internal components
    const modalProps: ModalProps = {
      allowFullscreen,
      isFullscreen,
      onClose: this.handleClose,
      preventScroll: this.preventScroll,
      toggleFullscreen: this.toggleFullscreen,
    };

    // augment user carousel with modal props
    // $FlowFixMe
    const carouselComponent: CarouselType = cloneElement(children, {
      isModal: true,
      modalProps,
    });

    return (
      <Fullscreen enabled={isFullscreen} onChange={this.handleFullscreenChange}>
        <Fade {...commonProps} component={Blanket} in={transitionIn} />
        <SlideUp
          {...commonProps}
          component={Positioner}
          in={transitionIn}
          innerProps={{
            onClick: this.handleBackdropClick,
          }}
          onEntered={this.modalDidMount}
          onExited={this.modalWillUnmount}
        >
          <Dialog {...commonProps}>{carouselComponent}</Dialog>
          {preventScroll && <ScrollLock />}
        </SlideUp>
      </Fullscreen>
    );
  }
}
export default Modal;
export type ModalType = typeof Modal;
<commit_msg>Fixed attempt to call .some() on DomTokenList, which isn't an array<commit_after>// @flow
// @jsx glam
import React, { cloneElement, Component } from 'react';
import glam from 'glam';
import Fullscreen from 'react-full-screen';
import ScrollLock from 'react-scrolllock';
import focusStore from 'a11y-focus-store';
import {
  defaultModalComponents,
  type ModalComponents,
} from '../defaultComponents';
import { Fade, SlideUp } from './Animation';
import { type CarouselType, trackBaseClassName } from '../Carousel';
import { defaultModalStyles, type ModalStylesConfig } from '../../styles';
import { isTouch, className } from '../../utils';
import { headerBaseClassName } from '../Header';
import { footerBaseClassName } from '../Footer';
import { viewBaseClassName } from '../View';

type MouseOrKeyboardEvent = MouseEvent | KeyboardEvent;
export type CloseType = (event: MouseOrKeyboardEvent) => void;
export type ModalProps = {
  allowFullscreen: boolean,
  isFullscreen: boolean,
  onClose: CloseType,
  preventScroll: boolean,
  toggleFullscreen: any => void,
};

export type Props = {
  /* Enable/disable the ability to "fullscreen" the dialog */
  allowFullscreen: boolean,
  /* Carousel only supported */
  children: CarouselType,
  /* Enable/disable calling `onClose` when the backdrop is clicked */
  closeOnBackdropClick: boolean,
  /* Enable/disable calling `onClose` when the `esc` key is pressed */
  closeOnEsc: boolean,
  /* Replace any of the modal components */
  components?: ModalComponents,
  /*
    Show the component; triggers the enter or exit states
    NOTE: provided by TransitionGroup, NOT supplied by the user
  */
  in: boolean,
  /* Function called to request close of the modal */
  onClose: CloseType,
  /* Prevent scroll */
  preventScroll: Boolean,
  /* Style modifier methods */
  styles: ModalStylesConfig,
};
type State = { isFullscreen: boolean };
const defaultProps = {
  allowFullscreen: !isTouch(),
  closeOnBackdropClick: true,
  closeOnEsc: true,
  preventScroll: true,
  styles: {},
};

/** Classes that when clicked on, close the backdrop */
const backdropClassNames = new Set(
  [
    viewBaseClassName,
    headerBaseClassName,
    footerBaseClassName,
    trackBaseClassName,
  ].map(className),
);

class Modal extends Component<Props, State> {
  commonProps: any; // TODO
  components: ModalComponents;

  static defaultProps = defaultProps;

  constructor(props: Props) {
    super(props);

    this.cacheComponents(props.components);

    this.state = { isFullscreen: false };
  }

  componentDidUpdate(prevProps: Props) {
    if (prevProps.components !== this.props.components) {
      this.cacheComponents(prevProps.components);
    }
  }

  // emulate `componentDidMount` & `componentWillUnmount`
  // called on complete of enter & exit transitions respectively
  modalDidMount = () => {
    document.addEventListener('keyup', this.handleKeyUp);
    focusStore.storeFocus();
  };
  modalWillUnmount = () => {
    document.removeEventListener('keyup', this.handleKeyUp);
    focusStore.restoreFocus();
  };

  cacheComponents = (comps?: ModalComponents) => {
    this.components = defaultModalComponents(comps);
  };
  handleFullscreenChange = (isFullscreen: boolean) => {
    this.setState({ isFullscreen });
  };
  handleKeyUp = (event: KeyboardEvent) => {
    const { allowFullscreen, closeOnEsc } = this.props;
    const { isFullscreen } = this.state;
    const allowClose = event.key === 'Escape' && closeOnEsc && !isFullscreen;

    // toggle fullscreen
    if (allowFullscreen && event.key === 'f') {
      this.toggleFullscreen();
    }

    // close on escape when not fullscreen
    if (allowClose) this.handleClose(event);
  };
  handleBackdropClick = (event: MouseEvent) => {
    let hasBackdropClassName = false;
    for (const targetClass of event.target.classList) {
      if (backdropClassNames.has(targetClass)) {
        hasBackdropClassName = true;
      }
    }

    if (!hasBackdropClassName || !this.props.closeOnBackdropClick) {
      return;
    }

    this.handleClose(event);
  };
  toggleFullscreen = () => {
    this.setState(state => ({ isFullscreen: !state.isFullscreen }));
  };
  handleClose = (event: MouseOrKeyboardEvent) => {
    const { onClose } = this.props;
    const { isFullscreen } = this.state;

    // force exit fullscreen mode on close
    if (isFullscreen) {
      this.toggleFullscreen();
    }

    // call the consumer's onClose func
    onClose(event);
  };

  getStyles = (key: string, props: {}): {} => {
    const base = defaultModalStyles[key](props);
    base.boxSizing = 'border-box';
    const custom = this.props.styles[key];
    return custom ? custom(base, props) : base;
  };
  getCommonProps() {
    const { isFullscreen } = this.state;

    return {
      getStyles: this.getStyles,
      isFullscreen,
      modalProps: this.props,
    };
  }
  render() {
    const { Blanket, Positioner, Dialog } = this.components;
    const { allowFullscreen, children, preventScroll } = this.props;
    const { isFullscreen } = this.state;
    const commonProps = (this.commonProps = this.getCommonProps());

    // $FlowFixMe
    const transitionIn = this.props.in;

    // forward props to modal for use in internal components
    const modalProps: ModalProps = {
      allowFullscreen,
      isFullscreen,
      onClose: this.handleClose,
      preventScroll: this.preventScroll,
      toggleFullscreen: this.toggleFullscreen,
    };

    // augment user carousel with modal props
    // $FlowFixMe
    const carouselComponent: CarouselType = cloneElement(children, {
      isModal: true,
      modalProps,
    });

    return (
      <Fullscreen enabled={isFullscreen} onChange={this.handleFullscreenChange}>
        <Fade {...commonProps} component={Blanket} in={transitionIn} />
        <SlideUp
          {...commonProps}
          component={Positioner}
          in={transitionIn}
          innerProps={{
            onClick: this.handleBackdropClick,
          }}
          onEntered={this.modalDidMount}
          onExited={this.modalWillUnmount}
        >
          <Dialog {...commonProps}>{carouselComponent}</Dialog>
          {preventScroll && <ScrollLock />}
        </SlideUp>
      </Fullscreen>
    );
  }
}
export default Modal;
export type ModalType = typeof Modal;
<|endoftext|>


<commit_before>function test(name, path) {
    describe(name, function () {
        require(path);
    });
}

describe('#dl-module', function (done) {
    this.timeout(2 * 60000);

    // Auth
    test('@AUTH/ACCOUNT', './auth/account');
    test('@AUTH/ROLE', './auth/role');
    test('@AUTH/API-ENDPOINT', './auth/api-endpoint');

    test('@ETL/DIM-CATEGORY', './etl/dim-category');
    test('@ETL/DIM-DIVISION', './etl/dim-division');
    test('@ETL/DIM-SUPPLIER', './etl/dim-supplier');
    test('@ETL/DIM-MACHINE', './etl/dim-machine');
    test('@ETL/DIM-UNIT', './etl/dim-unit');
    test('@ETL/FACT-TOTAL-HUTANG', './etl/fact-total-hutang');
    test('@ETL/FACT-PURCHASING', './etl/fact-purchasing');
    test('@ETL/FACT-MONITORING-EVENT', './etl/fact-monitoring-event');
    test('@ETL/FACT-SALES-CONTRACT', './etl/fact-sales-contract');

    // Master
    test('@MASTER/ACCOUNT-BANK', './master/account-bank');
    test('@MASTER/BUDGET', './master/budget');
    test('@MASTER/BUYER', './master/buyer');
    test('@MASTER/CATEGORY', './master/category');
    test('@MASTER/CURRENCY', './master/currency');
    test('@MASTER/DIVISION', './master/division');
    test('@MASTER/LAMP-STANDARD', './master/lamp-standard');
    test('@MASTER/LOT-MACHINE', './master/lot-machine');
    test('@MASTER/MACHINE', './master/machine');
    test('@MASTER/PRODUCT', './master/product');
    test('@MASTER/SUPPLIER', './master/supplier');
    test('@MASTER/THREAD-SPECIFICATION', './master/thread-specification');
    test('@MASTER/UNIT', './master/unit');
    test('@MASTER/UOM', './master/uom');
    test('@MASTER/USTER', './master/uster');
    test('@MASTER/VAT', './master/vat');
    test('@MASTER/YARN-EQUIVALENT-CONVERSION', './master/yarn-equivalent-coversion');
    test('@MASTER/ORDER-TYPE', './master/order-type');
    test('@MASTER/PROCESS-TYPE', './master/process-type');
    test('@MASTER/COLOR-TYPE', './master/color-type');
    test('@MASTER/INSTRUCTION', './master/instruction');

    // test('@MASTER/MONITORING-EVENT-TYPE', './master/monitoring-event-type');
    test('@MASTER/STEP', './master/step');
    // test('@MASTER/MACHINE-TYPE', './master/machine-type');
    test('@MASTER/MACHINE-SPESIFICATION-STANDARD', './master/machine-spesification-standard');
    test('@MASTER/MATERIAL-CONSTRUCTION', './master/material-construction');
    test('@MASTER/YARN-MATERIAL', './master/yarn-material');
    test('@MASTER/STANDARD-TEST', './master/standard-test');
    test('@MASTER/FINISH-TYPE', './master/finish-type');

    //Purchasing
    test('@PURCHASING/PURCHASE REQUEST', './purchasing/purchase-request');
    test('@PURCHASING/PURCHASE ORDER', './purchasing/purchase-order');
    test('@PURCHASING/PURCHASE ORDER EXTERNAL', './purchasing/purchase-order-external');
    test('@PURCHASING/DELIVERY ORDER', './purchasing/delivery-order');
    test('@PURCHASING/UNIT RECEIPT NOTE', './purchasing/unit-receipt-note');
    test('@PURCHASING/UNIT PAYMENT ORDER', './purchasing/unit-payment-order');
    test('@PURCHASING/UNIT PAYMENT PRICE CORRECTION', './purchasing/unit-payment-price-correction-note');
    test('@PURCHASING/UNIT PAYMENT QUANTITY CORRECTION', './purchasing/unit-payment-quantity-correction-note');

    test('@purchasing/purchase-order/report', './purchasing/purchase-order/report/report');
    //Production

    //test('@sales/production-order', './sales/production-order/create');

    // test('@production/daily-operation', './production/finishing-printing/daily-operation');
    // test('@production/finishing-printing/monitoring-specification-machine', './production/finishing-printing/monitoring-specification-machine');
    // test('@PRODUCTION/MONITORING-EVENT', './production/finishing-printing/monitoring-event');

    // test('@production/winding-quality-sampling-manager', './production/spinning/winding/winding-quality-sampling-manager-test');
    // test('@production/winding-production-output-manager', './production/spinning/winding/winding-production-output-manager-test');

    //Sales
    test('@production/production-order', './sales/production-order');
});
<commit_msg>comment instruction<commit_after>function test(name, path) {
    describe(name, function () {
        require(path);
    });
}

describe('#dl-module', function (done) {
    this.timeout(2 * 60000);

    // Auth
    test('@AUTH/ACCOUNT', './auth/account');
    test('@AUTH/ROLE', './auth/role');
    test('@AUTH/API-ENDPOINT', './auth/api-endpoint');

    test('@ETL/DIM-CATEGORY', './etl/dim-category');
    test('@ETL/DIM-DIVISION', './etl/dim-division');
    test('@ETL/DIM-SUPPLIER', './etl/dim-supplier');
    test('@ETL/DIM-MACHINE', './etl/dim-machine');
    test('@ETL/DIM-UNIT', './etl/dim-unit');
    test('@ETL/FACT-TOTAL-HUTANG', './etl/fact-total-hutang');
    test('@ETL/FACT-PURCHASING', './etl/fact-purchasing');
    test('@ETL/FACT-MONITORING-EVENT', './etl/fact-monitoring-event');
    test('@ETL/FACT-SALES-CONTRACT', './etl/fact-sales-contract');

    // Master
    test('@MASTER/ACCOUNT-BANK', './master/account-bank');
    test('@MASTER/BUDGET', './master/budget');
    test('@MASTER/BUYER', './master/buyer');
    test('@MASTER/CATEGORY', './master/category');
    test('@MASTER/CURRENCY', './master/currency');
    test('@MASTER/DIVISION', './master/division');
    test('@MASTER/LAMP-STANDARD', './master/lamp-standard');
    test('@MASTER/LOT-MACHINE', './master/lot-machine');
    test('@MASTER/MACHINE', './master/machine');
    test('@MASTER/PRODUCT', './master/product');
    test('@MASTER/SUPPLIER', './master/supplier');
    test('@MASTER/THREAD-SPECIFICATION', './master/thread-specification');
    test('@MASTER/UNIT', './master/unit');
    test('@MASTER/UOM', './master/uom');
    test('@MASTER/USTER', './master/uster');
    test('@MASTER/VAT', './master/vat');
    test('@MASTER/YARN-EQUIVALENT-CONVERSION', './master/yarn-equivalent-coversion');
    test('@MASTER/ORDER-TYPE', './master/order-type');
    test('@MASTER/PROCESS-TYPE', './master/process-type');
    test('@MASTER/COLOR-TYPE', './master/color-type');
    // test('@MASTER/INSTRUCTION', './master/instruction');

    // test('@MASTER/MONITORING-EVENT-TYPE', './master/monitoring-event-type');
    test('@MASTER/STEP', './master/step');
    // test('@MASTER/MACHINE-TYPE', './master/machine-type');
    test('@MASTER/MACHINE-SPESIFICATION-STANDARD', './master/machine-spesification-standard');
    test('@MASTER/MATERIAL-CONSTRUCTION', './master/material-construction');
    test('@MASTER/YARN-MATERIAL', './master/yarn-material');
    test('@MASTER/STANDARD-TEST', './master/standard-test');
    test('@MASTER/FINISH-TYPE', './master/finish-type');

    //Purchasing
    test('@PURCHASING/PURCHASE REQUEST', './purchasing/purchase-request');
    test('@PURCHASING/PURCHASE ORDER', './purchasing/purchase-order');
    test('@PURCHASING/PURCHASE ORDER EXTERNAL', './purchasing/purchase-order-external');
    test('@PURCHASING/DELIVERY ORDER', './purchasing/delivery-order');
    test('@PURCHASING/UNIT RECEIPT NOTE', './purchasing/unit-receipt-note');
    test('@PURCHASING/UNIT PAYMENT ORDER', './purchasing/unit-payment-order');
    test('@PURCHASING/UNIT PAYMENT PRICE CORRECTION', './purchasing/unit-payment-price-correction-note');
    test('@PURCHASING/UNIT PAYMENT QUANTITY CORRECTION', './purchasing/unit-payment-quantity-correction-note');

    test('@purchasing/purchase-order/report', './purchasing/purchase-order/report/report');
    //Production

    //test('@sales/production-order', './sales/production-order/create');

    // test('@production/daily-operation', './production/finishing-printing/daily-operation');
    // test('@production/finishing-printing/monitoring-specification-machine', './production/finishing-printing/monitoring-specification-machine');
    // test('@PRODUCTION/MONITORING-EVENT', './production/finishing-printing/monitoring-event');

    // test('@production/winding-quality-sampling-manager', './production/spinning/winding/winding-quality-sampling-manager-test');
    // test('@production/winding-production-output-manager', './production/spinning/winding/winding-production-output-manager-test');

    //Sales
    test('@production/production-order', './sales/production-order');
});
<|endoftext|>


<commit_before>'use strict';
const request         = require('../comum/tago_request.js');
const config          = require('../config.js');
const default_headers = require('../comum/default_headers.js');
const Realtime        = require('./../utils/').realtime;

/** Class for the device and data */
class Device {
    /** Device
     * @param  {String} Device Token
     * @param  {Boolean} Show Details
     * @return {Object} Device Object
     */
    constructor(token, details) {
        this.token   = token;
        this.default_options = {
            'json': true,
            'headers': default_headers(this)
        };

        if (details) {
            this.default_options.qs = {'details': true};
        }
    }

    /** Info
     * Get information about the current device
     * @return {Promise}
     */
    info() {
        let url    = `${config.api_url}/info`;
        let method = 'GET';

        let options = Object.assign({}, this.default_options, {url, method});
        return request(options);
    }

    /** Insert
     * @param  {Object|Array} data
     * @return {Promise}
     */
    insert(data) {
        data       = data || {};
        let url    = `${config.api_url}/data`;
        let method = 'POST';

        let options = Object.assign({}, this.default_options, {url, method, data});
        return request(options);
    }

    /** Edit
     * @param  {string} variable_id
     * @param  {Object} data
     * @return {Promise}
     */
    edit(variable_id, data) {
        data       = data || {};
        let url    = `${config.api_url}/data/${variable_id}`;
        let method = 'PUT';

        let options = Object.assign({}, this.default_options, {url, method, data});
        return request(options);
    }

    /** Find
     * @class
     * @param  {JSON} query object
     * @return {Promise}
     */
    find(query_obj) {
        query_obj  = query_obj || {};
        let url    = `${config.api_url}/data`;
        let method = 'GET';
        let params = Object.assign({}, this.default_options.qs || {}, query_obj);

        let options = Object.assign({}, this.default_options, {url, method, params});

        return request(options);
    }

    /** remove
     * @param  {string} variable_or_id
     * @param  {number} [qty] default is 1
     * @return {Promise}
     */
    remove(variable_or_id, qty) {
        let url    = `${config.api_url}/data`;
        if (variable_or_id) {
            url += `/${variable_or_id}`;
        }

        let params = Object.assign({}, this.default_options.qs || {}, qty ? {qty} : {});
        let method = 'DELETE';

        let options = Object.assign({}, this.default_options, {url, method, params});

        return request(options);
    }

     /** Get Parameters
     * @return {Promise}
     */
    getParams(sent_status) {
        let url     = `${config.api_url}/device/params`;
        let method  = 'GET';
        let params  = {
            sent_status
        };
        let options = Object.assign({}, this.default_options, {url, method, params});
        return request(options);
    }

    /** Mark Parameters as sent
     * @param  {String} param_id Id of the parameter
     * @return {Promise}
     */
    markParam(param_id) {
        let url     = `${config.api_url}/device/params/${param_id}`;
        let method  = 'PUT';
        let options = Object.assign({}, this.default_options, {url, method});
        return request(options);
    }

     /** Listen to device socket
     * @param  {function} callback to be executable
     * @return {function}
     */
    listening(callback) {
        this.realtime = new Realtime(this.token);
        this.realtime.get_socket.on('data', callback);
        this.realtime.register = (result) => {
            if (result.error) return console.log(result.error);
            console.log(result.message);
        };
        return Promise.resolve('Trying to listen to the device');
    }

    /** Stop to Listen the device */
    stopListening() {
        if (this.realtime) {
            this.realtime.get_socket.off('data');
            return Promise.resolve('Not listening to the device anymore');
        }
        return Promise.reject('Use .listening before trying to stop listening');
    }
}

module.exports = Device;
<commit_msg>Removed edit function for data<commit_after>'use strict';
const request         = require('../comum/tago_request.js');
const config          = require('../config.js');
const default_headers = require('../comum/default_headers.js');
const Realtime        = require('./../utils/').realtime;

/** Class for the device and data */
class Device {
    /** Device
     * @param  {String} Device Token
     * @param  {Boolean} Show Details
     * @return {Object} Device Object
     */
    constructor(token, details) {
        this.token   = token;
        this.default_options = {
            'json': true,
            'headers': default_headers(this)
        };

        if (details) {
            this.default_options.qs = {'details': true};
        }
    }

    /** Info
     * Get information about the current device
     * @return {Promise}
     */
    info() {
        let url    = `${config.api_url}/info`;
        let method = 'GET';

        let options = Object.assign({}, this.default_options, {url, method});
        return request(options);
    }

    /** Insert
     * @param  {Object|Array} data
     * @return {Promise}
     */
    insert(data) {
        data       = data || {};
        let url    = `${config.api_url}/data`;
        let method = 'POST';

        let options = Object.assign({}, this.default_options, {url, method, data});
        return request(options);
    }

    /** Find
     * @class
     * @param  {JSON} query object
     * @return {Promise}
     */
    find(query_obj) {
        query_obj  = query_obj || {};
        let url    = `${config.api_url}/data`;
        let method = 'GET';
        let params = Object.assign({}, this.default_options.qs || {}, query_obj);

        let options = Object.assign({}, this.default_options, {url, method, params});

        return request(options);
    }

    /** remove
     * @param  {string} variable_or_id
     * @param  {number} [qty] default is 1
     * @return {Promise}
     */
    remove(variable_or_id, qty) {
        let url    = `${config.api_url}/data`;
        if (variable_or_id) {
            url += `/${variable_or_id}`;
        }

        let params = Object.assign({}, this.default_options.qs || {}, qty ? {qty} : {});
        let method = 'DELETE';

        let options = Object.assign({}, this.default_options, {url, method, params});

        return request(options);
    }

     /** Get Parameters
     * @return {Promise}
     */
    getParams(sent_status) {
        let url     = `${config.api_url}/device/params`;
        let method  = 'GET';
        let params  = {
            sent_status
        };
        let options = Object.assign({}, this.default_options, {url, method, params});
        return request(options);
    }

    /** Mark Parameters as sent
     * @param  {String} param_id Id of the parameter
     * @return {Promise}
     */
    markParam(param_id) {
        let url     = `${config.api_url}/device/params/${param_id}`;
        let method  = 'PUT';
        let options = Object.assign({}, this.default_options, {url, method});
        return request(options);
    }

     /** Listen to device socket
     * @param  {function} callback to be executable
     * @return {function}
     */
    listening(callback) {
        this.realtime = new Realtime(this.token);
        this.realtime.get_socket.on('data', callback);
        this.realtime.register = (result) => {
            if (result.error) return console.log(result.error);
            console.log(result.message);
        };
        return Promise.resolve('Trying to listen to the device');
    }

    /** Stop to Listen the device */
    stopListening() {
        if (this.realtime) {
            this.realtime.get_socket.off('data');
            return Promise.resolve('Not listening to the device anymore');
        }
        return Promise.reject('Use .listening before trying to stop listening');
    }
}

module.exports = Device;
<|endoftext|>