<commit_before>/*global emit: false, start: false, log: false, getRow: false, send: false,
  $: false*/

var utils = require('./utils'),
    admin_forms = require('./forms'),
    core = require('kanso/core'),
    templates = require('kanso/templates'),
    db = require('kanso/db'),
    flashmessages = require('kanso/flashmessages');

exports.addtype = function (doc, req) {
    if (!req.client) {
        return [null, templates.render('base.html', req, {
            title: req.query.app + ' - Types - ' + req.query.type,
            content: templates.render('noscript.html', req, {})
        })];
    }
    utils.getDesignDoc(req.query.app, function (err, ddoc) {
        var settings = utils.appRequire(ddoc, 'kanso/settings'),
            types = utils.appRequire(ddoc, 'kanso/types'),
            app = utils.appRequire(ddoc, settings.load),
            type = app.types ? app.types[req.query.type]: undefined;

        var forms = utils.appRequire(ddoc, 'kanso/forms'),
            form = new forms.Form(type);

        form.validate(req);

        if (form.isValid()) {
            db.saveDoc(form.values, function (err, resp) {
                if (err) {
                    flashmessages.addMessage(req, {
                        type: 'error',
                        message: err.message || err.toString()
                    });

                    var content = templates.render('add_type.html', req, {
                        app: req.query.app,
                        app_heading: utils.capitalize(req.query.app),
                        type: req.query.type,
                        description: type.description,
                        type_heading: utils.typeHeading(req.query.type),
                        form: form.toHTML(req)
                    });

                    $('#content').html(content);
                    document.title = settings.name + ' - Types - ' + req.query.type;
                    admin_forms.bind(req);
                }
                else {
                    flashmessages.addMessage(req, {
                        type: 'success',
                        message: 'Added ' + resp.id
                    });
                    core.setURL('GET', '/' + req.query.app + '/view/' + resp.id);
                }
            });
        }
        else {
            flashmessages.addMessage(req, {
                type: 'error',
                message: 'Please correct the indicated errors'
            });

            var content = templates.render('add_type.html', req, {
                app: req.query.app,
                app_heading: utils.capitalize(req.query.app),
                type: req.query.type,
                description: type.description,
                type_heading: utils.typeHeading(req.query.type),
                form: form.toHTML(req)
            });

            $('#content').html(content);
            document.title = settings.name + ' - Types - ' + req.query.type;
        }
        admin_forms.bind(req);
    });
};

exports.updatetype = function (doc, req) {
    if (!req.client) {
        return [null, templates.render('base.html', req, {
            title: req.query.app + ' - Types - ' + doc.type,
            content: templates.render('noscript.html', req, {})
        })];
    }
    utils.getDesignDoc(req.query.app, function (err, ddoc) {
        var settings = utils.appRequire(ddoc, 'kanso/settings'),
            app = utils.appRequire(ddoc, settings.load),
            type = app.types ? app.types[doc.type]: undefined;

        var forms = utils.appRequire(ddoc, 'kanso/forms'),
            form = new forms.Form(type);

        form.validate(req);

        if (form.isValid()) {
            db.saveDoc(form.values, function (err, resp) {
                if (err) {
                    flashmessages.addMessage(req, {
                        type: 'error',
                        message: err.message || err.toString()
                    });

                    var content = templates.render('edit_type.html', req, {
                        id: req.query.id,
                        app: req.query.app,
                        app_heading: utils.capitalize(req.query.app),
                        type: doc.type,
                        type_heading: utils.typeHeading(doc.type),
                        form: form.toHTML(req)
                    });

                    $('#content').html(content);
                    document.title = settings.name + ' - Types - ' + doc.type;
                    admin_forms.bind(req);
                }
                else {
                    flashmessages.addMessage(req, {
                        type: 'success',
                        message: 'Saved changes to ' + doc._id
                    });
                    core.setURL('GET', '/' + req.query.app + '/view/' + resp.id);
                }
            });
        }
        else {
            flashmessages.addMessage(req, {
                type: 'error',
                message: 'Please correct the indicated errors'
            });

            var content = templates.render('edit_type.html', req, {
                id: req.query.id,
                app: req.query.app,
                app_heading: utils.capitalize(req.query.app),
                type: doc.type,
                type_heading: utils.typeHeading(doc.type),
                form: form.toHTML(req)
            });

            $('#content').html(content);
            document.title = settings.name + ' - Types - ' + doc.type;
        }
        admin_forms.bind(req);
    });
};

exports.deletetype = function (doc, req) {
    var baseURL = require('kanso/utils').getBaseURL();

    if (!req.client) {
        var loc = baseURL + '/' + req.query.app + '/types/' + doc.type;
        doc._deleted = true;
        flashmessages.addMessage(req, {
            type: 'success',
            message: 'Deleted ' + doc._id
        });
        return [doc, {code: 302, headers: {'Location': loc}}];
    }
    db.removeDoc(doc, function (err, resp) {
        if (err) {
            flashmessages.addMessage(req, {
                type: 'error',
                message: err.message || err.toString()
            });
        }
        else {
            flashmessages.addMessage(req, {
                type: 'success',
                message: 'Deleted ' + doc._id
            });
        }
        core.setURL('GET', core.appPath(
            (req.form && req.form.next) ||
            ('/' + req.query.app + '/types/' + doc.type)
        ));
    });
};
<commit_msg>initialize update forms in admin app<commit_after>/*global emit: false, start: false, log: false, getRow: false, send: false,
  $: false*/

var utils = require('./utils'),
    admin_forms = require('./forms'),
    core = require('kanso/core'),
    templates = require('kanso/templates'),
    db = require('kanso/db'),
    flashmessages = require('kanso/flashmessages');

exports.addtype = function (doc, req) {
    if (!req.client) {
        return [null, templates.render('base.html', req, {
            title: req.query.app + ' - Types - ' + req.query.type,
            content: templates.render('noscript.html', req, {})
        })];
    }
    utils.getDesignDoc(req.query.app, function (err, ddoc) {
        var settings = utils.appRequire(ddoc, 'kanso/settings'),
            types = utils.appRequire(ddoc, 'kanso/types'),
            app = utils.appRequire(ddoc, settings.load),
            type = app.types ? app.types[req.query.type]: undefined;

        var forms = utils.appRequire(ddoc, 'kanso/forms'),
            form = new forms.Form(type, doc);

        form.validate(req);

        if (form.isValid()) {
            db.saveDoc(form.values, function (err, resp) {
                if (err) {
                    flashmessages.addMessage(req, {
                        type: 'error',
                        message: err.message || err.toString()
                    });

                    var content = templates.render('add_type.html', req, {
                        app: req.query.app,
                        app_heading: utils.capitalize(req.query.app),
                        type: req.query.type,
                        description: type.description,
                        type_heading: utils.typeHeading(req.query.type),
                        form: form.toHTML(req)
                    });

                    $('#content').html(content);
                    document.title = settings.name + ' - Types - ' + req.query.type;
                    admin_forms.bind(req);
                }
                else {
                    flashmessages.addMessage(req, {
                        type: 'success',
                        message: 'Added ' + resp.id
                    });
                    core.setURL('GET', '/' + req.query.app + '/view/' + resp.id);
                }
            });
        }
        else {
            flashmessages.addMessage(req, {
                type: 'error',
                message: 'Please correct the indicated errors'
            });

            var content = templates.render('add_type.html', req, {
                app: req.query.app,
                app_heading: utils.capitalize(req.query.app),
                type: req.query.type,
                description: type.description,
                type_heading: utils.typeHeading(req.query.type),
                form: form.toHTML(req)
            });

            $('#content').html(content);
            document.title = settings.name + ' - Types - ' + req.query.type;
        }
        admin_forms.bind(req);
    });
};

exports.updatetype = function (doc, req) {
    if (!req.client) {
        return [null, templates.render('base.html', req, {
            title: req.query.app + ' - Types - ' + doc.type,
            content: templates.render('noscript.html', req, {})
        })];
    }
    utils.getDesignDoc(req.query.app, function (err, ddoc) {
        var settings = utils.appRequire(ddoc, 'kanso/settings'),
            app = utils.appRequire(ddoc, settings.load),
            type = app.types ? app.types[doc.type]: undefined;

        var forms = utils.appRequire(ddoc, 'kanso/forms'),
            form = new forms.Form(type, doc);

        form.validate(req);

        if (form.isValid()) {
            db.saveDoc(form.values, function (err, resp) {
                if (err) {
                    flashmessages.addMessage(req, {
                        type: 'error',
                        message: err.message || err.toString()
                    });

                    var content = templates.render('edit_type.html', req, {
                        id: req.query.id,
                        app: req.query.app,
                        app_heading: utils.capitalize(req.query.app),
                        type: doc.type,
                        type_heading: utils.typeHeading(doc.type),
                        form: form.toHTML(req)
                    });

                    $('#content').html(content);
                    document.title = settings.name + ' - Types - ' + doc.type;
                    admin_forms.bind(req);
                }
                else {
                    flashmessages.addMessage(req, {
                        type: 'success',
                        message: 'Saved changes to ' + doc._id
                    });
                    core.setURL('GET', '/' + req.query.app + '/view/' + resp.id);
                }
            });
        }
        else {
            flashmessages.addMessage(req, {
                type: 'error',
                message: 'Please correct the indicated errors'
            });

            var content = templates.render('edit_type.html', req, {
                id: req.query.id,
                app: req.query.app,
                app_heading: utils.capitalize(req.query.app),
                type: doc.type,
                type_heading: utils.typeHeading(doc.type),
                form: form.toHTML(req)
            });

            $('#content').html(content);
            document.title = settings.name + ' - Types - ' + doc.type;
        }
        admin_forms.bind(req);
    });
};

exports.deletetype = function (doc, req) {
    var baseURL = require('kanso/utils').getBaseURL();

    if (!req.client) {
        var loc = baseURL + '/' + req.query.app + '/types/' + doc.type;
        doc._deleted = true;
        flashmessages.addMessage(req, {
            type: 'success',
            message: 'Deleted ' + doc._id
        });
        return [doc, {code: 302, headers: {'Location': loc}}];
    }
    db.removeDoc(doc, function (err, resp) {
        if (err) {
            flashmessages.addMessage(req, {
                type: 'error',
                message: err.message || err.toString()
            });
        }
        else {
            flashmessages.addMessage(req, {
                type: 'success',
                message: 'Deleted ' + doc._id
            });
        }
        core.setURL('GET', core.appPath(
            (req.form && req.form.next) ||
            ('/' + req.query.app + '/types/' + doc.type)
        ));
    });
};
<|endoftext|>


