<commit_before>import React, { PropTypes } from 'react'
import { BaseComponent } from 'shared/components'
import GMap from 'shared/components/addon/maps/gmap'
import { isEmpty } from 'lodash'
import moment from 'moment'
import { getFileName, getFileExt } from 'shared/utils/file-utils'
import classNames from 'classnames'
import { PostPropArray } from 'shared/utils/forms'
import { at } from 'lodash'
import counterpart from 'counterpart'
import { Link } from 'react-router'
import { fixLocaleName, originLocaleName } from 'shared/utils/locale-utils'
import AutoLinkText from 'react-autolink-text'
import ADContent from './ADContent'
import Carousel from 'nuka-carousel'
import { Lightbox } from 'shared/components/addon/lightbox'
import {
  toMoment,
  isBetween,
  isPastDay,
  toShortDate,
  toYear
} from 'shared/utils/date-utils'

let swal
if (process.env.BROWSER) {
  swal = require('sweetalert')
}

export default class Post extends BaseComponent {

  static propTypes = {
    auth: PropTypes.object.isRequired,
    post: PropTypes.object.isRequired,
    moreList: PropTypes.object.isRequired,
    map: PropTypes.object.isRequired,
    remove: PropTypes.func.isRequired,
    defaultLocale: PropTypes.string.isRequired
  }

  static contextTypes = {
    history: PropTypes.object.isRequired
  }

  constructor (props) {
    super(props)

    counterpart.setLocale(props.defaultLocale)

    this.state = {
      locale: fixLocaleName(counterpart.getLocale())
    }

    counterpart.onLocaleChange(::this.handleLocaleChange)
    this.releaseTimeout = undefined
  }

  componentWillUnmount () {
    if (this.op) {
      clearTimeout(this.releaseTimeout)
    }
  }

  removeTags (html) {
    const pattern = /(<([^>]+)>)/ig;
    return html.replace(pattern , '')
  }

  parseContent (content) {
    const ent = require('ent')
    if (content) {
      return (
        content.replace(/^\"|\"$/g, '').split('\n').map((t) => {
          return t === ''
            ?

            :
<AutoLinkText text={ent.decode(this.removeTags(t))}/>

        })
      )
    }
  }

  deletePost () {
    const _t = require('counterpart')
    const { detail } = this.props.post
    const { remove } = this.props
    const { transitionTo, createLocation } = this.context.history
    swal({
      title: _t('post.detail.delete.title'),
      text: _t('post.detail.delete.text'),
      type: 'warning',
      showCancelButton: true,
      confirmButtonText: _t('post.detail.delete.confirm'),
      cancelButtonText: _t('post.detail.delete.cancel'),
      closeOnConfirm: false,
      showLoaderOnConfirm: true
    }, () => {
      Promise.all([
        remove(detail.id)
      ]).then((res) => {
        if (res[0].type === 'REMOVE_POST_COMPLETED') {
          swal({
            title: _t('post.detail.delete.ok.title'),
            text: _t('post.detail.delete.ok.text'),
            type: 'success',
            confirmButtonText: _t('post.detail.delete.ok.confirm'),
            closeOnConfirm: true
          }, () => {
            transitionTo(createLocation('/w'))
          })
        } else {
          swal(_t('post.detail.delete.err.title')
            , _t('post.detail.delete.err.text'),
            'error')
        }
      })
    })
  }

  handleImgClick (src, event) {
    Lightbox.show(

    )
  }

  handleLocaleChange () {
    if (process.env.BROWSER) {
      this.forceUpdate()
    }
  }

  renderDetailProp (detail) {
    return (

        {at(PostPropArray(originLocaleName(counterpart.getLocale())), detail.prop)}

    )
  }

  renderRegisterInfo (detail) {
    if (!detail.url) return

    const Translate = require('react-translate-component')
    const open = toMoment(detail.openDate)
    const close = toMoment(detail.closeDate)
    const now = moment()

    if (now.isBetween(open, close)) {
      return (

            <Translate content="post.detail.open" />

      )
    } else if (now.isAfter(close)) {
      return (

            <Translate content="post.detail.close" />

      )
    }
  }

  renderImageAttachments () {
    const { detail } = this.props.post
    const files = typeof detail.file !== 'undefined'
      ? JSON.parse(detail.file)
      : []

    const imgs = []
    files && files.map(function (file) {
      if (getFileExt(file) !== 'pdf') {
        imgs.push(file)
      }
    })
    if (!isEmpty(imgs)) {
      return (

          <Carousel cellAlign="center" slideWidth="300px">
          {
            imgs.map(function (link) {
              if (getFileExt(link) !== 'pdf') {
                const src = '/uploads/' + link
                return (

                )
              } else {
                return (
)
              }
            }.bind(this))
          }
          </Carousel>

      )
    }

    return (

    )
  }

  renderMoreList () {
    const { posts } = this.props.moreList
    return (

        {this.props.moreList.isFetching &&

        }

          { !isEmpty(posts) && posts.map(function (item, i) {
            return (
              <Link className="item" to={`/w/${item.id}`}>

                    { toShortDate(item.startDate) }

                  { item.title }

              </Link>
            )})
          }

    )
  }

  render () {
    const Translate = require('react-translate-component')

    if (!isEmpty(this.props.post.errors)) {
      return (

              <Translate content="post.detail.noexist" />

      )
    } else {
      const { detail } = this.props.post
      const { content } = detail
      const files = typeof detail.file !== 'undefined'
        ? JSON.parse(detail.file)
        : []

      const detailClass = classNames('content', { hide: !detail.id })

      const finalContent = this.parseContent(content)

      const eventDate = (detail.startDate === detail.endDate)
      ? toShortDate(detail.endDate)
      : toShortDate(detail.startDate) + ' - ' + toShortDate(detail.endDate)

      let eventEndYear =
        toYear(detail.endDate) > toYear(new Date())
        ? toYear(detail.endDate)
        : null

      const eventStartYear =
        toYear(detail.startDate) < toYear(new Date())
        ? toYear(detail.startDate)
        : null

      if (eventStartYear && toYear(detail.endDate) === toYear(new Date())) {
        eventEndYear = <Translate content="post.detail.this_year" />
      }

      const mainClasses = classNames(
        'ui',
        'two',
        'column',
        'post',
        'detail',
        'stackable',
        'has-header',
        'grid',
        'container'
      )

      const directionMode = true

      return (

                  {this.props.post.isFetching && !detail.id &&

                  }

                    {eventDate && (

                          {eventDate}

                      )}

                      {eventStartYear && (

                          {eventStartYear}
                          { eventEndYear
                            && <Translate content="post.detail.start" /> }

                      )}
                      {eventEndYear && (

                            <Translate content="post.detail.end" /> {eventEndYear}

                      )}

                      {detail.title}

                      {finalContent}
                      { files && !isEmpty(files)
                        &&

                          <Translate content="post.detail.attachments" />

 }

                      {
                        files && !isEmpty(files)
                        && files.map(function (file, i) {
                          return (

                                      { getFileName(file) }

                          )
                        })
                      }

                        {this.renderDetailProp(detail)}

                  {!isEmpty(detail.uid)
                    && this.props.auth.user.id === detail.uid &&

                      <Link
                        className="ui basic green button"
                        to={`/post/${detail.id}/edit`}>
                        <Translate content="post.detail.edit" />
                      </Link>

                        <Translate content="post.detail.delete.confirm" />

                  }

                { this.renderImageAttachments() }

                {this.renderRegisterInfo(detail)}

              {detail.cid && (

                <Link
                  className="ui orange fluid large top attached button"
                  to={`/c/${detail.cid}`}>
                  {detail.ocname}
                </Link>

              )}

                { (detail.lat && detail.lat) &&
                <GMap
                  ref="gmap"
                  {...this.props.map}
                  directionMode={directionMode}
                  defaultLocale={this.props.defaultLocale}
                />
                }
                {this.renderMoreList()}

                <ADContent />

      )
    }
  }
}
<commit_msg>edit mode always selected first tab<commit_after>import React, { PropTypes } from 'react'
import { BaseComponent } from 'shared/components'
import GMap from 'shared/components/addon/maps/gmap'
import { isEmpty } from 'lodash'
import moment from 'moment'
import { getFileName, getFileExt } from 'shared/utils/file-utils'
import classNames from 'classnames'
import { PostPropArray } from 'shared/utils/forms'
import { at } from 'lodash'
import counterpart from 'counterpart'
import { Link } from 'react-router'
import { fixLocaleName, originLocaleName } from 'shared/utils/locale-utils'
import AutoLinkText from 'react-autolink-text'
import ADContent from './ADContent'
import Carousel from 'nuka-carousel'
import { Lightbox } from 'shared/components/addon/lightbox'
import {
  toMoment,
  isBetween,
  isPastDay,
  toShortDate,
  toYear
} from 'shared/utils/date-utils'

let swal
if (process.env.BROWSER) {
  swal = require('sweetalert')
}

export default class Post extends BaseComponent {

  static propTypes = {
    auth: PropTypes.object.isRequired,
    post: PropTypes.object.isRequired,
    moreList: PropTypes.object.isRequired,
    map: PropTypes.object.isRequired,
    remove: PropTypes.func.isRequired,
    defaultLocale: PropTypes.string.isRequired
  }

  static contextTypes = {
    history: PropTypes.object.isRequired
  }

  constructor (props) {
    super(props)

    counterpart.setLocale(props.defaultLocale)

    this.state = {
      locale: fixLocaleName(counterpart.getLocale())
    }

    counterpart.onLocaleChange(::this.handleLocaleChange)
    this.releaseTimeout = undefined
  }

  componentWillUnmount () {
    if (this.op) {
      clearTimeout(this.releaseTimeout)
    }
  }

  removeTags (html) {
    const pattern = /(<([^>]+)>)/ig;
    return html.replace(pattern , '')
  }

  parseContent (content) {
    const ent = require('ent')
    if (content) {
      return (
        content.replace(/^\"|\"$/g, '').split('\n').map((t) => {
          return t === ''
            ?

            :
<AutoLinkText text={ent.decode(this.removeTags(t))}/>

        })
      )
    }
  }

  deletePost () {
    const _t = require('counterpart')
    const { detail } = this.props.post
    const { remove } = this.props
    const { transitionTo, createLocation } = this.context.history
    swal({
      title: _t('post.detail.delete.title'),
      text: _t('post.detail.delete.text'),
      type: 'warning',
      showCancelButton: true,
      confirmButtonText: _t('post.detail.delete.confirm'),
      cancelButtonText: _t('post.detail.delete.cancel'),
      closeOnConfirm: false,
      showLoaderOnConfirm: true
    }, () => {
      Promise.all([
        remove(detail.id)
      ]).then((res) => {
        if (res[0].type === 'REMOVE_POST_COMPLETED') {
          swal({
            title: _t('post.detail.delete.ok.title'),
            text: _t('post.detail.delete.ok.text'),
            type: 'success',
            confirmButtonText: _t('post.detail.delete.ok.confirm'),
            closeOnConfirm: true
          }, () => {
            transitionTo(createLocation('/w'))
          })
        } else {
          swal(_t('post.detail.delete.err.title')
            , _t('post.detail.delete.err.text'),
            'error')
        }
      })
    })
  }

  handleImgClick (src, event) {
    Lightbox.show(

    )
  }

  handleLocaleChange () {
    if (process.env.BROWSER) {
      this.forceUpdate()
    }
  }

  renderDetailProp (detail) {
    return (

        {at(PostPropArray(originLocaleName(counterpart.getLocale())), detail.prop)}

    )
  }

  renderRegisterInfo (detail) {
    if (!detail.url) return

    const Translate = require('react-translate-component')
    const open = toMoment(detail.openDate)
    const close = toMoment(detail.closeDate)
    const now = moment()

    if (now.isBetween(open, close)) {
      return (

            <Translate content="post.detail.open" />

      )
    } else if (now.isAfter(close)) {
      return (

            <Translate content="post.detail.close" />

      )
    }
  }

  renderImageAttachments () {
    const { detail } = this.props.post
    const files = typeof detail.file !== 'undefined'
      ? JSON.parse(detail.file)
      : []

    const imgs = []
    files && files.map(function (file) {
      if (getFileExt(file) !== 'pdf') {
        imgs.push(file)
      }
    })
    if (!isEmpty(imgs)) {
      return (

          <Carousel cellAlign="center" slideWidth="300px">
          {
            imgs.map(function (link) {
              if (getFileExt(link) !== 'pdf') {
                const src = '/uploads/' + link
                return (

                )
              } else {
                return (
)
              }
            }.bind(this))
          }
          </Carousel>

      )
    }

    return (

    )
  }

  renderMoreList () {
    const { posts } = this.props.moreList
    return (

        {this.props.moreList.isFetching &&

        }

          { !isEmpty(posts) && posts.map(function (item, i) {
            return (
              <Link className="item" to={`/w/${item.id}`}>

                    { toShortDate(item.startDate) }

                  { item.title }

              </Link>
            )})
          }

    )
  }

  render () {
    const Translate = require('react-translate-component')

    if (!isEmpty(this.props.post.errors)) {
      return (

              <Translate content="post.detail.noexist" />

      )
    } else {
      const { detail } = this.props.post
      const { content } = detail
      const files = typeof detail.file !== 'undefined'
        ? JSON.parse(detail.file)
        : []

      const detailClass = classNames('content', { hide: !detail.id })

      const finalContent = this.parseContent(content)

      const eventDate = (detail.startDate === detail.endDate)
      ? toShortDate(detail.endDate)
      : toShortDate(detail.startDate) + ' - ' + toShortDate(detail.endDate)

      let eventEndYear =
        toYear(detail.endDate) > toYear(new Date())
        ? toYear(detail.endDate)
        : null

      const eventStartYear =
        toYear(detail.startDate) < toYear(new Date())
        ? toYear(detail.startDate)
        : null

      if (eventStartYear && toYear(detail.endDate) === toYear(new Date())) {
        eventEndYear = <Translate content="post.detail.this_year" />
      }

      const mainClasses = classNames(
        'ui',
        'two',
        'column',
        'post',
        'detail',
        'stackable',
        'has-header',
        'grid',
        'container'
      )

      const directionMode = true

      return (

                  {this.props.post.isFetching && !detail.id &&

                  }

                    {eventDate && (

                          {eventDate}

                      )}

                      {eventStartYear && (

                          {eventStartYear}
                          { eventEndYear
                            && <Translate content="post.detail.start" /> }

                      )}
                      {eventEndYear && (

                            <Translate content="post.detail.end" /> {eventEndYear}

                      )}

                      {detail.title}

                      {finalContent}
                      { files && !isEmpty(files)
                        &&

                          <Translate content="post.detail.attachments" />

 }

                      {
                        files && !isEmpty(files)
                        && files.map(function (file, i) {
                          return (

                                      { getFileName(file) }

                          )
                        })
                      }

                        {this.renderDetailProp(detail)}

                  {!isEmpty(detail.uid)
                    && this.props.auth.user.id === detail.uid &&

                      <Link
                        className="ui basic green button"
                        to={`/post/${detail.id}/edit?tab=0`}>
                        <Translate content="post.detail.edit" />
                      </Link>

                        <Translate content="post.detail.delete.confirm" />

                  }

                { this.renderImageAttachments() }

                {this.renderRegisterInfo(detail)}

              {detail.cid && (

                <Link
                  className="ui orange fluid large top attached button"
                  to={`/c/${detail.cid}`}>
                  {detail.ocname}
                </Link>

              )}

                { (detail.lat && detail.lat) &&
                <GMap
                  ref="gmap"
                  {...this.props.map}
                  directionMode={directionMode}
                  defaultLocale={this.props.defaultLocale}
                />
                }
                {this.renderMoreList()}

                <ADContent />

      )
    }
  }
}
<|endoftext|>


<commit_before>import express from 'express'
const router = express.Router()

import { Subject, Card } from '../database/db'

router.get('/:id', (request, response, next ) => {
  const { id } = request.params
  console.log( 'subject', id )

  const query = [ Subject.find( id ), Card.findBySubjectId( id ) ]

  Promise.all( query )
    .then( result => {
      const [ subject, cards ] = result
      response.render( 'subjects', { subject, cards } )
    })

  Subject.find( id ).then( subject => {
    response.render('subjects', { subject })
  })
})

router.get('/new', (req, res, next) => {
  res.render('subjects/create')
})

router.post('/create-subject', ( request, response ) => {
  const { id } = request.user
  const { title } = request.body

  Subject.create( title, id ).then( result => {
    res.redirect(`/subjects/${result.id}`)
  })
})

module.exports = router
<commit_msg>refactored changes<commit_after>import express from 'express'
const router = express.Router()

import { Subject, Card } from '../database/db'

router.get('/:id', (request, response, next ) => {
  const { id } = request.params
  const query = [ Subject.find( id ), Card.findBySubjectId( id ) ]

  Promise.all( query )
    .then( result => {
      const [ subject, cards ] = result
      response.render( 'subjects', { subject, cards } )
    })
})

router.get('/new', (req, res, next) => {
  res.render('subjects/create')
})

router.post('/create-subject', ( request, response ) => {
  const { id } = request.user
  const { title } = request.body

  Subject.create( title, id ).then( result => {
    res.redirect(`/subjects/${result.id}`)
  })
})

module.exports = router
<|endoftext|>


<commit_before>class Prom {
    // TODO - chaining

    constructor(promiseCb) {
        this._promiseCb = promiseCb;
        this._setPending();
        this._value = undefined;
        this._resolveCb = undefined;
        this._rejectCb = undefined;
    }

    then(resolveCb, rejectCb) {
        if (this._promiseCb && this._isPending()) {
            this._resolveCb = resolveCb;
            this._rejectCb = rejectCb;

            this._promiseCb(this._doResolve, this._doReject);
        }
    }

    catch(rejectCb) {
        return this.then(null, rejectCb);
    }

    static resolve(res) {
        if (res instanceof Prom) {
            return res;
        }

        return new Prom((resolve) => {
            resolve(res);
        });
    }

    static reject(res) {
        return new Prom((resolve, reject) => {
            reject(res);
        });
    }

    static race(promiseArr) {
        if (Array.isArray(promiseArr)) {
            return new Prom((resolve, reject) => {
                promiseArr.forEach((prom) => {
                    Prom.resolve(prom).then(resolve, reject);
                });
            });
        }

        return Prom.reject('Error: Prom.race\'s parameter must be an array');
    }

    static all(promiseArr) {
        if (Array.isArray(promiseArr)) {
            return new Prom((resolve, reject) => {
                let remaining = promiseArr.length;
                const results = [];

                if (remaining === 0) {
                    resolve(results);
                }
                else {
                    promiseArr.forEach((prom, i) => {
                        prom.then((result) => {
                            results[i] = result;

                            if (--remaining === 0) {
                                resolve(results);
                            }
                        }, (err) => {
                            resolve(reject(err));
                        });
                    });
                }
            });
        }

        return Prom.reject('Error: Prom.all\'s parameter must be an array');
    }

    _doResolve = (res) => {
        if (this._isPending()) {
            this._setResolved();
            this._value = res;

            if (typeof this._resolveCb === 'function') {
                this._resolveCb(res);
            }
        }
    }

    _doReject = (res) => {
        if (this._isPending()) {
            this._setRejected();
            this._value = res;

            if (typeof this._rejectCb === 'function') {
                this._rejectCb(res);
            }
            else {
                console.error(`Uncaught (in promise) ${res}`);
            }
        }
    }

    _isPending = () => this._state === 0
    _isResolved = () => this._state === 1
    _isRejected = () => this._state === 2
    _setPending = () => { this._state = 0; }
    _setResolved = () => { this._state = 1; }
    _setRejected = () => { this._state = 2; }
}

/*
 * Test basic new Prom() functionality
 */
function testBasic() {
    return new Prom((resolve, reject) => {
        setTimeout(() => {
            const rand = Math.random();

            if (rand >= 0.5) {
                resolve(rand);
            }
            else {
                reject(rand);
            }
        }, 1000);
    });
}

testBasic().then((result) => {
    console.log('Basic Success', result);
}, (result) => {
    console.log('Basic Failure', result);
});

/*
 * Test Prom.resolve and Prom.reject
 */
function testStatic() {
    const rand = Math.random();

    if (rand >= 0.5) {
        return Prom.resolve(rand);
    }
    return Prom.reject(rand);
}

testStatic().then((result) => {
    console.log('Static Success', result);
}, (result) => {
    console.log('Static Failure', result);
});

/**
 * Test Prom.race
 */
function testRace() {
    const rand = Math.random();

    return [
        new Prom((resolve, reject) => {
            setTimeout(() => {
                if (rand >= 0.5) {
                    resolve('first');
                }
                else {
                    reject('first');
                }
            }, 2000);
        }),
        new Prom((resolve, reject) => {
            setTimeout(() => {
                if (rand >= 0.5) {
                    resolve('second');
                }
                else {
                    reject('second');
                }
            }, 1000);
        })
    ];
}

Prom.race(testRace()).then((result) => {
    console.log('Race Success', result);
}, (result) => {
    console.log('Race Failure', result);
});

/**
 * Test Prom.all
 */
function testAll() {
    const asyncCb = (resolve, reject) => {
        setTimeout(() => {
            const rand = Math.random();

            if (rand >= 0.5) {
                resolve(rand);
            }
            else {
                reject(rand);
            }
        }, 1000);
    };

    return [new Prom(asyncCb), new Prom(asyncCb)];
}

Prom.all(testAll()).then((results) => {
    console.log('All Success', results);
}, (results) => {
    console.log('All Failure', results);
});

/*
 * Test chaining
 */
// function testChaining() {
//     return new Prom((resolve, reject) => {
//         setTimeout(() => {
//             const rand = Math.random();

//             if (rand >= 0.5) {
//                 resolve(rand);
//             }
//             else {
//                 reject(rand);
//             }
//         }, 1000);
//     });
// }