<commit_before>/*
Copyright (c) 2014, Intel Corporation

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

    * Redistributions of source code must retain the above copyright notice,
      this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright notice,
      this list of conditions and the following disclaimer in the documentation
      and/or other materials provided with the distribution.
    * Neither the name of Intel Corporation nor the names of its contributors
      may be used to endorse or promote products derived from this software
      without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

var logger = require("../lib/logger").init(),
    Cloud = require("../api/cloud.proxy"),
    utils = require("../lib/utils").init(),
    common = require('../lib/common'),
    configurator = require('../admin/configurator');

var activate = function (code) {
    logger.debug("Activation started ...");
    utils.getDeviceId(function (id) {
        var cloud = Cloud.init(logger, id);
        cloud.activate(code, function (err) {
            var r = 0;
            cloud.disconnect();
            if (err) {
                logger.error("Error in the activation process ...", err);
                r = 1;
            }
            else{
                configurator.setDeviceId(id);
            }
            process.exit(r);
        });
    });
};

function testConnection () {
    var conf = common.getConfig();
    var host = conf.connector[conf.default_connector].host;
    utils.getDeviceId(function (id) {
        var cloud = Cloud.init(logger, id);
        cloud.test(function (res) {
            var r = 0;
            if (res) {
                logger.info("Connected to %s", host);
                logger.info("Environment: %s", res.currentSetting);
                logger.info("Build: %s", res.build);
                logger.debug("Full response %j", res );
            } else {
                logger.error("Connection failed to %s", host);
                r = 1;
            }
            process.exit(r);
        });
    });
}

module.exports = {
    addCommand : function (program) {
        program
            .command('test')
            .description('Tries to reach the server (using the current protocol).')
            .action(function() {
                testConnection();
            });

        program
            .command('activate <activation_code>')
            .description('Activates the device.')
            .action(activate);
    }
};
<commit_msg>DP-2864 : Fixed problem with 'test' command<commit_after>/*
Copyright (c) 2014, Intel Corporation

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

    * Redistributions of source code must retain the above copyright notice,
      this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright notice,
      this list of conditions and the following disclaimer in the documentation
      and/or other materials provided with the distribution.
    * Neither the name of Intel Corporation nor the names of its contributors
      may be used to endorse or promote products derived from this software
      without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

var logger = require("../lib/logger").init(),
    Cloud = require("../api/cloud.proxy"),
    utils = require("../lib/utils").init(),
    common = require('../lib/common'),
    configurator = require('../admin/configurator');

var activate = function (code) {
    logger.debug("Activation started ...");
    utils.getDeviceId(function (id) {
        var cloud = Cloud.init(logger, id);
        cloud.activate(code, function (err) {
            var r = 0;
            cloud.disconnect();
            if (err) {
                logger.error("Error in the activation process ...", err);
                r = 1;
            }
            else{
                configurator.setDeviceId(id);
            }
            process.exit(r);
        });
    });
};

function testConnection () {
    var conf = common.getConfig();
    var host;
    if(conf.default_connector === 'rest+ws') {
        host = conf.connector['rest'].host;
    } else {
        host = conf.connector[conf.default_connector].host;
    }
    utils.getDeviceId(function (id) {
        var cloud = Cloud.init(logger, id);
        cloud.test(function (res) {
            var r = 0;
            if (res) {
                logger.info("Connected to %s", host);
                logger.info("Environment: %s", res.currentSetting);
                logger.info("Build: %s", res.build);
                logger.debug("Full response %j", res );
            } else {
                logger.error("Connection failed to %s", host);
                r = 1;
            }
            process.exit(r);
        });
    });
}

module.exports = {
    addCommand : function (program) {
        program
            .command('test')
            .description('Tries to reach the server (using the current protocol).')
            .action(function() {
                testConnection();
            });

        program
            .command('activate <activation_code>')
            .description('Activates the device.')
            .action(activate);
    }
};
<|endoftext|>


<commit_before>define(function (require, exports, module) {
  /**
   *
   * @param option
   * {
   * el, //list wrap element,optional if listEl is specified
   * listEl,// list element,optional if el is specified
   * processEl,//process element,optional if el is specified
   * listCls, //[optional]css class to find the slide list,default ".list"
   * processCls, //[optional]css class to find the slide process,default ".process"
   *
   * vertical, //[optional]slide direction,default horizontal(false)
   * itemLen, //[optional]width(or height) for each item
   * itemCount,//[optional]total item length for the list
   * totalLen,//[optional]total width(or height) for the list
   *
   * enableDrag, //[optional]enable drag to move,default false
   * enableLoop, //[optional]enable infinite loop,default false
   * enableAutorun, //[optional]enable auto play,default false
   * enableProcess, //[optional]enable default navigation process UI,default false
   *
   * moveTimeout, //[optional]time out for next move,default 100ms
   * moveDuration, //[optional]time out for one move duration,default 640
   * moveRate, //[optional]speed for animate one move,default 1.3
   * dragAnim, //[optional]drag move animation timing function,default 'cubic-bezier(0.075, 0.82, 0.165, 1)'
   * moveAnim, //[optional]auto move animation timing function,default 'ease'
   *
   * onMove, //[optional]on moving event listener
   * onFirst, //[optional]on first slide event listener
   * onLast, //[optional]on last slide event listener
   * onTouchstart, //[optional]on touchstart event listener
   * onTouchend, //[optional]on touchend  event listener
   * onTouchmove //[optional]on touchmove  event listener
   * }
   *
   * @method next() //move to next slide
   * @method pre() //move to pre slide
   * @method moveTo(index) //move to specified index slide,start from 0
   * @method reset() //reset to default state
   * @method refresh() //refresh for content changed
   * @method startAutoRun() //start to auto play
   * @method stopAutoRun() //stop auto play
   * @constructor Slider
   */
  function Slider(option) {
    option = option || {};
    var me = this,
      emptyFn = function () {
      },
      el = option.listEl || option.el.find(option.listCls || '.list'),
      pEl = option.processEl || el.siblings(option.processCls || '.process'),
      isMoving = false,
      moveTimeout = option.moveTimeout || 100,
      moveDuration = option.moveDuration || 640,
      moveRate = option.moveRate || 1.3,
      vertical = option.vertical,
      index = 0,
      totalLen,
      itemCount,
      itemLen,
      orientation = true,
      lastMove = 0,
      autoTimer = 0,
      loopTimer = 0,
      loopCls = 'slider-duplicate',
      moveToFn = vertical ? moveToY : moveToX;
    resetSize();
    calculateSize();
    var enableProcess = option.enableProcess,
      enableAutorun = option.enableAutorun,
      enableDrag = option.enableDrag,
      enableLoop = option.enableLoop;
    var onMove = option.onMove || emptyFn,
      onFirst = option.onFirst || emptyFn,
      onLast = option.onLast || emptyFn,
      onTouchstart = option.onTouchstart || emptyFn,
      onTouchend = option.onTouchend || emptyFn,
      onTouchmove = option.onTouchmove || emptyFn;
    var dragAnim = option.dragAnim || 'cubic-bezier(0.075, 0.82, 0.165, 1)',//'cubic-bezier(0.1, 0.57, 0.1, 1)';
      moveAnim = option.moveAnim || 'ease';
    var drag = {
      moved: false,
      timer: 0,
      dirX: 0,
      distX: 0,
      dirY: 0,
      distY: 0,
      moveDistX: 0,
      maxMove: itemLen / 2,
      startTime: 0,
      endTime: 0,
      resetMaxMove: function () {
        drag.maxMove = itemLen / 2;
      },
      distPos: function () {
        return drag[vertical ? 'distY' : 'distX'];
      },
      reset: function () {
        drag.moved = false;
        drag.isSwipe = false;
        drag.dirX = 0;
        drag.distX = 0;
        drag.dirY = 0;
        drag.distY = 0;
        drag.timer = 0;
        drag.timer && cancelRequestAnimFrame(drag.timer);
      },
      move: function () {
        if (!drag.moved) {
          return;
        }
        var mX = -(index + (enableLoop ? 1 : 0)) * itemLen,
          dx = Math.round(Math.abs(drag.distPos()) / moveRate);
        drag.moveDistX = dx;
        if (dx > itemLen * 9 / 10) {
          drag.endDrag();
          return;
        } else if (drag.distPos() > 0) {
          mX += dx;
        } else {
          mX -= dx;
        }

        moveToFn(mX, 0, dragAnim);
        lastMove = -mX;
      },
      endDrag: function () {
        drag.moved = false;
        var mX = -index * itemLen,
          dx = drag.moveDistX;
        if (drag.isSwipe) {
          drag.distPos() > 0 ? me.pre() : me.next();
        } else {
          if (drag.distPos() > 0) {
            mX += dx;
          } else {
            mX -= dx;
          }
          if (mX >= 0 || mX <= -(totalLen - itemLen) || dx < drag.maxMove) {
            move();
          } else {
            drag.distPos() > 0 ? me.pre() : me.next();
          }
        }

        drag.reset();
        me.startAutoRun();
      }
    };

    function touchStart(e) {
      if (itemCount < 2 || isMoving) {
        return;
      }
      drag.startTime = new Date().getTime();
      onTouchstart();
      me.stopAutoRun();
      totalLen = totalLen || el.width();
      itemLen = itemLen || (totalLen / itemCount);
      drag.resetMaxMove();
      var touch = e.touches[0];
      drag.moved = true;
      drag.dirX = touch.pageX;
      drag.distX = 0;
      drag.dirY = touch.pageY;
      drag.distY = 0;
      (function animloop() {
        if (!drag.moved) {
          drag.reset();
          return;
        }
        drag.move();
        drag.timer = requestAnimFrame(animloop);
      })();
    }

    function touchMove(e) {
      var touch = e.touches[0];
      drag.distX = touch.pageX - drag.dirX;
      drag.distY = touch.pageY - drag.dirY;
      onTouchmove(Math.abs(drag.distX), Math.abs(drag.distY));
    }

    function touchEnd(e) {
      drag.endTime = new Date().getTime();
      if (drag.moved) {
        drag.isSwipe = drag.endTime - drag.startTime <= 200 && Math.abs(drag.distPos()) > 30;
        drag.endDrag();
      }
      onTouchend(Math.abs(drag.distX), Math.abs(drag.distY));
    }

    if (enableDrag) {
      el.touchstart = el.touchstart || touchStart;
      el.touchmove = el.touchmove || touchMove;
      el.touchend = el.touchend || touchEnd;
      el.off('touchstart', el.touchstart);
      el.off('touchmove', el.touchmove);
      el.off('touchend', el.touchend);
      el.on('touchstart', el.touchstart);
      el.on('touchmove', el.touchmove);
      el.on('touchend', el.touchend);
    }

    function move() {
      if (isMoving) {
        return;
      }
      isMoving = true;
      setTimeout(function () {
        isMoving = false;
      }, moveTimeout);
      if (!enableLoop) {
        if (index > itemCount - 1) {
          index = itemCount - 1;
          onLast(index);
        } else if (index < 0) {
          index = 0;
          onFirst(index);
        }
      }
      var mx = (index + (enableLoop ? 1 : 0)) * itemLen,
        absm = Math.abs(lastMove - mx),
        mtime = Math.min(moveDuration, (moveDuration / itemLen) * absm),
        animate = moveAnim;

      if (drag.isSwipe) {
        var velocity = drag.moveDistX * moveRate / (drag.endTime - drag.startTime);
        mtime = velocity * absm;
        animate = dragAnim;
      }

      lastMove = mx;
      //修正android差1px的问题
      //mx = (mx>0&&$.os.android)?(mx+1):mx;
      moveToFn(-mx, mtime, animate);

      stopLoopHelper();
      if (enableLoop) {
        var loopm;
        if (index > itemCount - 1) {
          loopm = itemLen;
          index = 0;
          lastMove = itemLen;
          onLast(index);
        } else if (index < 0) {
          loopm = itemLen * itemCount;
          index = itemCount - 1;
          onFirst(index);
        }
        loopTimer = loopm !== undefined && setTimeout(function () {
            moveToFn(-loopm);
          }, mtime);
      }
      runProcess();
      onMove(index);
    }

    function moveToX(x, time, anim) {
      moveTo(x, 0, time, anim);
    }

    function moveToY(x, time, anim) {
      moveTo(0, x, time, anim);
    }

    function moveTo(x, y, time, anim) {
      el.css({
        '-webkit-transform': 'translate3d(' + (x || 0) + 'px' + ',' + (y || 0) + 'px,0)',
        '-webkit-transition': '-webkit-transform ' + (time || 0) + 'ms ' + (anim || moveAnim)
      });
    }

    function stopLoopHelper() {
      loopTimer && clearInterval(loopTimer);
    }

    function moveOrientation() {
      calculateSize();
      if (!enableLoop && index == itemCount - 1) {
        orientation = false;
      } else if (index == 0) {
        orientation = true;
      }
      if (!orientation) {
        me.pre();
      } else {
        me.next();
      }
    }

    function renderProcess() {
      if (enableProcess && itemCount > 1) {
        var tmp = [];
        for (var i = 0; i < itemCount; i++) {
          tmp.push('

');
        }
        pEl.html(tmp.join(''));
        pEl.show();
        runProcess();
      }
    }

    function renderLoop() {
      if (enableLoop) {
        el.find('.' + loopCls).remove();
        var cels = [].slice.call(el.children()),
          first = cels.pop().cloneNode(true),
          last = cels.shift().cloneNode(true);
        first.classList.add(loopCls);
        last.classList.add(loopCls);
        el.prepend(first);
        el.append(last);
      }
    }

    function runProcess() {
      if (!enableProcess) {
        return;
      }
      var processChild = pEl.find('div');
      processChild.removeClass('on');
      $(processChild[index]).addClass('on');
    }

    function resetSize() {
      el.find('.' + loopCls).remove();
      itemLen = option.itemLen || 0;
      itemCount = option.itemCount || 0;
      totalLen = option.totalLen || (itemCount * itemLen) || 0;
    }

    function calculateSize() {
      var child = el.children();
      itemLen = itemLen || child.eq(0)[vertical ? 'height' : 'width']();
      itemCount = itemCount || child.length;
      totalLen = totalLen || (itemLen * itemCount);
    }

    this.next = function () {
      if (isMoving) {
        return;
      }
      index++;
      move();
    }

    this.pre = function () {
      if (isMoving) {
        return;
      }
      index--;
      move();
    }

    this.moveTo = function (idx) {
      index = idx;
      move();
    }

    this.reset = function () {
      index = 0;
      orientation = true;
      me.stopAutoRun();
      pEl.hide();
      resetSize();
      calculateSize();
      renderLoop();
      lastMove = enableLoop ? itemLen : 0;
      moveToFn(-lastMove);
      drag.reset();
      renderProcess();
      me.startAutoRun();
    }

    this.refresh = function () {
      me.stopAutoRun();
      pEl.hide();
      resetSize();
      calculateSize();
      renderLoop();
      renderProcess();
      me.startAutoRun();
    }

    this.startAutoRun = function () {
      if (enableAutorun && itemCount > 1) {
        autoTimer = setInterval(function () {
          if (drag.moved) {
            return;
          }//如果拖动就停止
          moveOrientation();
        }, 3000);
      }
    }

    this.stopAutoRun = function () {
      autoTimer && clearInterval(autoTimer);
      stopLoopHelper();
    }

    this.reset();
  }

  return Slider;
});
<commit_msg>added class to current slide<commit_after>define(function (require, exports, module) {
  /**
   *
   * @param option
   * {
   * el, //list wrap element,optional if listEl is specified
   * listEl,// list element,optional if el is specified
   * processEl,//process element,optional if el is specified
   * listCls, //[optional]css class to find the slide list,default ".list"
   * processCls, //[optional]css class to find the slide process,default ".process"
   *
   * vertical, //[optional]slide direction,default horizontal(false)
   * itemLen, //[optional]width(or height) for each item
   * itemCount,//[optional]total item length for the list
   * totalLen,//[optional]total width(or height) for the list
   *
   * enableDrag, //[optional]enable drag to move,default false
   * enableLoop, //[optional]enable infinite loop,default false
   * enableAutorun, //[optional]enable auto play,default false
   * enableProcess, //[optional]enable default navigation process UI,default false
   *
   * moveTimeout, //[optional]time out for next move,default 100ms
   * moveDuration, //[optional]time out for one move duration,default 640
   * moveRate, //[optional]speed for animate one move,default 1.3
   * dragAnim, //[optional]drag move animation timing function,default 'cubic-bezier(0.075, 0.82, 0.165, 1)'
   * moveAnim, //[optional]auto move animation timing function,default 'ease'
   *
   * onMove, //[optional]on moving event listener
   * onFirst, //[optional]on first slide event listener
   * onLast, //[optional]on last slide event listener
   * onTouchstart, //[optional]on touchstart event listener
   * onTouchend, //[optional]on touchend  event listener
   * onTouchmove //[optional]on touchmove  event listener
   * }
   *
   * @method next() //move to next slide
   * @method pre() //move to pre slide
   * @method moveTo(index) //move to specified index slide,start from 0
   * @method reset() //reset to default state
   * @method refresh() //refresh for content changed
   * @method startAutoRun() //start to auto play
   * @method stopAutoRun() //stop auto play
   * @constructor Slider
   */
  function Slider(option) {
    option = option || {};
    var me = this,
      emptyFn = function () {
      },
      el = option.listEl || option.el.find(option.listCls || '.list'),
      pEl = option.processEl || el.siblings(option.processCls || '.process'),
      isMoving = false,
      moveTimeout = option.moveTimeout || 100,
      moveDuration = option.moveDuration || 640,
      moveRate = option.moveRate || 1.3,
      vertical = option.vertical,
      index = 0,
      totalLen,
      itemCount,
      itemLen,
      orientation = true,
      lastMove = 0,
      autoTimer = 0,
      loopTimer = 0,
      loopCls = 'slider-duplicate',
      currentCls = 'slider-current',
      moveToFn = vertical ? moveToY : moveToX;
    resetSize();
    calculateSize();
    var enableProcess = option.enableProcess,
      enableAutorun = option.enableAutorun,
      enableDrag = option.enableDrag,
      enableLoop = option.enableLoop;
    var onMove = option.onMove || emptyFn,
      onFirst = option.onFirst || emptyFn,
      onLast = option.onLast || emptyFn,
      onTouchstart = option.onTouchstart || emptyFn,
      onTouchend = option.onTouchend || emptyFn,
      onTouchmove = option.onTouchmove || emptyFn;
    var dragAnim = option.dragAnim || 'cubic-bezier(0.075, 0.82, 0.165, 1)',//'cubic-bezier(0.1, 0.57, 0.1, 1)';
      moveAnim = option.moveAnim || 'ease';
    var drag = {
      moved: false,
      timer: 0,
      dirX: 0,
      distX: 0,
      dirY: 0,
      distY: 0,
      moveDistX: 0,
      maxMove: itemLen / 2,
      startTime: 0,
      endTime: 0,
      resetMaxMove: function () {
        drag.maxMove = itemLen / 2;
      },
      distPos: function () {
        return drag[vertical ? 'distY' : 'distX'];
      },
      reset: function () {
        drag.moved = false;
        drag.isSwipe = false;
        drag.dirX = 0;
        drag.distX = 0;
        drag.dirY = 0;
        drag.distY = 0;
        drag.timer = 0;
        drag.timer && cancelRequestAnimFrame(drag.timer);
      },
      move: function () {
        if (!drag.moved) {
          return;
        }
        var mX = -(index + (enableLoop ? 1 : 0)) * itemLen,
          dx = Math.round(Math.abs(drag.distPos()) / moveRate);
        drag.moveDistX = dx;
        if (dx > itemLen * 9 / 10) {
          drag.endDrag();
          return;
        } else if (drag.distPos() > 0) {
          mX += dx;
        } else {
          mX -= dx;
        }

        moveToFn(mX, 0, dragAnim);
        lastMove = -mX;
      },
      endDrag: function () {
        drag.moved = false;
        var mX = -index * itemLen,
          dx = drag.moveDistX;
        if (drag.isSwipe) {
          drag.distPos() > 0 ? me.pre() : me.next();
        } else {
          if (drag.distPos() > 0) {
            mX += dx;
          } else {
            mX -= dx;
          }
          if (mX >= 0 || mX <= -(totalLen - itemLen) || dx < drag.maxMove) {
            move();
          } else {
            drag.distPos() > 0 ? me.pre() : me.next();
          }
        }

        drag.reset();
        me.startAutoRun();
      }
    };

    function touchStart(e) {
      if (itemCount < 2 || isMoving) {
        return;
      }
      drag.startTime = new Date().getTime();
      onTouchstart();
      me.stopAutoRun();
      totalLen = totalLen || el.width();
      itemLen = itemLen || (totalLen / itemCount);
      drag.resetMaxMove();
      var touch = e.touches[0];
      drag.moved = true;
      drag.dirX = touch.pageX;
      drag.distX = 0;
      drag.dirY = touch.pageY;
      drag.distY = 0;
      (function animloop() {
        if (!drag.moved) {
          drag.reset();
          return;
        }
        drag.move();
        drag.timer = requestAnimFrame(animloop);
      })();
    }

    function touchMove(e) {
      var touch = e.touches[0];
      drag.distX = touch.pageX - drag.dirX;
      drag.distY = touch.pageY - drag.dirY;
      onTouchmove(Math.abs(drag.distX), Math.abs(drag.distY));
    }

    function touchEnd(e) {
      drag.endTime = new Date().getTime();
      if (drag.moved) {
        drag.isSwipe = drag.endTime - drag.startTime <= 200 && Math.abs(drag.distPos()) > 30;
        drag.endDrag();
      }
      onTouchend(Math.abs(drag.distX), Math.abs(drag.distY));
    }

    if (enableDrag) {
      el.touchstart = el.touchstart || touchStart;
      el.touchmove = el.touchmove || touchMove;
      el.touchend = el.touchend || touchEnd;
      el.off('touchstart', el.touchstart);
      el.off('touchmove', el.touchmove);
      el.off('touchend', el.touchend);
      el.on('touchstart', el.touchstart);
      el.on('touchmove', el.touchmove);
      el.on('touchend', el.touchend);
    }

    function move() {
      if (isMoving) {
        return;
      }
      isMoving = true;
      setTimeout(function () {
        isMoving = false;
      }, moveTimeout);
      if (!enableLoop) {
        if (index > itemCount - 1) {
          index = itemCount - 1;
          onLast(index);
        } else if (index < 0) {
          index = 0;
          onFirst(index);
        }
      }
      var mx = (index + (enableLoop ? 1 : 0)) * itemLen,
        absm = Math.abs(lastMove - mx),
        mtime = Math.min(moveDuration, (moveDuration / itemLen) * absm),
        animate = moveAnim;

      if (drag.isSwipe) {
        var velocity = drag.moveDistX * moveRate / (drag.endTime - drag.startTime);
        mtime = velocity * absm;
        animate = dragAnim;
      }

      lastMove = mx;
      //修正android差1px的问题
      //mx = (mx>0&&$.os.android)?(mx+1):mx;
      moveToFn(-mx, mtime, animate);

      stopLoopHelper();
      if (enableLoop) {
        var loopm;
        if (index > itemCount - 1) {
          loopm = itemLen;
          index = 0;
          lastMove = itemLen;
          onLast(index);
        } else if (index < 0) {
          loopm = itemLen * itemCount;
          index = itemCount - 1;
          onFirst(index);
        }
        loopTimer = loopm !== undefined && setTimeout(function () {
            moveToFn(-loopm);
          }, mtime);
      }
      runProcess();
      addClasses(index);
      onMove(index);
    }

    function moveToX(x, time, anim) {
      moveTo(x, 0, time, anim);
    }

    function moveToY(x, time, anim) {
      moveTo(0, x, time, anim);
    }

    function moveTo(x, y, time, anim) {
      el.css({
        '-webkit-transform': 'translate3d(' + (x || 0) + 'px' + ',' + (y || 0) + 'px,0)',
        '-webkit-transition': '-webkit-transform ' + (time || 0) + 'ms ' + (anim || moveAnim)
      });
    }

    function stopLoopHelper() {
      loopTimer && clearInterval(loopTimer);
    }

    function moveOrientation() {
      calculateSize();
      if (!enableLoop && index == itemCount - 1) {
        orientation = false;
      } else if (index == 0) {
        orientation = true;
      }
      if (!orientation) {
        me.pre();
      } else {
        me.next();
      }
    }

    function renderProcess() {
      if (enableProcess && itemCount > 1) {
        var tmp = [];
        for (var i = 0; i < itemCount; i++) {
          tmp.push('

');
        }
        pEl.html(tmp.join(''));
        pEl.show();
        runProcess();
      }
    }

    function renderLoop() {
      if (enableLoop) {
        el.find('.' + loopCls).remove();
        var cels = [].slice.call(el.children()),
          first = cels.pop().cloneNode(true),
          last = cels.shift().cloneNode(true);
        first.classList.add(loopCls);
        last.classList.add(loopCls);
        el.prepend(first);
        el.append(last);
      }
    }

    function runProcess() {
      if (!enableProcess) {
        return;
      }
      var processChild = pEl.find('div');
      processChild.removeClass('on');
      $(processChild[index]).addClass('on');
    }

    function resetSize() {
      el.find('.' + loopCls).remove();
      itemLen = option.itemLen || 0;
      itemCount = option.itemCount || 0;
      totalLen = option.totalLen || (itemCount * itemLen) || 0;
    }

    function calculateSize() {
      var child = el.children();
      itemLen = itemLen || child.eq(0)[vertical ? 'height' : 'width']();
      itemCount = itemCount || child.length;
      totalLen = totalLen || (itemLen * itemCount);
    }

    this.next = function () {
      if (isMoving) {
        return;
      }
      index++;
      move();
    }

    this.pre = function () {
      if (isMoving) {
        return;
      }
      index--;
      move();
    }

    this.moveTo = function (idx) {
      index = idx;
      move();
    }

    this.reset = function () {
      index = 0;
      orientation = true;
      me.stopAutoRun();
      pEl.hide();
      resetSize();
      calculateSize();
      renderLoop();
      lastMove = enableLoop ? itemLen : 0;
      moveToFn(-lastMove);
      drag.reset();
      renderProcess();
      me.startAutoRun();
      addClasses(index);
      onFirst(index);
      onMove(index);
    }

    this.refresh = function () {
      me.stopAutoRun();
      pEl.hide();
      resetSize();
      calculateSize();
      renderLoop();
      renderProcess();
      me.startAutoRun();
    }

    this.startAutoRun = function () {
      if (enableAutorun && itemCount > 1) {
        autoTimer = setInterval(function () {
          if (drag.moved) {
            return;
          }//如果拖动就停止
          moveOrientation();
        }, 3000);
      }
    }

    this.stopAutoRun = function () {
      autoTimer && clearInterval(autoTimer);
      stopLoopHelper();
    }

    function addClasses(idx){
      idx = enableLoop?(idx+1):idx;
      el.find('.'+currentCls).removeClass(currentCls);
      el.children().eq(idx).addClass(currentCls);
    }

    this.reset();
  }

  return Slider;
});
<|endoftext|>


<commit_before>/**
 * Regexes module
 *
 * Exports useful regular expressions
 */

const REGEXES = {}

REGEXES.EMAIL = /^(?:[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+\.)*[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+@(?:(?:(?:[a-zA-Z0-9](?:[a-zA-Z0-9\-](?!\.)){0,61}[a-zA-Z0-9]?\.)+[a-zA-Z0-9](?:[a-zA-Z0-9\-](?!$)){0,61}[a-zA-Z0-9]?)|(?:\[(?:(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\.){3}(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\]))$/
REGEXES.URL = /https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)/
REGEXES.COLOR = /(#(?:[\da-f]{3}){1,2}|rgb\((?:\d{1,3},\s*){2}\d{1,3}\)|rgba\((?:\d{1,3},\s*){3}\d*\.?\d+\)|hsl\(\d{1,3}(?:,\s*\d{1,3}%){2}\)|hsla\(\d{1,3}(?:,\s*\d{1,3}%){2},\s*\d*\.?\d+\))/i
REGEXES.PHONE = /^[\+]?[(]?[0-9]{3}[)]?[-\s\.]?[0-9]{3}[-\s\.]?[0-9]{4,6}$/im

module.exports = REGEXES<commit_msg>More permissive phone regex<commit_after>/**
 * Regexes module
 *
 * Exports useful regular expressions
 */

const REGEXES = {}

REGEXES.EMAIL = /^(?:[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+\.)*[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+@(?:(?:(?:[a-zA-Z0-9](?:[a-zA-Z0-9\-](?!\.)){0,61}[a-zA-Z0-9]?\.)+[a-zA-Z0-9](?:[a-zA-Z0-9\-](?!$)){0,61}[a-zA-Z0-9]?)|(?:\[(?:(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\.){3}(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\]))$/
REGEXES.URL = /https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)/
REGEXES.COLOR = /(#(?:[\da-f]{3}){1,2}|rgb\((?:\d{1,3},\s*){2}\d{1,3}\)|rgba\((?:\d{1,3},\s*){3}\d*\.?\d+\)|hsl\(\d{1,3}(?:,\s*\d{1,3}%){2}\)|hsla\(\d{1,3}(?:,\s*\d{1,3}%){2},\s*\d*\.?\d+\))/i
REGEXES.PHONE = /^((\+\d{1,3}(-| )?\(?\d\)?(-| )?\d{1,5})|(\(?\d{2,6}\)?))(-| )?(\d{3,4})(-| )?(\d{4})(( x| ext)\d{1,5}){0,1}$/

module.exports = REGEXES<|endoftext|>


<commit_before>var parser = require('parse-whois');
var whois = require('node-whois');

whois.lookup('github.com', function(err, data){
	if (err) throw err;

	console.log(data);

	console.log(parser.parseWhoIsData(data));
});<commit_msg>added host2co changes<commit_after>var parser = require('parse-whois');
var whois = require('node-whois');
var openCorporates = require('opencorporates')()

host = 'xiaomi.com'

company = ''

whois.lookup(host, function(err, data){
	if (err) throw err;
	parsed = parser.parseWhoIsData(data);
	company = parsed[14].value
	console.log(company)
	openCorporates.companies.search('xiamoi Inc', function(err, res){
	console.log(JSON.stringify(res, null, 2))
})
});<|endoftext|>


<commit_before>// console.perf.js
// https://github.com/PolymerLabs/console.perf
// Prints out window.performance information for Web Components

(function () {

  // Cross-browser compatibility
  if (!window.performance) {
    var start = Date.now();
    // only at millisecond precision
    window.performance = {
      now: function () {
        return Date.now() - start
      }
    };
  }

  console.perf = function () {
    if (window.HTMLImports && !HTMLImports.useNative) {
      var fn = console._perf.bind(console);
      if (!CustomElements.ready) {
        addEventListener('HTMLImportsLoaded', fn, true);
      } else {
        HTMLImports.whenReady(fn);
      }
    } else {
      console._perf();
    }
  };

  console._perf = function () {
    if (window.gc) {
      for (var i=0; i<8; i++) {
        gc();
      }
    }
    if (console.time) {
      console.time('perf');
    }
    console.profile();
    console.perf.time = performance.now();
  };

  console.perfEnd = function () {
    // TODO(sorvell): WCR is unnecessarily delayed via setTimeout to workaround
    // https://code.google.com/p/chromium/issues/detail?id=425790.
    // This can add significant noise to benchmarking so avoid the wait
    // if we know we can (native CE).
    // We don't need the workaround for this use case because perfEnd is typically
    // called via a blocking script.
    if (window.WebComponents && !CustomElements.useNative) {
      // TODO(sjmiles): we need some kind of 'whenReady' or other signal
      // that will work if this function is called after the event has fired
      // TODO(addyo): explore further when webcomponentsjs/pull/392 lands.
      if (!CustomElements.ready) {
        addEventListener('WebComponentsReady', function() {
          console._perfEnd();
        });
      } else {
        CustomElements.takeRecords();
        console._perfEnd();
      }
    } else {
      console._perfEnd();
    }
  };

  console._perfEnd = function () {
    // force layout
    document.body.offsetWidth;

    var time = performance.now() - console.perf.time;
    console.profileEnd();

    if (console.time) {
      console.timeEnd('perf');
    }

    document.title = time.toFixed(1) + 'ms: ' + document.title;

    if (window.top !== window) {
      window.top.postMessage(time + 'ms', '*');
    }
  };

})();
<commit_msg>Avoid sticking operators to variables.<commit_after>// console.perf.js
// https://github.com/PolymerLabs/console.perf
// Prints out window.performance information for Web Components

(function () {

  // Cross-browser compatibility
  if (!window.performance) {
    var start = Date.now();
    // only at millisecond precision
    window.performance = {
      now: function () {
        return Date.now() - start
      }
    };
  }

  console.perf = function () {
    if (window.HTMLImports && !HTMLImports.useNative) {
      var fn = console._perf.bind(console);
      if (!CustomElements.ready) {
        addEventListener('HTMLImportsLoaded', fn, true);
      } else {
        HTMLImports.whenReady(fn);
      }
    } else {
      console._perf();
    }
  };

  console._perf = function () {
    if (window.gc) {
      for (var i = 0; i < 8; i++) {
        gc();
      }
    }
    if (console.time) {
      console.time('perf');
    }
    console.profile();
    console.perf.time = performance.now();
  };

  console.perfEnd = function () {
    // TODO(sorvell): WCR is unnecessarily delayed via setTimeout to workaround
    // https://code.google.com/p/chromium/issues/detail?id=425790.
    // This can add significant noise to benchmarking so avoid the wait
    // if we know we can (native CE).
    // We don't need the workaround for this use case because perfEnd is typically
    // called via a blocking script.
    if (window.WebComponents && !CustomElements.useNative) {
      // TODO(sjmiles): we need some kind of 'whenReady' or other signal
      // that will work if this function is called after the event has fired
      // TODO(addyo): explore further when webcomponentsjs/pull/392 lands.
      if (!CustomElements.ready) {
        addEventListener('WebComponentsReady', function() {
          console._perfEnd();
        });
      } else {
        CustomElements.takeRecords();
        console._perfEnd();
      }
    } else {
      console._perfEnd();
    }
  };

  console._perfEnd = function () {
    // force layout
    document.body.offsetWidth;

    var time = performance.now() - console.perf.time;
    console.profileEnd();

    if (console.time) {
      console.timeEnd('perf');
    }

    document.title = time.toFixed(1) + 'ms: ' + document.title;

    if (window.top !== window) {
      window.top.postMessage(time + 'ms', '*');
    }
  };

})();
<|endoftext|>


<commit_before>var assert = require('chai').assert;
var nodemock = require('nodemock');

var utils = require('../../../test-utils');
var groongaUtils = require('./utils');

var express = require('express');
var httpAdapter = require('../../../../lib/adapter/http');
var groongaAPI = require('../../../../lib/adapter/api/groonga');

suite('adapter/api/groonga: basic commands', function() {
  var connection;
  var application;
  var server;
  var backend;

  setup(function(done) {
    utils.setupApplication()
      .then(function(result) {
        backend = result.backend;
        server = result.server;
        connection = result.connection;
        application = result.application;
        httpAdapter.register(application, {
          prefix: '',
          connection: connection,
          plugins: [groongaAPI]
        });
        done();
      })
      .catch(function(error) {
        done(error);
      });
  });

  teardown(function() {
    utils.teardownApplication({
      backend:    backend,
      server:     server,
      connection: connection
    });
  });

  suite('URL suffix', function() {
    test('nothing', function(done) {
      groongaUtils.pushSuccessResponse(backend);
      var body = [
      ]
      utils.get('/d/table_create?name=Users', JSON.stringify(body))
        .then(function(response) {
          assert.deepEqual(response.statusCode, 200);
          done();
        })
        .catch(done);
    });

    test('.json', function(done) {
      groongaUtils.pushSuccessResponse(backend);
      var body = [
      ]
      utils.get('/d/table_create.json?name=Users', JSON.stringify(body))
        .then(function(response) {
          assert.deepEqual(response.statusCode, 200);
          done();
        })
        .catch(done);
    });
  });
});
<commit_msg>Simplify<commit_after>var assert = require('chai').assert;
var nodemock = require('nodemock');

var utils = require('../../../test-utils');
var groongaUtils = require('./utils');

var express = require('express');
var httpAdapter = require('../../../../lib/adapter/http');
var groongaAPI = require('../../../../lib/adapter/api/groonga');

suite('adapter/api/groonga: basic commands', function() {
  var connection;
  var application;
  var server;
  var backend;

  setup(function(done) {
    utils.setupApplication()
      .then(function(result) {
        backend = result.backend;
        server = result.server;
        connection = result.connection;
        application = result.application;
        httpAdapter.register(application, {
          prefix: '',
          connection: connection,
          plugins: [groongaAPI]
        });
        done();
      })
      .catch(done);
  });

  teardown(function() {
    utils.teardownApplication({
      backend:    backend,
      server:     server,
      connection: connection
    });
  });

  suite('URL suffix', function() {
    test('nothing', function(done) {
      groongaUtils.pushSuccessResponse(backend);
      var body = [
      ]
      utils.get('/d/table_create?name=Users', JSON.stringify(body))
        .then(function(response) {
          assert.deepEqual(response.statusCode, 200);
          done();
        })
        .catch(done);
    });

    test('.json', function(done) {
      groongaUtils.pushSuccessResponse(backend);
      var body = [
      ]
      utils.get('/d/table_create.json?name=Users', JSON.stringify(body))
        .then(function(response) {
          assert.deepEqual(response.statusCode, 200);
          done();
        })
        .catch(done);
    });
  });
});
<|endoftext|>


<commit_before>/* global window */
/* eslint no-console: 0 */

import anime from 'animejs';

/**
 * this file contains _functions_ that do RAW DOM manipulations.
 * keeping our React Components _free_ of DOM hassle
 */

/**
 * shows or hides .close-button
 *
 * @param  {Boolean} show
 */
function showCloseButton(show = true) {
  const closeButton = window.document.querySelector('.close-button');

  switch (show) {
    case true:
      closeButton.style.transform = 'translateY(0em)';
      closeButton.style.opacity = '1';
      return;

    case false:
      closeButton.style.opacity = '0';
      setTimeout(() => {
        closeButton.style.transform = 'translateY(-2em)';
      }, 350);
      return;

    default:
      console.warn(`Expected bool, instead got '${typeof show}'`);
  }
}

/**
 * shows or hides .view-movie-background
 * @param  {Boolean} show [description]
 */
function showMovieBackground(show = true) {
  const viewMovieBackground = window.document.querySelector('.view-movie-background');

  switch (show) {
    case true:
      viewMovieBackground.style.transform = 'translateY(0vh)';
      viewMovieBackground.style.opacity = '1';
      return;

    case false:
      viewMovieBackground.style.opacity = '0';
      setTimeout(() => {
        viewMovieBackground.style.transform = 'translateY(100vh)';
      }, 350);
      return;

    default:
      console.warn(`Expected bool, instead got '${typeof show}'`);
  }
}

/**
 * shows or hides .movie-poster
 * @param  {Boolean} show
 * @param  {String} src
 * @return {Promise | undefined}
 */
function showPoster(show = true, src = '') {
  const moviePoster = window.document.querySelector('.movie-poster');

  switch (show) {
    case true: {
      // getting location and dimension of the active poster
      const activePoster = window.document.querySelector('.movie-container.active .poster-container .img-poster');
      const rect = activePoster.getBoundingClientRect();
      const { top, left } = rect; // number
      let width = window.getComputedStyle(activePoster).width; // string
      width = Number(width.substring(0, width.length - 2)); // number
      let screenWidth = window.getComputedStyle(window.document.body).width;
      screenWidth = Number(screenWidth.substring(0, screenWidth.length - 2));

      // overlaying image on the active poster...
      moviePoster.src = src;
      moviePoster.style.top = `${top}px`;
      moviePoster.style.left = `${left}px`;
      moviePoster.style.width = width;
      moviePoster.style.opacity = '1';

      // setting dataset...
      moviePoster.dataset.top = top;
      moviePoster.dataset.left = left;
      moviePoster.dataset.width = width;
      moviePoster.dataset.screenWidth = screenWidth;

      return new Promise((resolve) => {
        // scaling up the movie poster to fill the screen
        anime({
          targets: moviePoster,
          translateY: ['0px', `${top > 0 ? `-${top}` : '0'}px`],
          translateX: ['0px', `-${left}px`],
          width: [`${width}px`, `${screenWidth}px`],
          easing: 'easeOutExpo',
          duration: 750,
          elasticity: 100,
          complete() {
            resolve();
          },
        });
      });
    }

    case false: {
      const { top, left, width, screenWidth } = moviePoster.dataset;

      // setting border radius in the middle of scale-down animation
      setTimeout(() => {
        moviePoster.style.borderRadius = '.25em';
      }, 250);

      return new Promise((resolve) => {
        // scaling-down...
        anime({
          targets: moviePoster,
          translateY: [`-${top}px`, '0px'],
          translateX: [`-${left}px`, '0px'],
          width: [`${screenWidth}px`, `${width}px`],
          easing: 'easeOutExpo',
          duration: 500,
          elasticity: 100,
          complete() {
            // resetting style...
            moviePoster.style.opacity = '0';
            moviePoster.style.top = '0px';
            moviePoster.style.left = '0px';
            moviePoster.style.width = 'auto';
            moviePoster.style.borderRadius = '0em';
            moviePoster.style.transform = 'translateY(100vh)';
            resolve();
          },
        });
      });
    }

    default:
      console.warn(`Expected bool, instead got '${typeof show}'`);
      return typeof show;
  }
}

/**
 * sets .movie-poster src
 *
 * @param {String} src
 */
function setPosterSrc(src = '') {
  window.document.querySelector('.movie-poster').src = src;
}

module.exports = {
  showCloseButton,
  showMovieBackground,
  showPoster,
  setPosterSrc,
};
<commit_msg>why using screenWidth instead of window.screen.width<commit_after>/* global window */
/* eslint no-console: 0 */

import anime from 'animejs';

/**
 * this file contains _functions_ that do RAW DOM manipulations.
 * keeping our React Components _free_ of DOM hassle
 */

/**
 * shows or hides .close-button
 *
 * @param  {Boolean} show
 */
function showCloseButton(show = true) {
  const closeButton = window.document.querySelector('.close-button');

  switch (show) {
    case true:
      closeButton.style.transform = 'translateY(0em)';
      closeButton.style.opacity = '1';
      return;

    case false:
      closeButton.style.opacity = '0';
      setTimeout(() => {
        closeButton.style.transform = 'translateY(-2em)';
      }, 350);
      return;

    default:
      console.warn(`Expected bool, instead got '${typeof show}'`);
  }
}

/**
 * shows or hides .view-movie-background
 * @param  {Boolean} show [description]
 */
function showMovieBackground(show = true) {
  const viewMovieBackground = window.document.querySelector('.view-movie-background');

  switch (show) {
    case true:
      viewMovieBackground.style.transform = 'translateY(0vh)';
      viewMovieBackground.style.opacity = '1';
      return;

    case false:
      viewMovieBackground.style.opacity = '0';
      setTimeout(() => {
        viewMovieBackground.style.transform = 'translateY(100vh)';
      }, 350);
      return;

    default:
      console.warn(`Expected bool, instead got '${typeof show}'`);
  }
}

/**
 * shows or hides .movie-poster
 * @param  {Boolean} show
 * @param  {String} src
 * @return {Promise | undefined}
 */
function showPoster(show = true, src = '') {
  const moviePoster = window.document.querySelector('.movie-poster');

  switch (show) {
    case true: {
      // getting location and dimension of the active poster
      const activePoster = window.document.querySelector('.movie-container.active .poster-container .img-poster');
      const rect = activePoster.getBoundingClientRect();
      const { top, left } = rect; // number
      let width = window.getComputedStyle(activePoster).width; // string
      width = Number(width.substring(0, width.length - 2)); // number
      // Not using window.screen.width because on Safari it returns the Mac's screen width, not
      // the phone width (even in responsive mode)
      let screenWidth = window.getComputedStyle(window.document.body).width;
      screenWidth = Number(screenWidth.substring(0, screenWidth.length - 2));

      // overlaying image on the active poster...
      moviePoster.src = src;
      moviePoster.style.top = `${top}px`;
      moviePoster.style.left = `${left}px`;
      moviePoster.style.width = width;
      moviePoster.style.opacity = '1';

      // setting dataset...
      moviePoster.dataset.top = top;
      moviePoster.dataset.left = left;
      moviePoster.dataset.width = width;
      moviePoster.dataset.screenWidth = screenWidth;

      return new Promise((resolve) => {
        // scaling up the movie poster to fill the screen
        anime({
          targets: moviePoster,
          translateY: ['0px', `${top > 0 ? `-${top}` : '0'}px`],
          translateX: ['0px', `-${left}px`],
          width: [`${width}px`, `${screenWidth}px`],
          easing: 'easeOutExpo',
          duration: 750,
          elasticity: 100,
          complete() {
            resolve();
          },
        });
      });
    }

    case false: {
      const { top, left, width, screenWidth } = moviePoster.dataset;

      // setting border radius in the middle of scale-down animation
      setTimeout(() => {
        moviePoster.style.borderRadius = '.25em';
      }, 250);

      return new Promise((resolve) => {
        // scaling-down...
        anime({
          targets: moviePoster,
          translateY: [`-${top}px`, '0px'],
          translateX: [`-${left}px`, '0px'],
          width: [`${screenWidth}px`, `${width}px`],
          easing: 'easeOutExpo',
          duration: 500,
          elasticity: 100,
          complete() {
            // resetting style...
            moviePoster.style.opacity = '0';
            moviePoster.style.top = '0px';
            moviePoster.style.left = '0px';
            moviePoster.style.width = 'auto';
            moviePoster.style.borderRadius = '0em';
            moviePoster.style.transform = 'translateY(100vh)';
            resolve();
          },
        });
      });
    }

    default:
      console.warn(`Expected bool, instead got '${typeof show}'`);
      return typeof show;
  }
}

/**
 * sets .movie-poster src
 *
 * @param {String} src
 */
function setPosterSrc(src = '') {
  window.document.querySelector('.movie-poster').src = src;
}

module.exports = {
  showCloseButton,
  showMovieBackground,
  showPoster,
  setPosterSrc,
};
<|endoftext|>


<commit_before>app.constant('API', {
  HOST: 'localhost',
  TEAMS: {
    GET_ALL: '/api/teams',
    GET: '/api/team/',
    CREATE: '/api/team/create',
    UPDATE: '/api/team/update',
    DELETE: '/api/team/delete'
  },
  PLAYERS: {
    GET_ALL: '/api/players',
    GET: '/api/player/',
    CREATE: '/api/player/create',
    UPDATE: '/api/player/update',
    DELETE: '/api/player/delete'
  },
  LEADERS: '/api/leaders'
});<commit_msg>fixed api route constants<commit_after>app.constant('API', {
  HOST: 'localhost',
  TEAMS: {
    GET_ALL: '/api/teams',
    GET: '/api/team/',
    CREATE: '/api/team/create',
    UPDATE: '/api/team/update/',
    DELETE: '/api/team/delete/'
  },
  PLAYERS: {
    GET_ALL: '/api/players',
    GET: '/api/player/',
    CREATE: '/api/player/create',
    UPDATE: '/api/player/update/',
    DELETE: '/api/player/delete/'
  },
  LEADERS: '/api/leaders'
});<|endoftext|>


<commit_before>const path = require('path');
const url = require('url');
const electron = require('electron');
const BrowserWindow = electron.BrowserWindow;

function openCredits() {
    var win = new BrowserWindow({ width: 500, height: 400 });
    win.setMenu(null);
    win.loadURL(url.format({
        pathname: path.join(__dirname, 'credits.html'),
        protocol: 'file:',
        slashes: true
    }))
}<commit_msg>deleted unneeded file<commit_after><|endoftext|>


<commit_before>var ghdownload = require('download-github-repo')
  , GitHubApi  = require("github")
  , Promise = require('bluebird')
  , request = require('request')
  , jspm = require('jspm');

var github = new GitHubApi({
  // required
  version: "3.0.0",
  debug: false,
  protocol: "https",
  host: "api.github.com",
  pathPrefix: "",
  timeout: 5000,
  headers: {
    "user-agent": "Aurelia-Github-Loader"
  }
});

var pluginList = null;

function installTemplate(repoName) {
  // find the latest available tag
  return new Promise(function(resolve, reject){

    github.repos.getTags({ user: 'aurelia', repo: repoName, page: 1, per_page: 1 }, function(err, result) {
      if(err !== undefined && err !== null) {
        reject('Failed to get latest release info');
        return;
      }

      if(result.length < 1) {
        reject('No Release-Tags available');
        return;
      }
      console.log('Downloading latest available release: ' + result[0].name);

      // Kick off the repo download
      ghdownload("aurelia/skeleton-navigation#" + result[0].name, "", function(err) {
        if (err !== undefined && err !== null) {
          reject('An error occurred while downloading the template');
          console.log(err);
        } else {
          console.log('Successfully installed template: ' + repoName);
          console.log('Running npm install');
          runNPMInstall(function() {
            console.log('Successfully npm installed');
            console.log('Running jspm install');
            runJSPMInstall(function() {
              console.log('Successfully jspm installed');
              resolve('Installation completed successfully');
            });
          });
        }
      });
    });
  });
}

function runNPMInstall(cb) {
  var npm = require('npm');
  npm.load(function(err) {
    npm.commands.install(['.'], function(er, data) {
      if(er !== undefined && er !== null) {
        console.log(er);
        throw 'Error running NPM install';
      } else {
        cb();
      }
    });

    npm.on("log", function (message) {
      // log the progress of the installation
      console.log(message);
    });
  });
}

function runJSPMInstall(cb) {
  var jspm = require('jspm');
  jspm.configureLoader({ transpiler: 'babel'})
    .then(function() {
      return jspm.dlLoader();
    })
    .then(function() {
      jspm.install(true).then(cb);
    });
}

function _loadPluginList() {
  return new Promise(function(resolve, reject) {
    if(pluginList === null) {
      request.get('https://raw.githubusercontent.com/aurelia/registry/master/plugin-registry.json', function(error, response, body) {
        if (!error && response.statusCode == 200) {
          pluginList = JSON.parse(body).plugins;
          resolve(pluginList);
        } else {
          reject(error);
        }
      });
    } else {
      resolve(pluginList);
    }
  });
}

function getPluginListPrompt() {
  return _loadPluginList().then( (list) => {
    var registry = {};

    list.map( (plugin) => {
      registry[plugin.name] = plugin.name;
    });

    return registry;
  });
}

function getPluginInfo(name) {
  return _loadPluginList().then( (list) => {
    var result = list.filter( (plugin) => {

      return plugin.name === name;
    });

    if(result && result.length > 0) {
      return result[0];
    } else {
      return null;
    }
  });
}

function installPlugin(name, endpoint, location) {
  return new Promise(function(resolve, reject) {
    let user = location.substring(0, location.indexOf('/'))
      , repo = location.substring(location.indexOf('/') + 1);

    github.repos.getTags({user: user, repo: repo, page: 1, per_page: 1}, function(err, result) {
      if (err !== undefined && err !== null) {
        logger.error('blub');
        reject('Failed to get latest release info');
        return;
      }

      let tag = "master";

      if (result.length > 0) {
        tag = "^" + result[0].name;
      }

      jspm.install(name, endpoint + ':' + location + '@^' + tag)

      return jspm.install(name, endpoint + ':' + location + '@' + tag).then( (result) => {

        resolve("Successfully installed plugin " + name + "@" + tag);
      }).catch( (err) => {
        console.log(err);
      });
    });

  });
}

module.exports = {
  installTemplate: installTemplate,
  runNPMInstall: runNPMInstall,
  runJSPMInstall: runJSPMInstall,
  getPluginListPrompt: getPluginListPrompt,
  installPlugin: installPlugin,
  getPluginInfo: getPluginInfo
};
<commit_msg>fix(vm): use ES6 imports and function exports<commit_after>import download from 'download-github-repo';
import GitHubApi  from 'github';
import Promise from 'bluebird';
import request from 'request';
import jspm from 'jspm';

var github = new GitHubApi({
  // required
  version: "3.0.0",
  debug: false,
  protocol: "https",
  host: "api.github.com",
  pathPrefix: "",
  timeout: 5000,
  headers: {
    "user-agent": "Aurelia-Github-Loader"
  }
});

var pluginList = null;

export function installTemplate(repoName) {
  // find the latest available tag
  return new Promise(function(resolve, reject){

    github.repos.getTags({ user: 'aurelia', repo: repoName, page: 1, per_page: 1 }, function(err, result) {
      if(err !== undefined && err !== null) {
        reject('Failed to get latest release info');
        return;
      }

      if(result.length < 1) {
        reject('No Release-Tags available');
        return;
      }
      console.log('Downloading latest available release: ' + result[0].name);

      // Kick off the repo download
      ghdownload("aurelia/skeleton-navigation#" + result[0].name, "", function(err) {
        if (err !== undefined && err !== null) {
          reject('An error occurred while downloading the template');
          console.log(err);
        } else {
          console.log('Successfully installed template: ' + repoName);
          console.log('Running npm install');
          runNPMInstall(function() {
            console.log('Successfully npm installed');
            console.log('Running jspm install');
            runJSPMInstall(function() {
              console.log('Successfully jspm installed');
              resolve('Installation completed successfully');
            });
          });
        }
      });
    });
  });
}

export function runNPMInstall(cb) {
  var npm = require('npm');
  npm.load(function(err) {
    npm.commands.install(['.'], function(er, data) {
      if(er !== undefined && er !== null) {
        console.log(er);
        throw 'Error running NPM install';
      } else {
        cb();
      }
    });

    npm.on("log", function (message) {
      // log the progress of the installation
      console.log(message);
    });
  });
}

export function runJSPMInstall(cb) {
  var jspm = require('jspm');
  jspm.configureLoader({ transpiler: 'babel'})
    .then(function() {
      return jspm.dlLoader();
    })
    .then(function() {
      jspm.install(true).then(cb);
    });
}

function _loadPluginList() {
  return new Promise(function(resolve, reject) {
    if(pluginList === null) {
      request.get('https://raw.githubusercontent.com/aurelia/registry/master/plugin-registry.json', function(error, response, body) {
        if (!error && response.statusCode == 200) {
          pluginList = JSON.parse(body).plugins;
          resolve(pluginList);
        } else {
          reject(error);
        }
      });
    } else {
      resolve(pluginList);
    }
  });
}

export function getPluginListPrompt() {
  return _loadPluginList().then( (list) => {
    var registry = {};

    list.map( (plugin) => {
      registry[plugin.name] = plugin.name;
    });

    return registry;
  });
}

export function getPluginInfo(name) {
  return _loadPluginList().then( (list) => {
    var result = list.filter( (plugin) => {

      return plugin.name === name;
    });

    if(result && result.length > 0) {
      return result[0];
    } else {
      return null;
    }
  });
}

export function installPlugin(name, endpoint, location) {
  return new Promise(function(resolve, reject) {
    let user = location.substring(0, location.indexOf('/'))
      , repo = location.substring(location.indexOf('/') + 1);

    github.repos.getTags({user: user, repo: repo, page: 1, per_page: 1}, function(err, result) {
      if (err !== undefined && err !== null) {
        logger.error('blub');
        reject('Failed to get latest release info');
        return;
      }

      let tag = "master";

      if (result.length > 0) {
        tag = "^" + result[0].name;
      }

      jspm.install(name, endpoint + ':' + location + '@^' + tag)

      return jspm.install(name, endpoint + ':' + location + '@' + tag).then( (result) => {

        resolve("Successfully installed plugin " + name + "@" + tag);
      }).catch( (err) => {
        console.log(err);
      });
    });

  });
}
<|endoftext|>


<commit_before>HUD = function (game, playerInfo, worldInfo) {
	Phaser.Group.call(this, game);

	this.playerInfoView = new PlayerInfoView(game, playerInfo);
	this.homeInfoView = new HomeInfoView(game, null);
	this.worldInfoView = new WorldInfoView(game, playerInfo);
	this.settingsView = new SettingsView(game, playerInfo, worldInfo);

	game.add.existing(this.playerInfoView);
	game.add.existing(this.homeInfoView);
	game.add.existing(this.worldInfoView);
	game.add.existing(this.settingsView);

	this.currentMenu = null;

	this.createHUD(game);
};

HUD.prototype = Object.create(Phaser.Group.prototype);
HUD.prototype.constructor = HUD;

HUD.prototype.createHUD = function (game) {
	this.playerButton = game.add.button((AttackGame.WIDTH / 2) - 100,
		this.game.height - 45, 'playerSymbol',
		this.toggle, this);
	this.playerButton.view = this.playerInfoView;
	this.add(this.playerButton);

	this.homeButton = game.add.button((AttackGame.WIDTH / 2) - 50,
		this.game.height - 45, 'homeSymbol',
		this.toggle, this);
	this.homeButton.view = this.homeInfoView;
	this.add(this.homeButton);

	this.worldButton = game.add.button((AttackGame.WIDTH / 2),
		this.game.height - 45, 'worldSymbol',
		this.toggle, this);
	this.worldButton.view = this.worldInfoView;
	this.add(this.worldButton);

	this.settingsButton = game.add.button((AttackGame.WIDTH / 2) + 50,
		this.game.height - 45, 'settingsSymbol',
		this.toggle, this);
	this.settingsButton.view = this.settingsView;
	this.add(this.settingsButton);

	game.input.keyboard.addKey(Phaser.Keyboard.ESC).onDown.add(
		this.toggle, this.settingsButton);
}

HUD.prototype.toggle = function (button) {

	var turnOff = false;
	if (button.view.visible)
		turnOff = true;

	// hide all
	this.playerInfoView.hide();
	this.homeInfoView.hide();
	this.worldInfoView.hide();
	this.settingsView.hide();

	this.playerButton.frame = 0;
	this.homeButton.frame = 0;
	this.worldButton.frame = 0;
	this.settingsButton.frame = 0;

	if (!turnOff) {
		button.view.show();
		button.frame = 1;
	}
}

HUD.prototype.pauseOn = function () {
	return this.settingsView.pauseOn;
}<commit_msg>last commit for today<commit_after>HUD = function (game, playerInfo, worldInfo) {
	Phaser.Group.call(this, game);

	this.playerInfoView = new PlayerInfoView(game, playerInfo);
	this.homeInfoView = new HomeInfoView(game, null);
	this.worldInfoView = new WorldInfoView(game, playerInfo);
	this.settingsView = new SettingsView(game, playerInfo, worldInfo);

	game.add.existing(this.playerInfoView);
	game.add.existing(this.homeInfoView);
	game.add.existing(this.worldInfoView);
	game.add.existing(this.settingsView);

	this.createHUD(game);
	this.createHotKeys(game);

	//game.input.onDown.add(this.deselect, this);
};

HUD.prototype = Object.create(Phaser.Group.prototype);
HUD.prototype.constructor = HUD;

HUD.prototype.createHUD = function (game) {
	this.playerButton = game.add.button((AttackGame.WIDTH / 2) - 100,
		this.game.height - 45, 'playerSymbol',
		this.toggle, this);
	this.playerButton.view = this.playerInfoView;
	this.add(this.playerButton);

	this.homeButton = game.add.button((AttackGame.WIDTH / 2) - 50,
		this.game.height - 45, 'homeSymbol',
		this.toggle, this);
	this.homeButton.view = this.homeInfoView;
	this.add(this.homeButton);

	this.worldButton = game.add.button((AttackGame.WIDTH / 2),
		this.game.height - 45, 'worldSymbol',
		this.toggle, this);
	this.worldButton.view = this.worldInfoView;
	this.add(this.worldButton);

	this.settingsButton = game.add.button((AttackGame.WIDTH / 2) + 50,
		this.game.height - 45, 'settingsSymbol',
		this.toggle, this);
	this.settingsButton.view = this.settingsView;
	this.add(this.settingsButton);

}

HUD.prototype.deselect = function (mouse) {
	// hide all
	this.playerInfoView.hide();
	this.homeInfoView.hide();
	this.worldInfoView.hide();
	this.settingsView.hide();

	this.playerButton.frame = 0;
	this.homeButton.frame = 0;
	this.worldButton.frame = 0;
	this.settingsButton.frame = 0;
}

HUD.prototype.toggle = function (button) {

	var turnOff = false;
	if (button.view.visible)
		turnOff = true;

	this.deselect();

	if (!turnOff) {
		button.view.show();
		button.frame = 1;
	}
}

HUD.prototype.createHotKeys = function (game) {
	/*var player = game.input.keyboard.addKey(Phaser.Keyboard.P);
	player.button = this.playerButton;
	player.onDown.add(this.toggle, this.button);

	var home = game.input.keyboard.addKey(Phaser.Keyboard.H);
	home.button = this.homeButton;
	home.onDown.add(this.toggle, this.button);

	var world = game.input.keyboard.addKey(Phaser.Keyboard.W);
	world.button = this.worldButton;
	world.onDown.add(this.toggle, this.button);

	var settings = game.input.keyboard.addKey(Phaser.Keyboard.ESC);
	settings.button = this.settingsButton;
	settings.onDown.add(this.toggle, this.button);*/
}

HUD.prototype.pauseOn = function () {
	return this.settingsView.pauseOn;
}<|endoftext|>


<commit_before>"use strict";

// you can use: drawLine(ctx, x1, y1, x2, y2);
// you can use: drawLine(ctx, x1, y1, x2, y2);
// you can use: drawCircle(ctx, x, y, radius);

// Export only these methods
var drawCurve, drawConstruction, drawBezierNodes;

(function () {

    function calcDrawBspline(t, curve, ctx) {
        var m = curve.knots.length;
        var k = 0;
        for (var l = 3; l < (m - 2); l++) {
            if (curve.knots[l].val() >= t) break;
            k++;
        }

        if (t >= curve.knots[2].val() && t < curve.knots[m - 3].val()) {
            var u1 = curve.knots[k + 0].val();
            var u2 = curve.knots[k + 1].val();
            var u3 = curve.knots[k + 2].val();
            var u4 = curve.knots[k + 3].val();
            var u5 = curve.knots[k + 4].val();
            var u6 = curve.knots[k + 5].val();

            var p10 = curve.nodes[k + 0].pos();
            var p20 = curve.nodes[k + 1].pos();
            var p30 = curve.nodes[k + 2].pos();
            var p40 = curve.nodes[k + 3].pos();

            var p21 = p10.multiply((u4 - t) / (u4 - u1)).add(p20.multiply((t - u1) / (u4 - u1)));
            var p31 = p20.multiply((u5 - t) / (u5 - u2)).add(p30.multiply((t - u2) / (u5 - u2)));
            var p41 = p30.multiply((u6 - t) / (u6 - u3)).add(p40.multiply((t - u3) / (u6 - u3)));

            var p32 = p21.multiply((u4 - t) / (u4 - u2)).add(p31.multiply((t - u2) / (u4 - u2)));
            var p42 = p31.multiply((u5 - t) / (u5 - u3)).add(p41.multiply((t - u3) / (u5 - u3)));

            var p43 = p32.multiply((u4 - t) / (u4 - u3)).add(p42.multiply((t - u3) / (u4 - u3)));

            if (ctx) {
                setColors(ctx, 'yellow', 'cyan');
                drawCircle(ctx, p10.x, p10.y, 4);
                drawCircle(ctx, p20.x, p20.y, 4);
                drawCircle(ctx, p30.x, p30.y, 4);
                drawCircle(ctx, p40.x, p40.y, 4);
                drawLine(ctx, p10.x, p10.y, p20.x, p20.y);
                drawLine(ctx, p20.x, p20.y, p30.x, p30.y);
                drawLine(ctx, p30.x, p30.y, p40.x, p40.y);

                setColors(ctx, 'red', 'orange');
                drawCircle(ctx, p21.x, p21.y, 3);
                drawCircle(ctx, p31.x, p31.y, 3);
                drawCircle(ctx, p41.x, p41.y, 3);
                drawLine(ctx, p21.x, p21.y, p31.x, p31.y);
                drawLine(ctx, p31.x, p31.y, p41.x, p41.y);

                setColors(ctx, 'violet', 'pink');
                drawCircle(ctx, p32.x, p32.y, 2);
                drawCircle(ctx, p42.x, p42.y, 2);
                drawLine(ctx, p32.x, p32.y, p42.x, p42.y);

                setColors(ctx, 'green', 'darkgreen');
                drawCircle(ctx, p43.x, p43.y, 4);
            }

            return p43;
        }
    }

    drawCurve = function (ctx, curve) {
        if (curve.nodes.length < 4) return;

        var lknot = curve.knots[2].val();
        var rknot = curve.knots[curve.knots.length - 3].val();

        var samples = 1000;
        var l = calcDrawBspline(lknot, curve);

        for (var i = 1; i < samples; i++) {
            var t = lknot + (rknot - lknot) / samples * i;
            var r = calcDrawBspline(t, curve);
            drawLine(ctx, l.x, l.y, r.x, r.y);
            l = r;
        }
    };

    drawConstruction = function (ctx, curve) {
        calcDrawBspline(curve.timeKnot.val(), curve, ctx);
    };

    drawBezierNodes = function (ctx, curve) {
        // TODO: implement this
    };

})();
<commit_msg>refactoring<commit_after>"use strict";

// you can use: drawLine(ctx, x1, y1, x2, y2);
// you can use: drawLine(ctx, x1, y1, x2, y2);
// you can use: drawCircle(ctx, x, y, radius);

// Export only these methods
var drawCurve, drawConstruction, drawBezierNodes;

(function () {

    function drawBspline(ctx, p10, p20, p30, p40, p21, p31, p41, p32, p42, p43) {
        setColors(ctx, 'yellow', 'cyan');
        drawCircle(ctx, p10.x, p10.y, 4);
        drawCircle(ctx, p20.x, p20.y, 4);
        drawCircle(ctx, p30.x, p30.y, 4);
        drawCircle(ctx, p40.x, p40.y, 4);
        drawLine(ctx, p10.x, p10.y, p20.x, p20.y);
        drawLine(ctx, p20.x, p20.y, p30.x, p30.y);
        drawLine(ctx, p30.x, p30.y, p40.x, p40.y);

        setColors(ctx, 'red', 'orange');
        drawCircle(ctx, p21.x, p21.y, 3);
        drawCircle(ctx, p31.x, p31.y, 3);
        drawCircle(ctx, p41.x, p41.y, 3);
        drawLine(ctx, p21.x, p21.y, p31.x, p31.y);
        drawLine(ctx, p31.x, p31.y, p41.x, p41.y);

        setColors(ctx, 'violet', 'pink');
        drawCircle(ctx, p32.x, p32.y, 2);
        drawCircle(ctx, p42.x, p42.y, 2);
        drawLine(ctx, p32.x, p32.y, p42.x, p42.y);

        setColors(ctx, 'green', 'darkgreen');
        drawCircle(ctx, p43.x, p43.y, 4);
    }

    /**
     * Calculates the point on the line for the value t. If ctx is set, the construction is drawn.
     * @param t
     * @param curve
     * @param ctx
     * @returns The point on the curve
     */
    function calcDrawBspline(t, curve, ctx) {
        var m = curve.knots.length;
        var k = 0;
        for (var l = 3; l < (m - 2); l++) {
            if (curve.knots[l].val() >= t) break;
            k++;
        }

        if (t >= curve.knots[2].val() && t < curve.knots[m - 3].val()) {
            var u1 = curve.knots[k + 0].val();
            var u2 = curve.knots[k + 1].val();
            var u3 = curve.knots[k + 2].val();
            var u4 = curve.knots[k + 3].val();
            var u5 = curve.knots[k + 4].val();
            var u6 = curve.knots[k + 5].val();

            var p10 = curve.nodes[k + 0].pos();
            var p20 = curve.nodes[k + 1].pos();
            var p30 = curve.nodes[k + 2].pos();
            var p40 = curve.nodes[k + 3].pos();

            var p21 = p10.multiply((u4 - t) / (u4 - u1)).add(p20.multiply((t - u1) / (u4 - u1)));
            var p31 = p20.multiply((u5 - t) / (u5 - u2)).add(p30.multiply((t - u2) / (u5 - u2)));
            var p41 = p30.multiply((u6 - t) / (u6 - u3)).add(p40.multiply((t - u3) / (u6 - u3)));

            var p32 = p21.multiply((u4 - t) / (u4 - u2)).add(p31.multiply((t - u2) / (u4 - u2)));
            var p42 = p31.multiply((u5 - t) / (u5 - u3)).add(p41.multiply((t - u3) / (u5 - u3)));

            var p43 = p32.multiply((u4 - t) / (u4 - u3)).add(p42.multiply((t - u3) / (u4 - u3)));

            if (ctx) drawBspline(ctx, p10, p20, p30, p40, p21, p31, p41, p32, p42, p43);

            return p43;
        }
    }

    drawCurve = function (ctx, curve) {
        if (curve.nodes.length < 4) return;

        var lknot = curve.knots[2].val();
        var rknot = curve.knots[curve.knots.length - 3].val();

        var samples = 1000;
        var l = calcDrawBspline(lknot, curve);

        for (var i = 1; i < samples; i++) {
            var t = lknot + (rknot - lknot) / samples * i;
            var r = calcDrawBspline(t, curve);
            drawLine(ctx, l.x, l.y, r.x, r.y);
            l = r;
        }
    };

    drawConstruction = function (ctx, curve) {
        calcDrawBspline(curve.timeKnot.val(), curve, ctx);
    };

    drawBezierNodes = function (ctx, curve) {
        // TODO: implement this
    };

})();
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  View,
  Image
} from 'react-native';

export default class Shortsdag extends Component {
  constructor(props) {
    super(props);

    this.state = {
      forecast: null
    };

    const success = pos => {
      const url = '/api/forecast/'
            + pos.coords.latitude +'/'
            + pos.coords.longitude + '/';
      fetch('http://localhost:8999' + url)
        .then(response => response.json())
        .then(data => {
          this.setState({forecast: data});
        });
    };

    const error = err => {
      const url = '/api/forecast/';
      fetch('http://localhost:8999' + url)
        .then(response => response.json())
        .then(data => {
          this.setState({forecast: data});
        });
    };

    const options = {
      timeout: 5000,
      maximumAge: 60000
    };

    navigator.geolocation.getCurrentPosition(success, error, options)
  }

  render() {
    let forecastImage, forecastText;
    if (this.state.forecast) {
      const weather = this.state.forecast.weather;
      if (weather === 'shorts') {
        forecastImage = require('./images/bg_shorts.jpg');
        forecastText = 'Det er shortsdag!';
      } else if (weather === 'pants') {
        forecastImage = require('./images/bg_pants.jpg');
        forecastText = 'Det er ikke shortsdag :('
      } else if (weather === 'freezing') {
        forecastImage = require('./images/bg_cold.jpg');
        forecastText = 'Det er ikke shortsdag :('
      } else if (weather === 'snow') {
        forecastImage = require('./images/bg_snow.jpg');
        forecastText = 'Det er ikke shortsdag :('
      } else if (weather === 'rain') {
        forecastImage = require('./images/bg_rain.jpg');
        forecastText = 'Det er ikke shortsdag :('
      }
    }

    return (
      <View style={styles.container}>
        { this.state.forecast
          ? <Image style={styles.background} source={forecastImage}>
              <Text style={styles.shortsdag}>
                {forecastText}
              </Text>
            </Image>
          : <Text style={styles.loading}>
              Kikker ut vinduet...
            </Text>
        }
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  background: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    resizeMode: 'contain',
  },
  loading: {
    margin: 10,
    fontSize: 30,
    textAlign: 'center',
  },
  shortsdag: {
    fontSize: 30,
    textAlign: 'center',
    color: '#ffffff',
    backgroundColor: 'transparent',
  },
  notshortsdag: {
    fontSize: 30,
    textAlign: 'center',
    color: '#ffffff',
    backgroundColor: 'transparent',
  },
});

AppRegistry.registerComponent('Shortsdag', () => Shortsdag);
<commit_msg>Reload forecast on launch<commit_after>import React, { Component } from 'react';
import {
  AppRegistry,
  AppState,
  StyleSheet,
  Text,
  View,
  Image
} from 'react-native';

const apiURL = 'https://shortsdag.no';

export default class Shortsdag extends Component {
  constructor(props) {
    super(props);

    this.state = {
      appState: AppState.currentState,
      forecast: null,
    };

    this.updateForecast();
  }

  updateForecast() {
    const success = async pos => {
      const url = '/api/forecast/'
            + pos.coords.latitude +'/'
            + pos.coords.longitude + '/';
      const response = await fetch(apiURL + url);
      const data = await response.json();
      this.setState({forecast: data});
    };

    const error = async err => {
      const url = '/api/forecast/';
      const response = await fetch(apiURL + url);
      const data = await response.json();
      this.setState({forecast: data});
    };

    const options = {
      timeout: 5000,
      maximumAge: 60000
    };

    navigator.geolocation.getCurrentPosition(success, error, options)
  }

  componentDidMount() {
    AppState.addEventListener('change', this._handleAppStateChange);
  }

  componentWillUnmount() {
    AppState.removeEventListener('change', this._handleAppStateChange);
  }

  _handleAppStateChange = nextAppState => {
    if (this.state.appState.match(/inactive|background/) && nextAppState === 'active') {
      this.setState({forecast: null});
      this.updateForecast();
    }
    this.setState({appState: nextAppState});
  };

  render() {
    let forecastImage, forecastText;
    if (this.state.forecast) {
      const weather = this.state.forecast.weather;
      if (weather === 'shorts') {
        forecastImage = require('./images/bg_shorts.jpg');
        forecastText = 'Det er shortsdag!';
      } else if (weather === 'pants') {
        forecastImage = require('./images/bg_pants.jpg');
        forecastText = 'Det er ikke shortsdag :('
      } else if (weather === 'freezing') {
        forecastImage = require('./images/bg_cold.jpg');
        forecastText = 'Det er ikke shortsdag :('
      } else if (weather === 'snow') {
        forecastImage = require('./images/bg_snow.jpg');
        forecastText = 'Det er ikke shortsdag :('
      } else if (weather === 'rain') {
        forecastImage = require('./images/bg_rain.jpg');
        forecastText = 'Det er ikke shortsdag :('
      }
    }

    return (
      <View style={styles.container}>
        { this.state.forecast
          ? <Image style={styles.background} source={forecastImage}>
              <Text style={styles.shortsdag}>
                {forecastText}
              </Text>
            </Image>
          : <Text style={styles.loading}>
              Kikker ut vinduet...
            </Text>
        }
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  background: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    resizeMode: 'contain',
  },
  loading: {
    margin: 10,
    fontSize: 30,
    textAlign: 'center',
  },
  shortsdag: {
    fontSize: 30,
    textAlign: 'center',
    color: '#ffffff',
    backgroundColor: 'transparent',
  },
  notshortsdag: {
    fontSize: 30,
    textAlign: 'center',
    color: '#ffffff',
    backgroundColor: 'transparent',
  },
});

AppRegistry.registerComponent('Shortsdag', () => Shortsdag);
<|endoftext|>