// testChaining().then((result) => {
//     console.log('Chaining Success', result);
// }).then(undefined, (result) => {
//     console.log('Chaining Failure', result);
// });
<commit_msg>Change naming according to A+ spec<commit_after>class Prom {
    // TODO - chaining

    constructor(promiseCb) {
        this._promiseCb = promiseCb;
        this._setPending();
        this._value = undefined;
        this._reason = undefined;
        this._onFulfilled = undefined;
        this._onRejected = undefined;
    }

    then(onFulfilled, onRejected) {
        if (this._promiseCb && this._isPending()) {
            this._onFulfilled = onFulfilled;
            this._onRejected = onRejected;

            this._promiseCb(this._doFulfill, this._doReject);
        }
    }

    catch(onRejected) {
        return this.then(null, onRejected);
    }

    static resolve(value) {
        if (this._isProm(value)) {
            return value;
        }

        return new Prom((resolve) => {
            resolve(value);
        });
    }

    static reject(reason) {
        return new Prom((resolve, reject) => {
            reject(reason);
        });
    }

    static race(promiseArr) {
        if (Array.isArray(promiseArr)) {
            return new Prom((resolve, reject) => {
                promiseArr.forEach((prom) => {
                    Prom.resolve(prom).then(resolve, reject);
                });
            });
        }

        return Prom.reject('Error: Prom.race\'s parameter must be an array');
    }

    static all(promiseArr) {
        if (Array.isArray(promiseArr)) {
            return new Prom((resolve, reject) => {
                let remaining = promiseArr.length;
                const values = [];

                if (remaining === 0) {
                    resolve(values);
                }
                else {
                    promiseArr.forEach((prom, i) => {
                        prom.then((value) => {
                            values[i] = value;

                            if (--remaining === 0) {
                                resolve(values);
                            }
                        }, (reason) => {
                            resolve(reject(reason));
                        });
                    });
                }
            });
        }

        return Prom.reject('Error: Prom.all\'s parameter must be an array');
    }

    _doFulfill = (value) => {
        if (this._isPending()) {
            this._setFulfilled();
            this._value = value;

            if (typeof this._onFulfilled === 'function') {
                this._onFulfilled(value);
            }
        }
    }

    _doReject = (reason) => {
        if (this._isPending()) {
            this._setRejected();
            this._reason = reason;

            if (typeof this._onRejected === 'function') {
                this._onRejected(reason);
            }
            else {
                console.error(`Uncaught (in promise) ${reason}`);
            }
        }
    }

    _async = (cb) => {
        setTimeout(cb);
    }

    _isProm = (promise) => promise instanceof Prom;

    _isPending = () => this._state === 0;
    _isFulfilled = () => this._state === 1;
    _isRejected = () => this._state === 2;

    _setPending = () => { this._state = 0; }
    _setFulfilled = () => { this._state = 1; }
    _setRejected = () => { this._state = 2; }
}

/**
 * Test if promise is async
 * Success if the order is 1, 2, 3
 */
console.log('Test async', 1);
new Prom((resolve) => {
    resolve();
}).then(() => {
    console.log('Test async', 3);
});
console.log('Test async', 2);

/*
 * Test chaining
 * TODO
 */
// function testChaining() {
//     return new Prom((resolve, reject) => {
//         setTimeout(() => {
//             const rand = Math.random();

//             if (rand >= 0.5) {
//                 resolve(rand);
//             }
//             else {
//                 reject(rand);
//             }
//         }, 1000);
//     });
// }

// testChaining().then((result) => {
//     console.log('Chaining Success 1', result);
//     return result;
// }).then((result) => {
//     console.log('Chaining Failure 2', result);
// });

/*
 * Test basic new Prom() functionality
 */
function testBasic() {
    return new Prom((resolve, reject) => {
        setTimeout(() => {
            const rand = Math.random();

            if (rand >= 0.5) {
                resolve(rand);
            }
            else {
                reject(rand);
            }
        }, 1000);
    });
}

testBasic().then((result) => {
    console.log('Basic Success', result);
}, (result) => {
    console.log('Basic Failure', result);
});

/*
 * Test Prom.resolve and Prom.reject
 */
function testStatic() {
    const rand = Math.random();

    if (rand >= 0.5) {
        return Prom.resolve(rand);
    }
    return Prom.reject(rand);
}

testStatic().then((result) => {
    console.log('Static Success', result);
}, (result) => {
    console.log('Static Failure', result);
});

/**
 * Test Prom.race
 */
function testRace() {
    const rand = Math.random();

    return [
        new Prom((resolve, reject) => {
            setTimeout(() => {
                if (rand >= 0.5) {
                    resolve('first');
                }
                else {
                    reject('first');
                }
            }, 2000);
        }),
        new Prom((resolve, reject) => {
            setTimeout(() => {
                if (rand >= 0.5) {
                    resolve('second');
                }
                else {
                    reject('second');
                }
            }, 1000);
        })
    ];
}

Prom.race(testRace()).then((result) => {
    console.log('Race Success', result);
}, (result) => {
    console.log('Race Failure', result);
});

/**
 * Test Prom.all
 */
function testAll() {
    const asyncCb = (resolve, reject) => {
        setTimeout(() => {
            const rand = Math.random();

            if (rand >= 0.5) {
                resolve(rand);
            }
            else {
                reject(rand);
            }
        }, 1000);
    };

    return [new Prom(asyncCb), new Prom(asyncCb)];
}

Prom.all(testAll()).then((results) => {
    console.log('All Success', results);
}, (results) => {
    console.log('All Failure', results);
});

/**
 * Test - resolve rejected promise
 * TODO
 */
// new Prom((resolve) => {
//     resolve(Prom().reject(aa));
// }).then((result) => {
//     console.log('Success', result);
// }, (result) => {
//     console.log('Failure', result);
// });
<|endoftext|>


<commit_before>var io = require('socket.io')(4001);
var shuffle = require('shuffle-array');
var models = require('../../models/index');
const STATES = require('../../config/states');

//Seconds when the zivis should change
const MAX_TIME = 600;
//Every ten minutes update the client
var remaining = MAX_TIME;
setInterval(countDown, 1000);

//First load shuffle the zivis and set the order
shuffleAndUpdateZivis();

//Set the timeout on the first start and then every day after (86400000)
setPostInterval();
setInterval(setPostInterval, 86400000);
var lastPostZivi;

function countDown() {
  remaining--;
  io.sockets.emit('timer', {
    remaining: remaining
  });
  if (remaining === 0) {
    remaining = MAX_TIME;
    shuffleAndUpdateZivis();
  }
}

function shuffleAndUpdateZivis() {
  models.Zivi.find({}).then(function (result) {
    shuffle(result);
    result[0].first += 1;
    for (var i = 0; i < result.length; i++) {
      result[i].order = i + 1;
      result[i].save();
    }
  });
}

function setPostInterval() {
  var now = new Date();
  // don't do anything on the weekends
  if (now.getDay() == 6 || now.getDay() == 0) {
    return;
  }

  function millisUntilTime(hour, minute) {
    var millis = new Date(now.getFullYear(), now.getMonth(), now.getDate(), hour, minute, 0, 0) - now;
    if (millis < 0) { //already past this time today, set for tomorrow
      millis = new Date(now.getFullYear(), now.getMonth(), now.getDate() + 1, hour, minute, 0, 0) - now;
    }
    return millis;
  }

  setTimeout(changeStateToPrep, millisUntilTime(10, 45));
  setTimeout(changeStateToPrep, millisUntilTime(14, 45));
  setTimeout(changeStateToReminder, millisUntilTime(11, 10));
  setTimeout(changeStateToReminder, millisUntilTime(15, 10));
  setTimeout(changeStateToIdle, millisUntilTime(11, 30));
  setTimeout(changeStateToIdle, millisUntilTime(15, 30));
}

function changeStateToPrep() {
  models.Post.findOne({}).then(function (post) {
    //This should not happen, if everybody watches their shit
    //TODO: Uncomment
    /*if(post.state !== 'IDLE'){
     return console.log('Somebody missed the accept the post offer');
     }*/
    models.Zivi.find({
      name: {
        $ne: post.zivi ? post.zivi.name : ''
      }
    }).then(function (zivis) {
      shuffle(zivis);
      var chosenOne = zivis[0];

      post.state = STATES.PREPERATION;
      post.timestamp = new Date();
      post.zivi = chosenOne;

      post.save(function (err, result) {
        if (err) {
          return console.log('Something wrent wrong:', err);
        }
        sendPostUpdate();
      });

    });
  });
}

function changeStateToReminder() {
  models.Post.findOne({}).then(function (post) {
    if (post.state !== STATES.ACTION && post.state !== STATES.PREPERATION) {
      return console.log('Something went terribly wrong');
    }
    //User has accepted the request and is now back (probably) or forgot to accept the offer
    models.Zivi.findOne({name: post.zivi.name}).then(function (zivi) {
      zivi.post_count += 1;
      zivi.save(function (err) {
        if (err) {
          return console.log('Something went wrong on user update', err);
        }
        post.state = STATES.REMINDER;
        post.timestamp = new Date();
        post.save(function (err) {
          if (err) {
            return console.log('Something went wrong on post update', err);
          }
          sendPostUpdate();
        });
      });
    });

  });
}

function changeStateToIdle() {
  models.Post.findOne({}).then(function (post) {
    if (post.state !== STATES.REMINDER) {
      return console.log('Something went terribly wrong');
    }
    post.state = STATES.IDLE;
    post.timestamp = new Date();
    post.save(function (err) {
      if (err) {
        return console.log('Something went wrong on post update', err);
      }
      sendPostUpdate();
    });
  });
}

function sendPostUpdate() {
  io.sockets.emit('post', {
    update: 'state'
  });
}
<commit_msg>Don't change post state to idle if card reminder isn't dismissed<commit_after>var io = require('socket.io')(4001);
var shuffle = require('shuffle-array');
var models = require('../../models/index');
const STATES = require('../../config/states');

//Seconds when the zivis should change
const MAX_TIME = 600;
//Every ten minutes update the client
var remaining = MAX_TIME;
setInterval(countDown, 1000);

//First load shuffle the zivis and set the order
shuffleAndUpdateZivis();

//Set the timeout on the first start and then every day after (86400000)
setPostInterval();
setInterval(setPostInterval, 86400000);
var lastPostZivi;

function countDown() {
  remaining--;
  io.sockets.emit('timer', {
    remaining: remaining
  });
  if (remaining === 0) {
    remaining = MAX_TIME;
    shuffleAndUpdateZivis();
  }
}

function shuffleAndUpdateZivis() {
  models.Zivi.find({}).then(function (result) {
    shuffle(result);
    result[0].first += 1;
    for (var i = 0; i < result.length; i++) {
      result[i].order = i + 1;
      result[i].save();
    }
  });
}

function setPostInterval() {
  var now = new Date();
  // don't do anything on the weekends
  if (now.getDay() == 6 || now.getDay() == 0) {
    return;
  }

  function millisUntilTime(hour, minute) {
    var millis = new Date(now.getFullYear(), now.getMonth(), now.getDate(), hour, minute, 0, 0) - now;
    if (millis < 0) { //already past this time today, set for tomorrow
      millis = new Date(now.getFullYear(), now.getMonth(), now.getDate() + 1, hour, minute, 0, 0) - now;
    }
    return millis;
  }

  setTimeout(changeStateToPrep, millisUntilTime(10, 45));
  setTimeout(changeStateToPrep, millisUntilTime(14, 45));
  setTimeout(changeStateToReminder, millisUntilTime(11, 10));
  setTimeout(changeStateToReminder, millisUntilTime(15, 10));
}

function changeStateToPrep() {
  models.Post.findOne({}).then(function (post) {
    //This should not happen, if everybody watches their shit
    //TODO: Uncomment
    /*if(post.state !== 'IDLE'){
     return console.log('Somebody missed the accept the post offer');
     }*/
    models.Zivi.find({
      name: {
        $ne: post.zivi ? post.zivi.name : ''
      }
    }).then(function (zivis) {
      shuffle(zivis);
      var chosenOne = zivis[0];

      post.state = STATES.PREPERATION;
      post.timestamp = new Date();
      post.zivi = chosenOne;

      post.save(function (err, result) {
        if (err) {
          return console.log('Something wrent wrong:', err);
        }
        sendPostUpdate();
      });

    });
  });
}

function changeStateToReminder() {
  models.Post.findOne({}).then(function (post) {
    if (post.state !== STATES.ACTION && post.state !== STATES.PREPERATION) {
      return console.log('Something went terribly wrong');
    }
    //User has accepted the request and is now back (probably) or forgot to accept the offer
    models.Zivi.findOne({name: post.zivi.name}).then(function (zivi) {
      zivi.post_count += 1;
      zivi.save(function (err) {
        if (err) {
          return console.log('Something went wrong on user update', err);
        }
        post.state = STATES.REMINDER;
        post.timestamp = new Date();
        post.save(function (err) {
          if (err) {
            return console.log('Something went wrong on post update', err);
          }
          sendPostUpdate();
        });
      });
    });

  });
}

function changeStateToIdle() {
  models.Post.findOne({}).then(function (post) {
    if (post.state !== STATES.REMINDER) {
      return console.log('Something went terribly wrong');
    }
    post.state = STATES.IDLE;
    post.timestamp = new Date();
    post.save(function (err) {
      if (err) {
        return console.log('Something went wrong on post update', err);
      }
      sendPostUpdate();
    });
  });
}

function sendPostUpdate() {
  io.sockets.emit('post', {
    update: 'state'
  });
}
<|endoftext|>


<commit_before>#!/usr/bin/env node

import { install } from 'source-map-support';
install();

import 'babel-polyfill';
// Libs
import chalk from 'chalk';
import program from 'commander';
import fs from 'fs-extra';
import moment from 'moment';
import co from 'co';
import prompt from 'co-prompt';
import * as Utils from './utils';

program
  .version('0.0.1')
  .command('new [template]')
  .alias('n')
  .description('create a new note for the day')
  .action(function(template, cmd) {
    if(!template) {
      template = 'default';
    }
    const today = moment().format("DD-MM-YYYY");
    const yesterday = moment().subtract(1, 'day').format("DD-MM-YYYY");
    var configPath = `${process.env.HOME}/.nonoterc.json`;

    fs.readJson(configPath, (err, configObj) => {
      if (err) console.error(err)

      const notesDir = configObj.notesDirectory;
      const days = `${notesDir}/days/`;
      const todayPath = days + today;
      const yesterdayPath = days + yesterday;
      const yesterdayDataJSONPath= `${yesterdayPath}/data.json`;
      const dataJSONPath = `${todayPath}/data.json`;
      const noteMdPath = `${todayPath}/note.md`;

      const templateDataPath = `${notesDir}/templates/${template}.json`;

      fs.mkdirs(todayPath, (err) => {
        if (err) console.error(err)

        fs.copy(templateDataPath, dataJSONPath, (err) => {
          if (err) console.error(err)

          fs.readJson(yesterdayDataJSONPath, (err, yesterdayObj) => {
            let hasPreviousNote = true;
            let incompleteTasks = [];

            if (err && err.code === 'ENOENT') {
              hasPreviousNote = false;
            }

            if (hasPreviousNote) {
              incompleteTasks = Object.keys(yesterdayObj).map(section => {
                return yesterdayObj[section].items.filter(item => {
                  return item.status !== "complete"
                });
              })[0];
            }

            fs.readJson(dataJSONPath, (err, noteObj) => {
              console.log(`Creating new note from the ${chalk.green(template)} template...`);
              if (hasPreviousNote && incompleteTasks.length > 0) {
                console.log(`\nCopying ${chalk.cyan(incompleteTasks.length)} incomplete tasks from yesterday:`);
                incompleteTasks.forEach((task, i) => console.log(`   ${chalk.cyan(i)}.) ${task.description}`));
                const firstNote = Object.keys(noteObj)[0];
                const mergedItems = [ ...incompleteTasks, ...noteObj[firstNote].items ];
                noteObj[firstNote].items = mergedItems;
              }

              Utils.makeNote(noteObj);
              const watchCmd = 'nono watch';
              console.log(`\nGreat success! Here is your note for today: \n${chalk.cyan(noteMdPath)}`);
              console.log(`\nYou can see the note by running ${chalk.green(watchCmd)} anywhere in your console!`);
            });
          });
        });
      });
    });
  });

program
  .command('watch')
  .alias('w')
  .description('watches todays note')
  .action(function(){
    co(function *() {
      const today = moment().format("DD-MM-YYYY");
      var configPath = `${process.env.HOME}/.nonoterc.json`;
      fs.readJson(configPath, (err, configJSON) => {
        if (err) console.error(err)

        const notesDir = configJSON.notesDirectory;
        const days = `${notesDir}/days/`;
        const toDir = days + today;
        const noteMd = `${toDir}/note.md`;

        fs.access(noteMd, fs.constants.F_OK, (err) => {
          if (err && err.code === 'ENOENT') {
            const badNotePath = chalk.cyan(noteMd);
            const newNoteCmd = chalk.green('nono new');
            console.log(`
Oh man, oh jeez, ok, I-I-I can't access this note:
${badNotePath}

C-c-can you try m-m-making a new note or s-s-something?
${newNoteCmd}
            `);
            return;
          }

          fs.readFile(noteMd, (err, data) => {
            if (err) throw err;
            console.log('\x1Bc');
            console.log(data.toString());
          });

          fs.watch(noteMd, () => {
            fs.readFile(noteMd, (err, data) => {
              if (err) throw err;
              console.log('\x1Bc');
              console.log(data.toString());
            });
          });
        });
      });
    });
  });

program
  .command('section')
  .alias('s')
  .description('create new section')
  .action(function() {
    co(function *() {
      const sectionName = yield prompt('New section name: ');
      const cliRefName = yield prompt('Cli reference key: ');
      const description = yield prompt('Short description: ');

      Utils.createSection(sectionName, cliRefName, description);

      console.log(chalk.green(`new section '${sectionName}' was created!`));
    });
  });

program
  .command('init')
  .description('initializes notes')
  .action(function() {
    co(function *() {
      const notesDirPath = yield prompt('notes directory path (from $HOME): ');
      const homePath = `${process.env.HOME}/${notesDirPath}`;
      Utils.initializeNotes(homePath);

      const shouldCreate = yield prompt.confirm(`Would you like me to create "${homePath}" for you?(Recommended) [y/N] `);
      Utils.createDir(shouldCreate, homePath);
      console.log('Start taking notes with', chalk.cyan('nonote new!'));
      // TODO: create a readme
      process.exit();
    })
  });

program
  .command('add <cli-ref> [notes...]')
  .alias('a')
  .description('add note to object')
  .action(function(ref, note) {
    try {
      Utils.addNote(note, ref);
      console.log(chalk.green('note added!'));
    } catch (e) {
      console.log(chalk.red(e));
    }
  });

program
  .command('remove <cli-ref> [index]')
  .alias('r')
  .option('-s, --section', 'remove a seciton')
  .description('remove note from note object')
  .action(function(ref, note, options) {
    if (options.section && note === undefined) {
      Utils.removeSection(ref);
    } else {
      try {
        Utils.changeStatus(note, ref, Utils.removeNote);
        console.log(chalk.green(`note at index[${note}] was removed!`));
      } catch (e) {
        console.log(chalk.red(e));
      }
    }
  });

program
  .command('complete <cli-ref> [index]')
  .alias('c')
  .description('mark item as complete')
  .action(function(ref, note) {
    try {
      Utils.changeStatus(note, ref, Utils.completeNote);
      console.log(chalk.green(`note at index[${note}] was marked as complete!`));
    } catch (e) {
      console.log(chalk.red(e));
    }
  });

program
  .command('incomplete <cli-ref> [index]')
  .alias('i')
  .description('mark item as incomplete')
  .action(function(ref, note) {
    try {
      Utils.changeStatus(note, ref, Utils.incompleteNote);
      console.log(chalk.green(`note at index[${note}] was marked as incomplete!`));
    } catch (e) {
      console.log(chalk.red(e));
    }
  });

program
  .command('failed [cli-ref] <index>')
  .alias('f')
  .description('mark item as failed')
  .action(function(ref, note) {
    try {
      Utils.changeStatus(note, ref, Utils.failNote);
      console.log(chalk.green(`note at index[${note}] was marked as failed :(`));
    } catch (e) {
      console.log(chalk.red(e));
    }
  });

  program.parse(process.argv);

<commit_msg>Was only making the note update<commit_after>#!/usr/bin/env node

import { install } from 'source-map-support';
install();

import 'babel-polyfill';
// Libs
import chalk from 'chalk';
import program from 'commander';
import fs from 'fs-extra';
import moment from 'moment';
import co from 'co';
import prompt from 'co-prompt';
import * as Utils from './utils';

program
  .version('0.0.1')
  .command('new [template]')
  .alias('n')
  .description('create a new note for the day')
  .action(function(template, cmd) {
    if(!template) {
      template = 'default';
    }
    const today = moment().format("DD-MM-YYYY");
    const yesterday = moment().subtract(1, 'day').format("DD-MM-YYYY");
    var configPath = `${process.env.HOME}/.nonoterc.json`;

    fs.readJson(configPath, (err, configObj) => {
      if (err) console.error(err)

      const notesDir = configObj.notesDirectory;
      const days = `${notesDir}/days/`;
      const todayPath = days + today;
      const yesterdayPath = days + yesterday;
      const yesterdayDataJSONPath= `${yesterdayPath}/data.json`;
      const dataJSONPath = `${todayPath}/data.json`;
      const noteMdPath = `${todayPath}/note.md`;

      const templateDataPath = `${notesDir}/templates/${template}.json`;

      fs.mkdirs(todayPath, (err) => {
        if (err) console.error(err)

        fs.copy(templateDataPath, dataJSONPath, (err) => {
          if (err) console.error(err)

          fs.readJson(yesterdayDataJSONPath, (err, yesterdayObj) => {
            let hasPreviousNote = true;
            let incompleteTasks = [];

            if (err && err.code === 'ENOENT') {
              hasPreviousNote = false;
            }

            if (hasPreviousNote) {
              incompleteTasks = Object.keys(yesterdayObj).map(section => {
                return yesterdayObj[section].items.filter(item => {
                  return item.status !== "complete"
                });
              })[0];
            }

            fs.readJson(dataJSONPath, (err, noteObj) => {
              console.log(`Creating new note from the ${chalk.green(template)} template...`);
              if (hasPreviousNote && incompleteTasks.length > 0) {
                console.log(`\nCopying ${chalk.cyan(incompleteTasks.length)} incomplete tasks from yesterday:`);
                incompleteTasks.forEach((task, i) => console.log(`   ${chalk.cyan(i)}.) ${task.description}`));
                const firstNote = Object.keys(noteObj)[0];
                const mergedItems = [ ...incompleteTasks, ...noteObj[firstNote].items ];
                noteObj[firstNote].items = mergedItems;
              }

              fs.writeJson(dataJSONPath, noteObj, (err) => {
                if (err) return console.error(err)

                Utils.makeNote(noteObj);
                const watchCmd = 'nono watch';
                console.log(`\nGreat success! Here is your note for today: \n${chalk.cyan(noteMdPath)}`);
                console.log(`\nYou can see the note by running ${chalk.green(watchCmd)} anywhere in your console!`);
              });
            })
          });
        });
      });
    });
  });

program
  .command('watch')
  .alias('w')
  .description('watches todays note')
  .action(function(){
    co(function *() {
      const today = moment().format("DD-MM-YYYY");
      var configPath = `${process.env.HOME}/.nonoterc.json`;
      fs.readJson(configPath, (err, configJSON) => {
        if (err) console.error(err)

        const notesDir = configJSON.notesDirectory;
        const days = `${notesDir}/days/`;
        const toDir = days + today;
        const noteMd = `${toDir}/note.md`;

        fs.access(noteMd, fs.constants.F_OK, (err) => {
          if (err && err.code === 'ENOENT') {
            const badNotePath = chalk.cyan(noteMd);
            const newNoteCmd = chalk.green('nono new');
            console.log(`
Oh man, oh jeez, ok, I-I-I can't access this note:
${badNotePath}

C-c-can you try m-m-making a new note or s-s-something?
${newNoteCmd}
            `);
            return;
          }

          fs.readFile(noteMd, (err, data) => {
            if (err) throw err;
            console.log('\x1Bc');
            console.log(data.toString());
          });

          fs.watch(noteMd, () => {
            fs.readFile(noteMd, (err, data) => {
              if (err) throw err;
              console.log('\x1Bc');
              console.log(data.toString());
            });
          });
        });
      });
    });
  });

program
  .command('section')
  .alias('s')
  .description('create new section')
  .action(function() {
    co(function *() {
      const sectionName = yield prompt('New section name: ');
      const cliRefName = yield prompt('Cli reference key: ');
      const description = yield prompt('Short description: ');

      Utils.createSection(sectionName, cliRefName, description);

      console.log(chalk.green(`new section '${sectionName}' was created!`));
    });
  });

program
  .command('init')
  .description('initializes notes')
  .action(function() {
    co(function *() {
      const notesDirPath = yield prompt('notes directory path (from $HOME): ');
      const homePath = `${process.env.HOME}/${notesDirPath}`;
      Utils.initializeNotes(homePath);

      const shouldCreate = yield prompt.confirm(`Would you like me to create "${homePath}" for you?(Recommended) [y/N] `);
      Utils.createDir(shouldCreate, homePath);
      console.log('Start taking notes with', chalk.cyan('nonote new!'));
      // TODO: create a readme
      process.exit();
    })
  });

program
  .command('add <cli-ref> [notes...]')
  .alias('a')
  .description('add note to object')
  .action(function(ref, note) {
    try {
      Utils.addNote(note, ref);
      console.log(chalk.green('note added!'));
    } catch (e) {
      console.log(chalk.red(e));
    }
  });

program
  .command('remove <cli-ref> [index]')
  .alias('r')
  .option('-s, --section', 'remove a seciton')
  .description('remove note from note object')
  .action(function(ref, note, options) {
    if (options.section && note === undefined) {
      Utils.removeSection(ref);
    } else {
      try {
        Utils.changeStatus(note, ref, Utils.removeNote);
        console.log(chalk.green(`note at index[${note}] was removed!`));
      } catch (e) {
        console.log(chalk.red(e));
      }
    }
  });

program
  .command('complete <cli-ref> [index]')
  .alias('c')
  .description('mark item as complete')
  .action(function(ref, note) {
    try {
      Utils.changeStatus(note, ref, Utils.completeNote);
      console.log(chalk.green(`note at index[${note}] was marked as complete!`));
    } catch (e) {
      console.log(chalk.red(e));
    }
  });

program
  .command('incomplete <cli-ref> [index]')
  .alias('i')
  .description('mark item as incomplete')
  .action(function(ref, note) {
    try {
      Utils.changeStatus(note, ref, Utils.incompleteNote);
      console.log(chalk.green(`note at index[${note}] was marked as incomplete!`));
    } catch (e) {
      console.log(chalk.red(e));
    }
  });

program
  .command('failed [cli-ref] <index>')
  .alias('f')
  .description('mark item as failed')
  .action(function(ref, note) {
    try {
      Utils.changeStatus(note, ref, Utils.failNote);
      console.log(chalk.green(`note at index[${note}] was marked as failed :(`));
    } catch (e) {
      console.log(chalk.red(e));
    }
  });

  program.parse(process.argv);

<|endoftext|>


<commit_before>var timers = require('timers'),
    http = require('http'),
    querystring = require('querystring'),
    async = require('async'),
    express = require('express');

var services = require('./services'),
    servicesParser = require('./services/parser');

var app = express(),
  argv = require('minimist')(process.argv.slice(2));

var servicesIndex = servicesParser.parseServices(argv.services);

function getRandomTimeForDelay()
{
  // wait between 0 - 1.5 records before delivering any results back
  return (Math.random() * 1.5).toFixed(2) * 1000;
}

app.get('/:serviceName/:indentLevel?', function (req, res) {

  var indentLevel = req.params.indentLevel ? parseInt(req.params.indentLevel) : 0,
      service = services.findService('/' + req.params.serviceName, servicesIndex);

  var randomTimeInSeconds, date;

  date = new Date();

  if (service) {

    console.log(Array(30).join('-'));
    console.log(date.getMinutes() + ':' + date.getSeconds() + ':' + date.getMilliseconds(), Array(indentLevel * 3).join(' '), service.label, '->', service.url);

    if (service.children) {
      var funcs = [],
          urlParams = (indentLevel + 1);

      for (var i = 0; i < service.children.urls.length; i++) {

        funcs.push(function(path) {

          return function (next) {

            http.get('http://' + argv.address +':'+ argv['proxy-port'] + path, function (res) {
              timers.setTimeout(function() {
                next();
              }, getRandomTimeForDelay());
            });

          };

        }( service.children.urls[i]) );
      }

      //console.log('>> flow', '-', service.children.flow);

      if (service.children.flow === 'serial') {

        async.series(funcs, function (err, results) {
          res.send();
        });

      } else if (service.children.flow === 'parallel') {

        async.parallel(funcs, function (err, results) {
          res.send();
        });

      }
    } else {

      timers.setTimeout(function() {
        res.send();
      }, getRandomTimeForDelay());

    }

  } else {
    res.status(404).send();
  }

});

var server = app.listen(argv.port, argv.address, function() {

  var address = server.address().address,
    port = server.address().port;

  console.log(argv.service + ' server listening at http://%s:%d', address, port);
  console.log('');

});
<commit_msg>print x-varnish header<commit_after>var timers = require('timers'),
    http = require('http'),
    querystring = require('querystring'),
    async = require('async'),
    express = require('express');

var services = require('./services'),
    servicesParser = require('./services/parser');

var app = express(),
  argv = require('minimist')(process.argv.slice(2));

var servicesIndex = servicesParser.parseServices(argv.services);

function getRandomTimeForDelay()
{
  // wait between 0 - 1.5 records before delivering any results back
  return (Math.random() * 1.5).toFixed(2) * 1000;
}

app.get('/:serviceName/:indentLevel?', function (req, res) {

  var indentLevel = req.params.indentLevel ? parseInt(req.params.indentLevel) : 0,
      service = services.findService('/' + req.params.serviceName, servicesIndex);

  var randomTimeInSeconds, date;

  date = new Date();

  if (service) {

    console.log(Array(30).join('-'));
    console.log(date.getMinutes() + ':' + date.getSeconds() + ':' + date.getMilliseconds(), Array(indentLevel * 3).join(' '), service.label, '->', service.url);

    if (service.children) {
      var funcs = [],
          urlParams = (indentLevel + 1);

      for (var i = 0; i < service.children.urls.length; i++) {

        funcs.push(function(path) {

          return function (next) {

            console.log('x-varnish', req.headers['x-varnish']);

            http.get('http://' + argv.address +':'+ argv['proxy-port'] + path, function (res) {
              timers.setTimeout(function() {
                next();
              }, getRandomTimeForDelay());
            });

          };

        }( service.children.urls[i]) );
      }

      //console.log('>> flow', '-', service.children.flow);

      if (service.children.flow === 'serial') {

        async.series(funcs, function (err, results) {
          res.send();
        });

      } else if (service.children.flow === 'parallel') {

        async.parallel(funcs, function (err, results) {
          res.send();
        });

      }
    } else {

      timers.setTimeout(function() {
        res.send();
      }, getRandomTimeForDelay());

    }

  } else {
    res.status(404).send();
  }

});

var server = app.listen(argv.port, argv.address, function() {

  var address = server.address().address,
    port = server.address().port;

  console.log(argv.service + ' server listening at http://%s:%d', address, port);
  console.log('');

});
<|endoftext|>


<commit_before>function Buscar(){

  var cadena_entrada  = document.getElementById('destino').value;

  $("#lista_destino").empty();

    //
    ajax_url="https://usabilidad-y-accesibilidad-alu0100763478.c9users.io/Pagina_UYA/coches.json"

    // Creamos un nuevo objeto encargado de la comunicación
    var ajax_peticion = new XMLHttpRequest();

    if(ajax_peticion){
        ajax_peticion.open( "POST", ajax_url, true );
        ajax_peticion.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        ajax_peticion.send(ajax_url);

        ajax_peticion.onreadystatechange = function()
        {

          // readyState es 4
          if (ajax_peticion.readyState == 4 )
          {

              // Analizaos el responseText que contendrá el JSON enviado desde el servidor
              var objeto = JSON.parse( ajax_peticion.responseText );
              // La variable jsonObj ahora contiene un objeto con los datos recibidos

                  vacio = true;
                  for( var i=0; i< objeto.coches.length; i++){
                    for( var j=0; j< objeto.coches[i].viajes_rutina.length; j++){

                    console.log("¿ ",cadena_entrada," = ",objeto.coches[i].viajes_rutina[j]," ?");

                      if(cadena_entrada == objeto.coches[i].viajes_rutina[j]){

                       $("#lista_destino").append("
"
                       + "Usuario: " + objeto.coches[i].nombre_usuario + "
"
                       + "Modelo del coche: " + objeto.coches[i].modelo + "
"
                       +"Valoracion de otros usuarios: " + objeto.coches[i].valoracion + "
"
                       +"Preferencias del conductor: " + "
"
                       +"
" + "Fumar: " + objeto.coches[i].opciones[0].fumar
                       +"
" + "Comer: " + objeto.coches[i].opciones[0].comer
                       +"
" + "Vehículo adaptado: " + objeto.coches[i].opciones[0].adaptado
                       +"
" + "Mascotas: " + objeto.coches[i].opciones[0].mascotas);

                       vacio = false;
                     }

                  if(vacio==true) alert("No hay viajes para el destino buscado. Cree una alerta o publique su viaje");

                    }
                  }

          }
        }
      }
}

// http://cybmeta.com/ajax-con-json-y-php-con-javascript-puro<commit_msg>arreglando servidor<commit_after>function Buscar(){

  var cadena_entrada  = document.getElementById('destino').value;

  $("#lista_destino").empty();

    //
    ajax_url="coches.json"

    // Creamos un nuevo objeto encargado de la comunicación
    var ajax_peticion = new XMLHttpRequest();

    if(ajax_peticion){
        ajax_peticion.open( "POST", ajax_url, true );
        ajax_peticion.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        ajax_peticion.send(ajax_url);

        ajax_peticion.onreadystatechange = function()
        {

          // readyState es 4
          if (ajax_peticion.readyState == 4 )
          {

              // Analizaos el responseText que contendrá el JSON enviado desde el servidor
              var objeto = JSON.parse( ajax_peticion.responseText );
              // La variable jsonObj ahora contiene un objeto con los datos recibidos

                  vacio = true;
                  for( var i=0; i< objeto.coches.length; i++){
                    for( var j=0; j< objeto.coches[i].viajes_rutina.length; j++){

                    console.log("¿ ",cadena_entrada," = ",objeto.coches[i].viajes_rutina[j]," ?");

                      if(cadena_entrada == objeto.coches[i].viajes_rutina[j]){

                       $("#lista_destino").append("
"
                       + "Usuario: " + objeto.coches[i].nombre_usuario + "
"
                       + "Modelo del coche: " + objeto.coches[i].modelo + "
"
                       +"Valoracion de otros usuarios: " + objeto.coches[i].valoracion + "
"
                       +"Preferencias del conductor: " + "
"
                       +"
" + "Fumar: " + objeto.coches[i].opciones[0].fumar
                       +"
" + "Comer: " + objeto.coches[i].opciones[0].comer
                       +"
" + "Vehículo adaptado: " + objeto.coches[i].opciones[0].adaptado
                       +"
" + "Mascotas: " + objeto.coches[i].opciones[0].mascotas);

                       vacio = false;
                     }

                  if(vacio==true) alert("No hay viajes para el destino buscado. Cree una alerta o publique su viaje");

                    }
                  }

          }
        }
      }
}

// http://cybmeta.com/ajax-con-json-y-php-con-javascript-puro<|endoftext|>


<commit_before>/**
 * @file key-cache
 * @author xiaowu
 * @email fe.xiaowu@gmail.com
 */

import {statSync, writeFileSync, readFileSync, unlinkSync, readdirSync} from 'fs';
import {mkdirsSync, emptyDirSync, readJsonSync} from 'fs-extra';
import {resolve} from 'path';
import {createHash} from 'crypto';

/**
 * 检查文件是否存在
 *
 * @inner
 * @param  {string} filePath 文件路径
 * @param {string} [type=file] 检测类型
 *
 * @return {boolean}          是否存在
 */
let exists = (filePath, type = 'file') => {
    try {
        return type === 'file' ? statSync(filePath).isFile() : statSync(filePath).isDirectory();
    }
    catch (e) {
        return false;
    }
};

export default class KeyCache {
    static options = {
        /**
         * 缓存目录，路径基于当前运行目录
         *
         * @default 安装包里 dirname + .cache
         * @type {String}
         */
        dir: resolve(__dirname, '..', '.cache'),

        /**
         * 保存的时间，单位秒，如果是null则表示一直保存
         *
         * @default null
         * @type {Number|null}
         */
        timeout: null,

        /**
         * 是否使用md5命名缓存文件
         *
         * @default true
         * @type {Boolean}
         */
        md5key: true
    }

    constructor(options = {}) {
        // 合并默认配置
        this.options = {...KeyCache.options, ...options};

        // 解析路径
        this.options.dir = resolve(this.options.dir);

        // 创建缓存目录
        mkdirsSync(this.options.dir);
    }

    /**
     * 设置缓存
     *
     * @param {string} key   key
     * @param {Object|string} value 值
     * @param {Object|undefined} options 可选配置
     * @return {Object} this
     */
    set(key, value, options = {}) {
        if (!key  || 'string' !== typeof key || value === undefined) {
            return this;
        }

        options = {...this.options, ...options};

        let data = {
            __time: null,
            __result: value,
            key
        };

        // 如果有过期时间则记录，否则忽略
        if (options.timeout !== null) {
            data.__time = Date.now();
            data.__end = options.timeout;
        }

        // 如果配置的缓存目录不是初始的则创建该目录，防止出错
        if (options.dir !== this.options.dir) {
            mkdirsSync(options.dir);
        }

        // 写入缓存
        writeFileSync(this._getFilePath(key, options), JSON.stringify(data));

        return this;
    }

    /**
     * 获取缓存文件路径
     *
     * @private
     * @param  {string} key key
     * @param {Object|undefined} options 配置参数，如果为空则调用this.options
     *
     * @return {string}     文件绝对路径
     */
    _getFilePath(key, options) {
        let filename;

        options = options || this.options;

        if (options.md5key) {
            let md5 = createHash('md5');
            // unescape encodeURIComponent 兼容中文 md5
            md5.update(unescape(encodeURIComponent(key)));

            filename = md5.digest('hex');
        }
        else {
            // 把文件名中的:替换为空
            filename = String(key).replace(/[^\u4e00-\u9fa5a-zA-Z\_\-0-9]/g, '');

            // 如果替换后为空则使用md5
            if (!filename) {
                return this._getFilePath(key, {...options, ...{md5key: true}});
            }
        }

        return  resolve(options.dir, filename + '.json');
    }

    getAll() {
        let dir = resolve(this.options.dir);

        // 如果目录不存在
        if (!exists(dir, 'dir')) {
            return [];
        }

        let data = {};

        readdirSync(dir).map(filename => {
            let result = readJsonSync(resolve(dir, filename), {
                throws: false
            }) || {};

            if (result.key) {
                data[result.key] = this.get(result.key);
            }
        });

        return data;
    }

    /**
     * 获取缓存
     *
     * @param  {string} key key
     *
     * @return {Object|string|null}     结果，如果没有找到或者过期则为null
     */
    get(key) {
        let filepath = this._getFilePath(key);

        // 如果文件不存在
        if (!exists(filepath)) {
            return null;
        }

        let filedata = readFileSync(filepath).toString();

        try {
            filedata = JSON.parse(filedata);
        }
        catch (e) {
            return null;
        }

        // 如果没有时间就不是key-cache设置的，则忽略
        if (filedata.__time === undefined) {
            return null;
        }

        // 如果设置了时间并且过期了
        // 则删除这个缓存文件
        if (filedata.__time !== null && Date.now() - filedata.__time > filedata.__end * 1000) {
            this.remove(key);
            return null;
        }

        // 如果为undefined则返回null，因为值是fn时不会被JSON.stringify解析
        return filedata.__result !== undefined ? filedata.__result : null;
    }

    /**
     * 删除缓存
     *
     * @param  {string|undefined} key key，如果为空则全部删除
     *
     * @return {Object}     this
     */
    remove(key) {
        // 如果没有key则说明全部删除
        if (!key) {
            emptyDirSync(this.options.dir);
            return this;
        }

        let filepath = this._getFilePath(key);

        // 如果文件不存在
        if (!exists(filepath)) {
            return this;
        }

        // 删除文件
        unlinkSync(filepath);

        return this;
    }
}
<commit_msg>update: 添加注释<commit_after>/**
 * @file key-cache
 * @author xiaowu
 * @email fe.xiaowu@gmail.com
 */

import {statSync, writeFileSync, readFileSync, unlinkSync, readdirSync} from 'fs';
import {mkdirsSync, emptyDirSync, readJsonSync} from 'fs-extra';
import {resolve} from 'path';
import {createHash} from 'crypto';

/**
 * 检查文件是否存在
 *
 * @inner
 * @param  {string} filePath 文件路径
 * @param {string} [type=file] 检测类型
 *
 * @return {boolean}          是否存在
 */
let exists = (filePath, type = 'file') => {
    try {
        return type === 'file' ? statSync(filePath).isFile() : statSync(filePath).isDirectory();
    }
    catch (e) {
        return false;
    }
};

export default class KeyCache {
    static options = {
        /**
         * 缓存目录，路径基于当前运行目录
         *
         * @default 安装包里 dirname + .cache
         * @type {String}
         */
        dir: resolve(__dirname, '..', '.cache'),

        /**
         * 保存的时间，单位秒，如果是null则表示一直保存
         *
         * @default null
         * @type {Number|null}
         */
        timeout: null,

        /**
         * 是否使用md5命名缓存文件
         *
         * @default true
         * @type {Boolean}
         */
        md5key: true
    }

    constructor(options = {}) {
        // 合并默认配置
        this.options = {...KeyCache.options, ...options};

        // 解析路径
        this.options.dir = resolve(this.options.dir);

        // 创建缓存目录
        mkdirsSync(this.options.dir);
    }

    /**
     * 设置缓存
     *
     * @param {string} key   key
     * @param {Object|string} value 值
     * @param {Object|undefined} options 可选配置
     * @return {Object} this
     */
    set(key, value, options = {}) {
        if (!key  || 'string' !== typeof key || value === undefined) {
            return this;
        }

        options = {...this.options, ...options};

        let data = {
            __time: null,
            __result: value,
            __key: key
        };

        // 如果有过期时间则记录，否则忽略
        if (options.timeout !== null) {
            data.__time = Date.now();
            data.__end = options.timeout;
        }

        // 如果配置的缓存目录不是初始的则创建该目录，防止出错
        if (options.dir !== this.options.dir) {
            mkdirsSync(options.dir);
        }

        // 写入缓存
        writeFileSync(this._getFilePath(key, options), JSON.stringify(data));

        return this;
    }

    /**
     * 获取缓存文件路径
     *
     * @private
     * @param  {string} key key
     * @param {Object|undefined} options 配置参数，如果为空则调用this.options
     *
     * @return {string}     文件绝对路径
     */
    _getFilePath(key, options) {
        let filename;

        options = options || this.options;

        if (options.md5key) {
            let md5 = createHash('md5');
            // unescape encodeURIComponent 兼容中文 md5
            md5.update(unescape(encodeURIComponent(key)));

            filename = md5.digest('hex');
        }
        else {
            // 把文件名中的:替换为空
            filename = String(key).replace(/[^\u4e00-\u9fa5a-zA-Z\_\-0-9]/g, '');

            // 如果替换后为空则使用md5
            if (!filename) {
                return this._getFilePath(key, {...options, ...{md5key: true}});
            }
        }

        return  resolve(options.dir, filename + '.json');
    }

    /**
     * 获取所有缓存数据
     *
     * @return {Object} {key: value, ...}
     */
    getAll() {
        let dir = resolve(this.options.dir);

        // 如果目录不存在
        if (!exists(dir, 'dir')) {
            return [];
        }

        let data = {};

        readdirSync(dir).map(filename => {
            let result = readJsonSync(resolve(dir, filename), {
                throws: false
            }) || {};

            if (result.__key) {
                data[result.__key] = this.get(result.__key);
            }
        });

        return data;
    }

    /**
     * 获取缓存
     *
     * @param  {string} key key
     *
     * @return {Object|string|null}     结果，如果没有找到或者过期则为null
     */
    get(key) {
        let filepath = this._getFilePath(key);

        // 如果文件不存在
        if (!exists(filepath)) {
            return null;
        }

        let filedata = readFileSync(filepath).toString();

        try {
            filedata = JSON.parse(filedata);
        }
        catch (e) {
            return null;
        }

        // 如果没有时间就不是key-cache设置的，则忽略
        if (filedata.__time === undefined) {
            return null;
        }

        // 如果设置了时间并且过期了
        // 则删除这个缓存文件
        if (filedata.__time !== null && Date.now() - filedata.__time > filedata.__end * 1000) {
            this.remove(key);
            return null;
        }

        // 如果为undefined则返回null，因为值是fn时不会被JSON.stringify解析
        return filedata.__result !== undefined ? filedata.__result : null;
    }

    /**
     * 删除缓存
     *
     * @param  {string|undefined} key key，如果为空则全部删除
     *
     * @return {Object}     this
     */
    remove(key) {
        // 如果没有key则说明全部删除
        if (!key) {
            emptyDirSync(this.options.dir);
            return this;
        }

        let filepath = this._getFilePath(key);

        // 如果文件不存在
        if (!exists(filepath)) {
            return this;
        }

        // 删除文件
        unlinkSync(filepath);

        return this;
    }
}
<|endoftext|>


<commit_before>import React from 'react';
import { SprkLink } from '@sparkdesignsystem/spark-react';
import { Link } from 'gatsby';
import classnames from 'classnames';

function ContextMenu({context, setContext, className, autoNav}) {
  return (

          <SprkLink
            additionalClasses={classnames({'docs-context-menu__item--active': context==='installing-spark'})}
            onClick={(e) => {if (!autoNav) {e.preventDefault();} setContext('installing-spark');}}
            variant="simple"
            element={Link}
            to="/installing-spark">Installing Spark</SprkLink>

          <SprkLink
            additionalClasses={classnames({'docs-context-menu__item--active': context==='using-spark'})}
            onClick={(e) => {if (!autoNav) {e.preventDefault();} setContext('using-spark');}}
            variant="simple"
            element={Link}
            to="/using-spark">Using Spark</SprkLink>

          <SprkLink
            additionalClasses={classnames({'docs-context-menu__item--active': context==='principles'})}
            onClick={(e) => {if (!autoNav) {e.preventDefault();} setContext('principles');}}
            element={Link}
            variant='simple'
            to="/principles/design-principles">Principles</SprkLink>

  );
}

export default ContextMenu;
<commit_msg>add proptypes to context<commit_after>import React from 'react';
import { SprkLink } from '@sparkdesignsystem/spark-react';
import { Link } from 'gatsby';
import classnames from 'classnames';
import PropTypes from 'prop-types';

function ContextMenu({ context, setContext, className, autoNav }) {
  return (

          <SprkLink
            additionalClasses={
              classnames(
                {
                  'docs-context-menu__item--active': context === 'installing-spark',
                },
              )
            }
            onClick={
              (e) => {
                if (!autoNav) {
                  e.preventDefault();
                }
                setContext('installing-spark');
              }
            }
            variant="simple"
            element={Link}
            to="/installing-spark/setting-up-your-environment"
          >
            Installing Spark
          </SprkLink>

          <SprkLink
            additionalClasses={
              classnames(
                {
                  'docs-context-menu__item--active': context === 'using-spark',
                },
              )
            }
            onClick={
              (e) => {
                if (!autoNav) {
                  e.preventDefault();
                }
                setContext('using-spark');
              }
            }
            variant="simple"
            href="#nogo"
          >
            Using Spark
          </SprkLink>

          <SprkLink
            additionalClasses={
              classnames(
                { 'docs-context-menu__item--active': context === 'principles' },
              )
            }
            onClick={
              (e) => {
                if (!autoNav) { e.preventDefault(); } setContext('principles');
              }
            }
            variant="simple"
            href="#nogo"
          >
            Principles
          </SprkLink>

  );
}

ContextMenu.propTypes = {
  context: PropTypes.string,
  setContext: PropTypes.func,
  className: PropTypes.string,
  autoNav: PropTypes.bool,
};

export default ContextMenu;
<|endoftext|>


<commit_before>var http = require('http'),
  async = require('async'),
  express = require('express');

var app = express(),
  argv = require('minimist')(process.argv.slice(2));

app.get('/', function (req, res) {

  var rpcCalls = [];

  if (argv.call) {
    if (Array.isArray(argv.call)) {
      rpcCalls = argv.call.slice();
    } else if (argv.call && argv.call.length) {
      rpcCalls.push( argv.call );
    }
  }

  console.log('inside service:', argv.service);

  if (rpcCalls.length > 0) {

    var funcs = [];

    for (var i = 0; i < rpcCalls.length; i++) {
      funcs.push((function (url) {

        return function(next) {

          http.get(url, function (res) {
            next();
          });

        };

      }( rpcCalls[i] )));
    }

    async.parallel(funcs, function (err, results) {
      //console.log('parallel finishes');
    });

    res.send();

  } else {

    res.send(argv.service);

  }

});

var server = app.listen(argv.port, argv.address, function() {

  var address = server.address().address,
    port = server.address().port;

  console.log(argv.service + ' service listening at http://%s:%d', address, port);

});
<commit_msg>ability to make rpc calls in parallel or serial<commit_after>var http = require('http'),
  async = require('async'),
  express = require('express');

var app = express(),
  argv = require('minimist')(process.argv.slice(2));

app.get('/', function (req, res) {

  var rpcCalls = [];

  if (argv.call) {
    if (Array.isArray(argv.call)) {
      rpcCalls = argv.call.slice();
    } else if (argv.call && argv.call.length) {
      rpcCalls.push( argv.call );
    }
  }

  console.log('inside service:', argv.service);

  if (rpcCalls.length > 0) {

    var funcs = [];

    for (var i = 0; i < rpcCalls.length; i++) {
      funcs.push((function (url) {

        return function(next) {

          http.get(url, function (res) {
            next();
          });

        };

      }( rpcCalls[i] )));
    }

    if (argv.flow === 'parallel') {

      async.parallel(funcs, function (err, results) {
        res.send();
      });

    } else if (argv.flow === 'series') {

      async.series(funcs, function (err, results) {
        res.send();
      });

    }

  } else {

    res.send(argv.service);

  }

});

var server = app.listen(argv.port, argv.address, function() {

  var address = server.address().address,
    port = server.address().port;

  console.log(argv.service + ' service listening at http://%s:%d', address, port);

});
<|endoftext|>


<commit_before>import React from 'react';
import {Provider} from 'react-redux';
import {shallow, render} from 'enzyme';
import configureMockStore from 'redux-mock-store';
const createMockStore = configureMockStore([]);

import Harper from './harper';

const makeState = name => {
  return {name: name};
};

const embed = (component, state) => {
  let createStore = configureMockStore([]);
  let store = createStore(state);
  return (
    <Provider store={store}>
      {React.createElement(component)}
    </Provider>
  );
};

it ('renders name in a span', () => {
  // given
  let name = 'Charles';
  let state = makeState(name);
  let embedded = embed(Harper, state);

  // when
  let wrapper = render(embedded);

  // then
  let spans = wrapper.find('span');
  expect(spans.length).toBe(1);
  // expect(spans).toEqual(name);
  // expect(wrapper.text()).toEqual(name);

});
<commit_msg>re-enable name assertion<commit_after>import React from 'react';
import {Provider} from 'react-redux';
import {shallow, render} from 'enzyme';
import configureMockStore from 'redux-mock-store';
const createMockStore = configureMockStore([]);

import Harper from './harper';

const makeState = name => {
  return {name: name};
};

const embed = (component, state) => {
  let createStore = configureMockStore([]);
  let store = createStore(state);
  return (
    <Provider store={store}>
      {React.createElement(component)}
    </Provider>
  );
};

it ('renders name in a span', () => {
  // given
  let name = 'Charles';
  let state = makeState(name);
  let embedded = embed(Harper, state);

  // when
  let wrapper = render(embedded);

  // then
  let spans = wrapper.find('span');
  expect(spans.length).toBe(1);
  expect(wrapper.text()).toEqual(name);

});
<|endoftext|>


<commit_before>(function(name, definition) {

  // Important NOTE
  // In browsers, binary types must use a 3rd party Buffer implementation,
  // the recommended one is from https://github.com/feross/buffer

  if (typeof module != 'undefined') {
    var Buffer = require('buffer/').Buffer;
    // CommonJS - NodeJS
    module.exports = definition(Buffer);
  } else if (typeof define == 'function' && typeof define.amd == 'object') {
    // AMD - RequireJS(Buffer class must be exposed as AMD)
    define(['Buffer'], definition);
  } else {
    // Global - Browser(Buffer class should exists globally)
    this[name] = definition(this.Buffer);
  }

}('mod', function(Buffer) {

  if (typeof Buffer === 'undefined') {
    throw new Error('Cannot continue without a binary Buffer implementation')
  }

  function deserializeMap(m) {
    var items = {};
    var keys = Object.keys(m);
    for (var k in keys) {
      var key = keys[k];
      items[key] = Translator.toFlatJSON(m[key]);
    }
    return items;
  }

  function serializeMap(m) {
    var items = {'M': {}};
    var keys = Object.keys(m);
    for (var k in keys) {
      var key = keys[k];
      items['M'][key] = Translator.toDynamoDBJSON(m[key]);
    }
    return items;
  }

  var Deserializers = {
       'S': function(v) { return String(v); },
       'N': function(v) { return typeof v === 'string' ? v : Number(v); },
       'B': function(v) { return new Buffer(v, 'utf8'); },
    'BOOL': function(v) { return v ? true : false; },
    'NULL': function(v) { return null; },
      'SS': function(v) { return v.map(function(it) { return String(it); }); },
      'NS': function(v) { return v.map(function(it) { return typeof it === 'string' ? it : Number(it); }); },
      'BS': function(v) { return v.map(function(it) { return new Buffer(it, 'utf8'); }); },
       'L': function(v) { return v.map(function(it) { return Translator.toFlatJSON(it); }); },
       'M': function(v) { return deserializeMap(v); }
  };

  var Serializers = {
     'undefined': function(v) { return {'NULL': null}; },
          'null': function(v) { return {'NULL': null}; },
       'boolean': function(v) { return {'BOOL': v}; },
        'number': function(v) { return {'N': v}; },
        'string': function(v) { return {'S': v}; },
         'array': function(v) {
            // check if every element is Number => NS
            // check if every element is String => SS
            // check if every element is Binary => BS
            // else => L
            var numbers = v.filter(function(it) { return Translator.getJSTypeOf(it) === 'number'; });
            var strings = v.filter(function(it) { return Translator.getJSTypeOf(it) === 'string'; });
            var buffers = v.filter(function(it) { return Buffer.isBuffer(it); });
            // check if only numbers
            if (numbers.length === v.length) {
              return {'NS': numbers};
            } else if (strings.length === v.length) {
              return {'SS': strings};
            } else if (buffers.length === v.length) {
              return {'BS': buffers};
            } else {
              return {'L': v.map(function(it) { return Translator.toDynamoDBJSON(it); })};
            }
         },
    'uint8array': function(v) { return {'B': v}; },
        'object': function(v) { return Buffer.isBuffer(v) ? {'B': v} : serializeMap(v); }
  };

  var Translator = {
    /**
     * Convert to flat JSON from DynamoDB json
     *
     * @param {mixed} input - DynamoDB JSON value
     */
    toFlatJSON: function(input) {
      if (typeof input !== 'object') {
        throw new Error('Invalid input, only objects are allowed');
      }
      var keys = Object.keys(input);
      if (keys.length === 0) {
        throw new Error('Invalid input, object has no attributes');
      }
      var typeSymbol = keys[0];
      if (typeSymbol in Deserializers) {
        return Deserializers[typeSymbol](input[typeSymbol]);
      } else {
        throw new Error('Unsupported deserialzier type: ' + typeSymbol);
      }
      return result;
    },
    /**
     * Convert to DynamoDB json from flat JSON
     *
     * @param {mixed} input - flat JSON value
     */
    toDynamoDBJSON: function(input) {
      var tof = Translator.getJSTypeOf(input);
      if (tof in Serializers) {
        return Serializers[tof](input);
      } else {
        throw new Error('Type is not supported');
      }
    },
    getJSTypeOf: function(val) {
      return Object.prototype.toString.call(val).replace(/^\[object (.+)\]$/, '$1').toLowerCase();
    }
  };

  return Translator;
}));<commit_msg>always encode number to string<commit_after>(function(name, definition) {

  // Important NOTE
  // In browsers, binary types must use a 3rd party Buffer implementation,
  // the recommended one is from https://github.com/feross/buffer

  if (typeof module != 'undefined') {
    var Buffer = require('buffer/').Buffer;
    // CommonJS - NodeJS
    module.exports = definition(Buffer);
  } else if (typeof define == 'function' && typeof define.amd == 'object') {
    // AMD - RequireJS(Buffer class must be exposed as AMD)
    define(['Buffer'], definition);
  } else {
    // Global - Browser(Buffer class should exists globally)
    this[name] = definition(this.Buffer);
  }

}('mod', function(Buffer) {

  if (typeof Buffer === 'undefined') {
    throw new Error('Cannot continue without a binary Buffer implementation')
  }

  function deserializeMap(m) {
    var items = {};
    var keys = Object.keys(m);
    for (var k in keys) {
      var key = keys[k];
      items[key] = Translator.toFlatJSON(m[key]);
    }
    return items;
  }

  function serializeMap(m) {
    var items = {'M': {}};
    var keys = Object.keys(m);
    for (var k in keys) {
      var key = keys[k];
      items['M'][key] = Translator.toDynamoDBJSON(m[key]);
    }
    return items;
  }

  var Deserializers = {
       'S': function(v) { return String(v); },
       'N': function(v) { return typeof v === 'string' ? v : Number(v); },
       'B': function(v) { return new Buffer(v, 'utf8'); },
    'BOOL': function(v) { return v ? true : false; },
    'NULL': function(v) { return null; },
      'SS': function(v) { return v.map(function(it) { return String(it); }); },
      'NS': function(v) { return v.map(function(it) { return typeof it === 'string' ? it : Number(it); }); },
      'BS': function(v) { return v.map(function(it) { return new Buffer(it, 'utf8'); }); },
       'L': function(v) { return v.map(function(it) { return Translator.toFlatJSON(it); }); },
       'M': function(v) { return deserializeMap(v); }
  };

  var Serializers = {
     'undefined': function(v) { return {'NULL': null}; },
          'null': function(v) { return {'NULL': null}; },
       'boolean': function(v) { return {'BOOL': v}; },
        'number': function(v) { return {'N': String(v)}; },
        'string': function(v) { return {'S': v}; },
         'array': function(v) {
            // check if every element is Number => NS
            // check if every element is String => SS
            // check if every element is Binary => BS
            // else => L
            var numbers = v.filter(function(it) { return Translator.getJSTypeOf(it) === 'number'; });
            var strings = v.filter(function(it) { return Translator.getJSTypeOf(it) === 'string'; });
            var buffers = v.filter(function(it) { return Buffer.isBuffer(it); });
            // check if only numbers
            if (numbers.length === v.length) {
              return {'NS': numbers};
            } else if (strings.length === v.length) {
              return {'SS': strings};
            } else if (buffers.length === v.length) {
              return {'BS': buffers};
            } else {
              return {'L': v.map(function(it) { return Translator.toDynamoDBJSON(it); })};
            }
         },
    'uint8array': function(v) { return {'B': v}; },
        'object': function(v) { return Buffer.isBuffer(v) ? {'B': v} : serializeMap(v); }
  };

  var Translator = {
    /**
     * Convert to flat JSON from DynamoDB json
     *
     * @param {mixed} input - DynamoDB JSON value
     */
    toFlatJSON: function(input) {
      if (typeof input !== 'object') {
        throw new Error('Invalid input, only objects are allowed');
      }
      var keys = Object.keys(input);
      if (keys.length === 0) {
        throw new Error('Invalid input, object has no attributes');
      }
      var typeSymbol = keys[0];
      if (typeSymbol in Deserializers) {
        return Deserializers[typeSymbol](input[typeSymbol]);
      } else {
        throw new Error('Unsupported deserialzier type: ' + typeSymbol);
      }
      return result;
    },
    /**
     * Convert to DynamoDB json from flat JSON
     *
     * @param {mixed} input - flat JSON value
     */
    toDynamoDBJSON: function(input) {
      var tof = Translator.getJSTypeOf(input);
      if (tof in Serializers) {
        return Serializers[tof](input);
      } else {
        throw new Error('Type is not supported');
      }
    },
    getJSTypeOf: function(val) {
      return Object.prototype.toString.call(val).replace(/^\[object (.+)\]$/, '$1').toLowerCase();
    }
  };

  return Translator;
}));<|endoftext|>


<commit_before>import craftai from 'craft-ai-client-js';
import loadCfg from './loadCfg';

loadCfg()
  .then(config => craftai(config))
  .then(instance => {
    console.log(`'${instance.id}' successfully created!`);
    return instance.createAgent('bts/hello_world.bt', {name: 'juliette'})
      .then(agent => console.log(`agent #${agent.id} created.`))
      .then(() => instance.createAgent('bts/hello_world.bt', {name: 'romeo'}))
      .then(agent => console.log(`agent #${agent.id} created.`))
      .then(() => instance.registerAction(
        'HelloWorld',
        (requestId, agentId, input, success, failure) => {
          console.log(`#${agentId}: "Hello World!"`);
          success();
        }))
      .then(() => instance.registerAction(
        'SayMyName',
        (requestId, agentId, input, success, failure) => {
          console.log(`#${agentId}: "My name is ${input.name}."`);
          success();
        }))
      .then(() => instance.update(500));
  })
  .catch((err) => {
    console.log('Unexpected error!');
    console.log(err);
  });
<commit_msg>Improving error retrieval<commit_after>import craftai from 'craft-ai-client-js';
import loadCfg from './loadCfg';

loadCfg()
  .then(config => craftai(config))
  .then(instance => {
    console.log(`'${instance.id}' successfully created!`);
    return instance.createAgent('bts/hello_world.bt', {name: 'juliette'})
      .then(agent => console.log(`agent #${agent.id} created.`))
      .then(() => instance.createAgent('bts/hello_world.bt', {name: 'romeo'}))
      .then(agent => console.log(`agent #${agent.id} created.`))
      .then(() => instance.registerAction(
        'HelloWorld',
        (requestId, agentId, input, success, failure) => {
          console.log(`#${agentId}: "Hello World!"`);
          success();
        }))
      .then(() => instance.registerAction(
        'SayMyName',
        (requestId, agentId, input, success, failure) => {
          console.log(`#${agentId}: "My name is ${input.name}."`);
          success();
        }))
      .then(() => instance.update(500))
      .catch((err) => {
        console.log(`Error during the instance lifetime, check 'https://workbench.craft.ai/instances/${instance.cfg.owner}/${instance.cfg.name}/${instance.cfg.version}/${instance.id}/monitor' for further information.`);
        console.log(err);
      });
  })
  .catch((err) => {
    console.log(`Error during instance creation.`);
    console.log(err);
  });
<|endoftext|>


<commit_before>import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
import { PENDING } from 'constants';
import Loader from 'components/Loader';
import styled from 'styled-components';
import LoginButton from './LoginButton';

const Wrapper = styled.div`
  width: 100vw;
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
  background: ${props => props.theme.colors.primaryBackground}
  color: ${props => props.theme.colors.primaryText}
`;

const LoginContainer = styled.div`
`

const SubTitle = styled.h2`
  margin-top: 10px;
  font-size: 14px;
`;

class Login extends PureComponent {
  static propTypes = {
    status: PropTypes.string.isRequired,
    onLoginClicked: PropTypes.func.isRequired,
  };

  render() {
    const { status } = this.props;
    return (
      <Wrapper>
        {status === PENDING ?
          <Loader /> :
          <LoginContainer>
            <LoginButton onLoginClicked={this.props.onLoginClicked} />
          </LoginContainer>
        }
      </Wrapper>
    );
  }
}

export default Login;
<commit_msg>fix logincontainer styling<commit_after>import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
import { PENDING } from 'constants';
import Loader from 'components/Loader';
import { prop } from 'styled-tools';
import styled from 'styled-components';
import LoginButton from './LoginButton';

const Wrapper = styled.div`
  width: 100vw;
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
  background: ${prop('theme.colors.primaryBackground')};
  color: ${prop('theme.colors.primaryText')};
`;

class Login extends PureComponent {
  static propTypes = {
    status: PropTypes.string.isRequired,
    onLoginClicked: PropTypes.func.isRequired,
  };

  render() {
    const { status } = this.props;
    return (
      <Wrapper>
        {status === PENDING ?
          <Loader /> :
          <div>
            <LoginButton onLoginClicked={this.props.onLoginClicked} />
          </div>
        }
      </Wrapper>
    );
  }
}

export default Login;
<|endoftext|>