<commit_before>var v = "1.3";
if ('undefined' === typeof window) {
    importScripts('manifest.js');
}
this.addEventListener('install', function (event) {
    console.log("install event");
    event.waitUntil(
        caches.open(v).then(function (cache) {
            //return cache.addAll([
            //    '/app/view1/view1.html',
            //    '/app/view2/view2.html',
            //    '/app/view1/fallback.html'
            //]);
            return cache.addAll(OFFLINK_STATIC_CACHE);
        })
    );
});

this.addEventListener('fetch', function (event) {
    console.log("fetch event");
    var response;
    event.respondWith(caches.match(event.request)/**.catch(function () {
        console.log(event.request);
        return fetch(event.request);
    })**/.then(function (r) {
            response = r;
            if (r) {
                return r;
            } else {
                return fetch(event.request).then(function (response) {
                    console.log('Response from network is:', response);
                    caches.open(v).then(function (cache) {
                        cache.put(event.request, response);
                    });
                    return response.clone();
                }).catch(function (error) {
                    // This catch() will handle exceptions thrown from the fetch() operation.
                    // Note that a HTTP error response (e.g. 404) will NOT trigger an exception.
                    // It will return a normal response object that has the appropriate error code set.
                    console.error('Fetching failed:', error);
                    console.log("fallback!");
                    return caches.match('/app/view1/fallback.html');
                    //throw error;
                });
                //
                //console.log("responseeeeee : " + r);
                //caches.open(v).then(function (cache) {
                //    cache.put(event.request, response);
                //});
            }
            //return response.clone();
        }));
    //.catch(function () {
    //    console.log("fallback!");
    //    return caches.match('/app/view1/fallback.html');
    //}));
    //console.log("EVENT URL : " + event.request.url);
    var prefix = self.location.protocol + "//" + self.location.hostname + (self.location.port ? ':' + self.location.port : '');
    var rel_path = (event.request.url + "").split(prefix)[0];
    console.log("rel path " + rel_path);
    if (OFFLINK_DYNAMIC_CACHE[event.request.url] != null) {
        fetch(OFFLINK_DYNAMIC_CACHE[event.request.url]).then(function (r) {
            cache.put(OFFLINK_DYNAMIC_CACHE[event.request.url], r);
        });
    }
});

this.addEventListener('activate', function (event) {
    var cacheWhitelist = [v];
    console.log("activate event");
    console.log(cacheWhitelist);
    event.waitUntil(
        caches.keys().then(function (keyList) {
            return Promise.all(keyList.map(function (key) {
                console.log(typeof key);
                if (cacheWhitelist.indexOf(key) === -1) {
                    console.log(cacheWhitelist.indexOf(key));
                    return caches.delete(key);
                }
            }));
        })
    );
});<commit_msg>Remove old cache<commit_after>var v = "1.3";
if ('undefined' === typeof window) {
    importScripts('manifest.js');
}
this.addEventListener('install', function (event) {
    console.log("install event");
    event.waitUntil(
        caches.open(v).then(function (cache) {
            //return cache.addAll([
            //    '/app/view1/view1.html',
            //    '/app/view2/view2.html',
            //    '/app/view1/fallback.html'
            //]);
            return cache.addAll(OFFLINK_STATIC_CACHE);
        })
    );
});

this.addEventListener('fetch', function (event) {
    console.log("fetch event");
    var response;
    event.respondWith(caches.match(event.request)/**.catch(function () {
        console.log(event.request);
        return fetch(event.request);
    })**/.then(function (r) {
            response = r;
            if (r) {
                return r;
            } else {
                return fetch(event.request).then(function (response) {
                    console.log('Response from network is:', response);
                    caches.open(v).then(function (cache) {
                        cache.put(event.request, response);
                    });
                    return response.clone();
                }).catch(function (error) {
                    // This catch() will handle exceptions thrown from the fetch() operation.
                    // Note that a HTTP error response (e.g. 404) will NOT trigger an exception.
                    // It will return a normal response object that has the appropriate error code set.
                    console.error('Fetching failed:', error);
                    console.log("fallback!");
                    return caches.match('/app/view1/fallback.html');
                    //throw error;
                });
                //
                //console.log("responseeeeee : " + r);
                //caches.open(v).then(function (cache) {
                //    cache.put(event.request, response);
                //});
            }
            //return response.clone();
        }));
    //.catch(function () {
    //    console.log("fallback!");
    //    return caches.match('/app/view1/fallback.html');
    //}));
    //console.log("EVENT URL : " + event.request.url);
    var prefix = self.location.protocol + "//" + self.location.hostname + (self.location.port ? ':' + self.location.port : '');
    var rel_path = (event.request.url + "").split(prefix)[1];
    console.log("rel path " + rel_path);
    if (OFFLINK_DYNAMIC_CACHE[event.request.url] != null) {
        fetch(OFFLINK_DYNAMIC_CACHE[event.request.url]).then(function (r) {
            cache.put(OFFLINK_DYNAMIC_CACHE[event.request.url], r);
        });
    }
});

this.addEventListener('activate', function (event) {
    var cacheWhitelist = [v];
    console.log("activate event");
    console.log(cacheWhitelist);
    event.waitUntil(
        caches.keys().then(function (keyList) {
            return Promise.all(keyList.map(function (key) {
                console.log(typeof key);
                if (cacheWhitelist.indexOf(key) === -1) {
                    console.log(cacheWhitelist.indexOf(key));
                    return caches.delete(key);
                }
            }));
        })
    );
});<|endoftext|>


<commit_before>;(function(window, undefined){

  var matches;

  (function(doc) {
     matches =
        doc.matchesSelector ||
        doc.webkitMatchesSelector ||
        doc.mozMatchesSelector ||
        doc.oMatchesSelector ||
        doc.msMatchesSelector;
  })(document.documentElement);

  // simple implementation of $(document).delegate
  function delegate(event, selector, callback) {
    document.addEventListener(event, function(e){
      if (matches.call(e.target, selector)) {
        callback.call(e.target, e);
      }
    });
  }

  //Form Submit
  function sendProtectedForm(event) {
    // looking for closest .js-protected-form block
    var container = this;
    do {
      container = container.parentNode;
    }
    while (!container.className.match('js-protected-form'));
    var form = document.getElementById(container.id + '_form').firstChild;
    var submitEvent = new Event('submit', {
      'bubbles'    : true,
      'cancelable' : true
    });

    // change html structure: return content into form
    container.parentNode.insertBefore(form, container[0]);
    form.firstChild.appendChild(container);

    // and than trigger submit for this form
    form.dispatchEvent(submitEvent);
    if (event) {
      // Prevent double submit event
      event.preventDefault();
    }
    return false;
  }

  delegate('click', '.js-protected-form input[type=submit]', sendProtectedForm);
  delegate('keyup', '.js-protected-form input[type=text], .js-protected-form input[type=email]', function(e){
    if (e.keyCode == 13) {
      sendProtectedForm.call(e.target);
    }
  });
}(this));<commit_msg>JS rework (compatible with IE; without double-submit issues)<commit_after>;(function(window, undefined){

  var matches;

  (function(doc) {
    matches =
      doc.matchesSelector ||
      doc.webkitMatchesSelector ||
      doc.mozMatchesSelector ||
      doc.oMatchesSelector ||
      doc.msMatchesSelector;
  })(document.documentElement);

  // Simple implementation of $(document).delegate
  function delegate(event, selector, callback) {
    document.addEventListener(event, function(e){
      if (matches.call(e.target, selector)) {
        callback.call(e.target, e);
      }
    });
  }

  //Form Submit
  function sendProtectedForm() {
    // Looking for closest .js-protected-form block
    var container = this;
    do {
      container = container.parentNode;
    }
    while (!container.className.match('js-protected-form'));
    var form = document.getElementById(container.id + '_form').firstChild;

    // Change html structure: return content into form
    container.parentNode.insertBefore(form, container);
    form.firstChild.appendChild(container);

    // Fix for IE when using certain versions of pjax libraries and losing focus
    document.body.focus();

    return false;
  }

  delegate('click', '.js-protected-form input[type=submit]', sendProtectedForm);
  delegate('keyup', '.js-protected-form input[type=text], .js-protected-form input[type=email]', function(e){
    if (e.keyCode == 13) {
      sendProtectedForm.call(e.target);
    }
  });
}(this));
<|endoftext|>


<commit_before>/**
 * Base Avatar
 *
 * @param {Player} player
 */
function BaseAvatar(player)
{
    EventEmitter.call(this);

    this.id              = player.id;
    this.name            = player.name;
    this.color           = player.color;
    this.player          = player;
    this.x               = 0;
    this.y               = 0;
    this.trail           = new Trail(this);
    this.bonusStack      = new BonusStack(this);
    this.angle           = 0;
    this.velocityX       = 0;
    this.velocityY       = 0;
    this.angularVelocity = 0;
    this.alive           = true;
    this.printing        = false;
    this.score           = 0;
    this.roundScore      = 0;
    this.ready           = false;
    this.present         = true;

    // useless too? this.updateVelocities();
}

BaseAvatar.prototype = Object.create(EventEmitter.prototype);
BaseAvatar.prototype.constructor = BaseAvatar;

/**
 * Movement velocity
 *
 * @type {Number}
 */
BaseAvatar.prototype.velocity = 16;

/**
 * Turn velocity
 *
 * @type {Float}
 */
BaseAvatar.prototype.angularVelocityBase = 2.8/1000;

/**
 * Radius
 *
 * @type {Number}
 */
BaseAvatar.prototype.radius = 0.6;

/**
 * Number of trail points that don't kill the player
 *
 * @type {Number}
 */
BaseAvatar.prototype.trailLatency = 3;

/**
 * Inverted controls
 *
 * @type {Boolean}
 */
BaseAvatar.prototype.inverse = false;

/**
 * Invincible
 *
 * @type {Boolean}
 */
BaseAvatar.prototype.invincible = false;

/**
 * Type of tunrn: round or straight
 *
 * @type {Boolean}
 */
BaseAvatar.prototype.directionInLoop = true;

/**
 * Equal
 *
 * @param {Avatar} avatar
 *
 * @return {Boolean}
 */

 function sp1(){
	 BaseAvatar.prototype.speed = true;
 }

BaseAvatar.prototype.equal = function(avatar)
{
    return this.id === avatar.id;
};

/**
 * Set Point
 *
 * @param {Float} x
 * @param {Float} y
 */
BaseAvatar.prototype.setPosition = function(x, y)
{
    this.x = x;
    this.y = y;
};

/**
 * Add point
 *
 * @param {Float} x
 * @param {Float} y
 */
BaseAvatar.prototype.addPoint = function(x, y)
{
    this.trail.addPoint(x, y);
};

/**
 * Update angular velocity
 *
 * @param {Number} factor
 */
BaseAvatar.prototype.updateAngularVelocity = function(factor)
{
    if (typeof(factor) === 'undefined') {
        if (this.angularVelocity === 0) { return; }
        factor = (this.angularVelocity > 0 ? 1 : -1) * (this.inverse ? -1 : 1);
    }

    this.setAngularVelocity(factor * this.angularVelocityBase * (this.inverse ? -1 : 1));
};

/**
 * Set angular velocity
 *
 * @param {Float} angularVelocity
 */
BaseAvatar.prototype.setAngularVelocity = function(angularVelocity)
{
    this.angularVelocity = angularVelocity;
};

/**
 * Set angle
 *
 * @param {Float} angle
 */
BaseAvatar.prototype.setAngle = function(angle)
{
    if (this.angle !== angle) {
        this.angle = angle;
        this.updateVelocities();
    }
};

/**
 * Update
 *
 * @param {Number} step
 */
BaseAvatar.prototype.update = function(step) {};

/**
 * Add angle
 *
 * @param {Number} step
 */
BaseAvatar.prototype.updateAngle = function(step)
{
    if (this.angularVelocity) {
        if (this.directionInLoop) {
            this.setAngle(this.angle + this.angularVelocity * step);
        } else {
            this.setAngle(this.angle + this.angularVelocity * step);
            this.updateAngularVelocity(0);

        }
    }
};

/**
 * Update position
 *
 * @param {Number} step
 */
BaseAvatar.prototype.updatePosition = function(step)
{

    this.setPosition(
        this.x + this.velocityX * step,
        this.y + this.velocityY * step
    );
};

/**
 * Set velocity
 *
 * @param {Number} step
 */
BaseAvatar.prototype.setVelocity = function(velocity)
{
	if (BaseAvatar.prototype.speed === true) {
		BaseAvatar.prototype.velocity = 66;
		console.log('speedsuccess!');
	}
    velocity = Math.max(velocity, BaseAvatar.prototype.velocity/2);

    if (this.velocity !== velocity) {
        this.velocity = velocity;
        this.updateVelocities();
    }
};

/**
 * Update velocities
 */
BaseAvatar.prototype.updateVelocities = function()
{

    var velocity = this.velocity/1000;

    this.velocityX = Math.cos(this.angle) * velocity;
    this.velocityY = Math.sin(this.angle) * velocity;

    this.updateBaseAngularVelocity();
};

/**
 * Update base angular velocity
 */
BaseAvatar.prototype.updateBaseAngularVelocity = function()
{
    if (this.directionInLoop) {
        var ratio = this.velocity / BaseAvatar.prototype.velocity;
        this.angularVelocityBase = ratio*1.4 * BaseAvatar.prototype.angularVelocityBase + Math.log(1/ratio)/3000;
        this.updateAngularVelocity();
    }
};

/**
 * Set radius
 *
 * @param {Number} radius
 */
BaseAvatar.prototype.setRadius = function(radius)
{
    this.radius = Math.max(radius, BaseAvatar.prototype.radius/8);
};

/**
 * Set inverse
 *
 * @param {Number} inverse
 */
BaseAvatar.prototype.setInverse = function(inverse)
{
    if (this.inverse !== inverse) {
        this.inverse = inverse ? true : false;
        this.updateAngularVelocity();
    }
};

/**
 * Set invincible
 *
 * @param {Number} invincible
 */
BaseAvatar.prototype.setInvincible = function(invincible)
{
    this.invincible = invincible ? true : false;
};

/**
 * Get distance
 *
 * @param {Number} fromX
 * @param {Number} fromY
 * @param {Number} toX
 * @param {Number} toY
 *
 * @return {Number}
 */
BaseAvatar.prototype.getDistance = function(fromX, fromY, toX, toY)
{
    return Math.sqrt(Math.pow(fromX - toX, 2) + Math.pow(fromY - toY, 2));
};

/**
 * Die
 */
BaseAvatar.prototype.die = function()
{
    this.bonusStack.clear();
    this.alive = false;
    this.addPoint(this.x, this.y);
};

/**
 * Set printing
 *
 * @param {Boolean} printing
 */
BaseAvatar.prototype.setPrinting = function(printing)
{
    printing = printing ? true : false;

    if (this.printing !== printing) {
        this.printing = printing;

        this.addPoint(this.x, this.y, true);

        if (!this.printing) {
            this.trail.clear();
        }
    }
};

/**
 * This score
 *
 * @param {Number} score
 */
BaseAvatar.prototype.addScore = function(score)
{
    this.setRoundScore(this.roundScore + score);
};

/**
 * Resolve score
 *
 * @param {Number} score
 */
BaseAvatar.prototype.resolveScore = function()
{
    this.setScore(this.score + this.roundScore);
    this.roundScore = 0;
};

/**
 * This round score
 *
 * @param {Number} score
 */
BaseAvatar.prototype.setRoundScore = function(score)
{
    this.roundScore = score;
};

/**
 * This score
 *
 * @param {Number} score
 */
BaseAvatar.prototype.setScore = function(score)
{
    this.score = score;
};

/**
 * Set color
 *
 * @param {Number} color
 */
BaseAvatar.prototype.setColor = function(color)
{
    this.color = color;
};

/**
 * Clear
 */
BaseAvatar.prototype.clear = function()
{
    this.bonusStack.clear();

    this.x                   = this.radius;
    this.y                   = this.radius;
    this.angle               = 0;
    this.velocityX           = 0;
    this.velocityY           = 0;
    this.angularVelocity     = 0;
    this.roundScore          = 0;
    this.velocity            = BaseAvatar.prototype.velocity;
    this.alive               = true;
    this.printing            = false;
    this.color               = this.player.color;
    this.radius              = BaseAvatar.prototype.radius;
    this.inverse             = BaseAvatar.prototype.inverse;
    this.invincible          = BaseAvatar.prototype.invincible;
    this.directionInLoop     = BaseAvatar.prototype.directionInLoop;
    this.angularVelocityBase = BaseAvatar.prototype.angularVelocityBase;

    if (this.body) {
        this.body.radius = BaseAvatar.prototype.radius;
    }

    // useless? this.updateVelocities();
};

/**
 * Destroy
 */
BaseAvatar.prototype.destroy = function()
{
    this.clear();
    this.present = false;
    this.alive   = false;
};

/**
 * Serialize
 *
 * @return {Object}
 */
BaseAvatar.prototype.serialize = function()
{
    return {
        id: this.id,
        name: this.name,
        color: this.color,
        score: this.score
    };
};
<commit_msg>asfsa<commit_after>/**
 * Base Avatar
 *
 * @param {Player} player
 */
function BaseAvatar(player)
{
    EventEmitter.call(this);

    this.id              = player.id;
    this.name            = player.name;
    this.color           = player.color;
    this.player          = player;
    this.x               = 0;
    this.y               = 0;
    this.trail           = new Trail(this);
    this.bonusStack      = new BonusStack(this);
    this.angle           = 0;
    this.velocityX       = 0;
    this.velocityY       = 0;
    this.angularVelocity = 0;
    this.alive           = true;
    this.printing        = false;
    this.score           = 0;
    this.roundScore      = 0;
    this.ready           = false;
    this.present         = true;

    // useless too? this.updateVelocities();
}

BaseAvatar.prototype = Object.create(EventEmitter.prototype);
BaseAvatar.prototype.constructor = BaseAvatar;

/**
 * Movement velocity
 *
 * @type {Number}
 */
BaseAvatar.prototype.velocity = 16;

/**
 * Turn velocity
 *
 * @type {Float}
 */
BaseAvatar.prototype.angularVelocityBase = 2.8/1000;

/**
 * Radius
 *
 * @type {Number}
 */
BaseAvatar.prototype.radius = 0.6;

/**
 * Number of trail points that don't kill the player
 *
 * @type {Number}
 */
BaseAvatar.prototype.trailLatency = 3;

/**
 * Inverted controls
 *
 * @type {Boolean}
 */
BaseAvatar.prototype.inverse = false;

/**
 * Invincible
 *
 * @type {Boolean}
 */
BaseAvatar.prototype.invincible = false;

/**
 * Type of tunrn: round or straight
 *
 * @type {Boolean}
 */
BaseAvatar.prototype.directionInLoop = true;

/**
 * Equal
 *
 * @param {Avatar} avatar
 *
 * @return {Boolean}
 */

 function sp1(){
	 BaseAvatar.prototype.speed = true;
 }
  function sp2(){

 }

BaseAvatar.prototype.equal = function(avatar)
{
    return this.id === avatar.id;
};

/**
 * Set Point
 *
 * @param {Float} x
 * @param {Float} y
 */
BaseAvatar.prototype.setPosition = function(x, y)
{
    this.x = x;
    this.y = y;
};

/**
 * Add point
 *
 * @param {Float} x
 * @param {Float} y
 */
BaseAvatar.prototype.addPoint = function(x, y)
{
    this.trail.addPoint(x, y);
};

/**
 * Update angular velocity
 *
 * @param {Number} factor
 */
BaseAvatar.prototype.updateAngularVelocity = function(factor)
{
    if (typeof(factor) === 'undefined') {
        if (this.angularVelocity === 0) { return; }
        factor = (this.angularVelocity > 0 ? 1 : -1) * (this.inverse ? -1 : 1);
    }

    this.setAngularVelocity(factor * this.angularVelocityBase * (this.inverse ? -1 : 1));
};

/**
 * Set angular velocity
 *
 * @param {Float} angularVelocity
 */
BaseAvatar.prototype.setAngularVelocity = function(angularVelocity)
{
    this.angularVelocity = angularVelocity;
};

/**
 * Set angle
 *
 * @param {Float} angle
 */
BaseAvatar.prototype.setAngle = function(angle)
{
    if (this.angle !== angle) {
        this.angle = angle;
        this.updateVelocities();
    }
};

/**
 * Update
 *
 * @param {Number} step
 */
BaseAvatar.prototype.update = function(step) {};

/**
 * Add angle
 *
 * @param {Number} step
 */
BaseAvatar.prototype.updateAngle = function(step)
{
    if (this.angularVelocity) {
        if (this.directionInLoop) {
            this.setAngle(this.angle + this.angularVelocity * step);
        } else {
            this.setAngle(this.angle + this.angularVelocity * step);
            this.updateAngularVelocity(0);

        }
    }
};

/**
 * Update position
 *
 * @param {Number} step
 */
BaseAvatar.prototype.updatePosition = function(step)
{

    this.setPosition(
        this.x + this.velocityX * step,
        this.y + this.velocityY * step
    );
};

/**
 * Set velocity
 *
 * @param {Number} step
 */
BaseAvatar.prototype.setVelocity = function(velocity)
{
	if (BaseAvatar.prototype.speed === true) {
		BaseAvatar.prototype.velocity = 66;
		console.log('speedsuccess!');
	}
    velocity = Math.max(velocity, BaseAvatar.prototype.velocity/2);

    if (this.velocity !== velocity) {
        this.velocity = velocity;
        this.updateVelocities();
    }
};

/**
 * Update velocities
 */
BaseAvatar.prototype.updateVelocities = function()
{

    var velocity = this.velocity/1000;

    this.velocityX = Math.cos(this.angle) * velocity;
    this.velocityY = Math.sin(this.angle) * velocity;

    this.updateBaseAngularVelocity();
};

/**
 * Update base angular velocity
 */
BaseAvatar.prototype.updateBaseAngularVelocity = function()
{
    if (this.directionInLoop) {
        var ratio = this.velocity / BaseAvatar.prototype.velocity;
        this.angularVelocityBase = ratio*1.4 * BaseAvatar.prototype.angularVelocityBase + Math.log(1/ratio)/3000;
        this.updateAngularVelocity();
    }
};

/**
 * Set radius
 *
 * @param {Number} radius
 */
BaseAvatar.prototype.setRadius = function(radius)
{
    this.radius = Math.max(radius, BaseAvatar.prototype.radius/8);
};

/**
 * Set inverse
 *
 * @param {Number} inverse
 */
BaseAvatar.prototype.setInverse = function(inverse)
{
    if (this.inverse !== inverse) {
        this.inverse = inverse ? true : false;
        this.updateAngularVelocity();
    }
};

/**
 * Set invincible
 *
 * @param {Number} invincible
 */
BaseAvatar.prototype.setInvincible = function(invincible)
{
    this.invincible = invincible ? true : false;
};

/**
 * Get distance
 *
 * @param {Number} fromX
 * @param {Number} fromY
 * @param {Number} toX
 * @param {Number} toY
 *
 * @return {Number}
 */
BaseAvatar.prototype.getDistance = function(fromX, fromY, toX, toY)
{
    return Math.sqrt(Math.pow(fromX - toX, 2) + Math.pow(fromY - toY, 2));
};

/**
 * Die
 */
BaseAvatar.prototype.die = function()
{
    this.bonusStack.clear();
    this.alive = false;
    this.addPoint(this.x, this.y);
};

/**
 * Set printing
 *
 * @param {Boolean} printing
 */
BaseAvatar.prototype.setPrinting = function(printing)
{
    printing = printing ? true : false;

    if (this.printing !== printing) {
        this.printing = printing;

        this.addPoint(this.x, this.y, true);

        if (!this.printing) {
            this.trail.clear();
        }
    }
};

/**
 * This score
 *
 * @param {Number} score
 */
BaseAvatar.prototype.addScore = function(score)
{
    this.setRoundScore(this.roundScore + score);
};

/**
 * Resolve score
 *
 * @param {Number} score
 */
BaseAvatar.prototype.resolveScore = function()
{
    this.setScore(this.score + this.roundScore);
    this.roundScore = 0;
};

/**
 * This round score
 *
 * @param {Number} score
 */
BaseAvatar.prototype.setRoundScore = function(score)
{
    this.roundScore = score;
};

/**
 * This score
 *
 * @param {Number} score
 */
BaseAvatar.prototype.setScore = function(score)
{
    this.score = score;
};

/**
 * Set color
 *
 * @param {Number} color
 */
BaseAvatar.prototype.setColor = function(color)
{
    this.color = color;
};

/**
 * Clear
 */
BaseAvatar.prototype.clear = function()
{
    this.bonusStack.clear();

    this.x                   = this.radius;
    this.y                   = this.radius;
    this.angle               = 0;
    this.velocityX           = 0;
    this.velocityY           = 0;
    this.angularVelocity     = 0;
    this.roundScore          = 0;
    this.velocity            = BaseAvatar.prototype.velocity;
    this.alive               = true;
    this.printing            = false;
    this.color               = this.player.color;
    this.radius              = BaseAvatar.prototype.radius;
    this.inverse             = BaseAvatar.prototype.inverse;
    this.invincible          = BaseAvatar.prototype.invincible;
    this.directionInLoop     = BaseAvatar.prototype.directionInLoop;
    this.angularVelocityBase = BaseAvatar.prototype.angularVelocityBase;

    if (this.body) {
        this.body.radius = BaseAvatar.prototype.radius;
    }

    // useless? this.updateVelocities();
};

/**
 * Destroy
 */
BaseAvatar.prototype.destroy = function()
{
    this.clear();
    this.present = false;
    this.alive   = false;
};

/**
 * Serialize
 *
 * @return {Object}
 */
BaseAvatar.prototype.serialize = function()
{
    return {
        id: this.id,
        name: this.name,
        color: this.color,
        score: this.score
    };
};
<|endoftext|>


<commit_before>'use strict';
const express = require('express');
const bodyParser = require('body-parser'); //auto-parses the payload
const requestModule = require('request'); //for creating http requests

const app = express();
const PORT = process.env.PORT || 4390;

const SLACK_TOKEN = process.env.SLACK_TOKEN || 'xxxxxxxxxxx'; //insert your Slack token here, or through Heroku
const BUFFER_TOKEN = process.env.BUFFER_TOKEN || 'xxxxxxxxxxx'; //insert your Buffer token, or through Heroku

const bufferRequest = (tweet, callback) => { //post the message to Buffer
  let data = {
    profile_ids: [],
    text: tweet,
    shorten: true,
    now: false,
    top: false,
  };
  requestModule.post("http://api.buffer.com/1/updates/create", data, (err, res, body) => { //create a Buffer request
    if (err){ //if it's an error
      callback(err); //send the error to the callback
    }
    else{ //log the successful Buffer request
      console.log('Upload to Buffer successful. Server response: ', body);
      callback(null, res, body); //then send the parameters to the callback
    }
  });
};

const slackResponse = (req, res, callback) => { //the message posted to the Slack once the Buffer has been updated
  var userName = req.body.user_name;
  var payload = {
    text: 'Thanks, ' + userName + '! Your message was added to Buffer.'
  };

  if ( userName !== 'slackbot')
  { //send the response back to the Slack channel
    return res.status(200).json(payload);
    callback();
  }
  else {
    return res.status(200).end();
  }
};

app.use(bodyPaser.urlencoded({ extended: true })); //parse all payloads

app.get('/command', (request, response) => {
  bufferRequest(request.body.text, (err, res, body) => {
    if( err ){
      console.error('Upload failed: ', err);
    }
    else if( res.statusCode !== 200 ){
      console.log('Something happened. Status Code: %s | %s', res.StatusCode, body);
    }
    else{
      console.log("Upload successful. Server response: ", body);
      slackResponse(request, response, () => {
        console.log('thank you message posted to Slack.');
      });
    }
  });
});
app.listen(PORT, () => {
  console.log('app is running on port %s', PORT);
});
<commit_msg>fixed typos<commit_after>'use strict';
const express = require('express');
const bodyParser = require('body-parser'); //auto-parses the payload
const requestModule = require('request'); //for creating http requests

const app = express();
const PORT = process.env.PORT || 4390;

const SLACK_TOKEN = process.env.SLACK_TOKEN || 'xxxxxxxxxxx'; //insert your Slack token here, or through Heroku
const BUFFER_TOKEN = process.env.BUFFER_TOKEN || 'xxxxxxxxxxx'; //insert your Buffer token, or through Heroku

const bufferRequest = (tweet, callback) => { //post the message to Buffer
  let data = {
    profile_ids: [],
    text: tweet,
    shorten: true,
    now: false,
    top: false,
  };
  requestModule.post("http://api.buffer.com/1/updates/create", form: data, (err, res, body) => { //create a Buffer request
    if (err){ //if it's an error
      callback(err); //send the error to the callback
    }
    else{ //log the successful Buffer request
      console.log('Upload to Buffer successful. Server response: ', body);
      callback(null, res, body); //then send the parameters to the callback
    }
  });
};

const slackResponse = (req, res, callback) => { //the message posted to the Slack once the Buffer has been updated
  var userName = req.body.user_name;
  var payload = {
    text: 'Thanks, ' + userName + '! Your message was added to Buffer.'
  };

  if ( userName !== 'slackbot')
  { //send the response back to the Slack channel
    return res.status(200).json(payload);
    callback();
  }
  else {
    return res.status(200).end();
  }
};

app.use(bodyParser.urlencoded({ extended: true })); //parse all payloads

app.get('/command', (request, response) => {
  bufferRequest(request.body.text, (err, res, body) => {
    if( err ){
      console.error('Upload failed: ', err);
    }
    else if( res.statusCode !== 200 ){
      console.log('Something happened. Status Code: %s | %s', res.StatusCode, body);
    }
    else{
      console.log("Upload successful. Server response: ", body);
      slackResponse(request, response, () => {
        console.log('thank you message posted to Slack.');
      });
    }
  });
});
app.listen(PORT, () => {
  console.log('app is running on port %s', PORT);
});
<|endoftext|>


<commit_before>/**
 * @file - handle information from vip. @see openagency.addi.dk
 * Internally (DBC) we use vipcore : http://vipcore.iscrum-vip-prod.svc.cloud.dbc.dk:8080/1.0/api
 * For documentation @see https://dbcjira.atlassian.net/wiki/spaces/IS/pages/884998162/VipCore+API+beskrivelse
 *
 * Bssically this transformer gets ALL pickupagencies and orderparameters from vipcore. When a single
 * library/branch is requested it returns a filtered result of the pickupagencies.
 *
 */

import * as IsilUtils from './utils/isil.utils';

const timeout = 60 * 60 * 1000;
let cache;
let timestamp;

/**
 * Insert orderparameters in the list of pickupagencies.
 *
 * @param results
 *   all the pickupagencies retrieved from vipcore
 * @param agencyKeys
 *    agencyIds of all pickupagencies
 * @param orderParameters
 *    order parameters (eg. userid, username ...) to insert
 * @returns {*}
 */
function orderParameterPromiseHandler(results, agencyKeys, orderParameters) {
  const agencyOrderParameters = {};
  for (let i = 0; i < agencyKeys.length; ++i) {
    agencyOrderParameters[agencyKeys[i]] = orderParameters[i];
  }
  for (let i = 0; i < results.length; ++i) {
    results[i].orderParameters = agencyOrderParameters[results[i].agencyId];
  }
  cache = results;
  timestamp = Date.now();
  return results;
}

/**
 * Do a call to vipcore service endpoint
 * e.g http://vipcore.iscrum-vip-prod.svc.cloud.dbc.dk/1.0/api/service/710100/userOrderParameters/
 * Parse and return orderparamters from service
 *
 * @param context
 * @param agencyId
 * @returns {*}
 */
function getOrderParameters(context, agencyId) {
  const service = context.get('services.openagency');
  const path = `/service/${agencyId}/userOrderParameters/`;
  const api = service + path;

  return context.call(api, {}).then(response => {
    const result = [];

    // @TODO datacheck - service may return an error e.g service_unavailable

    let parameters = response.data.userOrderParameters.userParameter
      ? response.data.userOrderParameters.userParameter
      : null;

    // map selected parameters
    const parameterMap = {
      userName: 'name',
      userAddress: 'address',
      userMail: 'email',
      userTelephone: 'phone'
    };

    if (parameters) {
      for (let i = 0; i < parameters.length; ++i) {
        if (parameters[i].parameterRequired === true) {
          let parameter = parameters[i].userParameterType;
          parameter = parameterMap[parameter] || parameter;
          result.push(parameter);
        }
      }
    }

    return Promise.resolve(result);
  });
}

/**
 * For backward compatibility - use the danish value for some of the fields.
 * Use "1" for true & "0" for false
 * @param key
 * @param library
 * @returns {string|*}
 */
function libraryFilter(key, library) {
  // which fields to change - for all of them - they are in an array - get the danish value
  const keysToChange = [
    'branchName',
    'branchShortName',
    'openingHours',
    'illOrderReceiptText',
    'temporarilyClosedReason'
  ];

  if (keysToChange.includes(key)) {
    return (
      library[key]
        // filter on language
        .sort(field => field.language === 'dan')
        // return the value
        .map(field => {
          return field.value;
        })
    );
  }
  if (library[key] === true) {
    return '1';
  }
  if (library[key] === false) {
    return '0';
  }

  return library[key];
}

/**
 * Parse response from findlibrary/all endpoint. Filter out ncip info.
 * Bind getOrderParameters to add order parameters to result.
 * @param context
 * @param response
 * @returns {Promise<unknown[]>}
 */
function openAgencyPromiseHandler(context, response) {
  const results = response.data.pickupAgency.map(library => {
    const result = {};

    // filter out ncip info
    Object.keys(library)
      .filter(
        libraryKey =>
          libraryKey !== '@' &&
          libraryKey.indexOf('ncip') !== 0 &&
          library[libraryKey] !== null
      )
      .forEach(key => (result[key] = libraryFilter(key, library)));

    // check if mainagencyid is set - it might not be the case for single branch
    // libraries
    if (!result.agencyId) {
      result.agencyId = result.branchId;
    }

    return result;
  });

  // collect agencyids as keys for getOrderParameters service call
  const agencies = {};
  for (let i = 0; i < results.length; ++i) {
    agencies[results[i].agencyId] = true;
  }
  const agencyKeys = Object.keys(agencies);
  // iterate agencyIds - get orderparameters
  const agencyPromises = agencyKeys.map(getOrderParameters.bind(null, context));
  return Promise.all(agencyPromises).then(
    orderParameterPromiseHandler.bind(null, results, agencyKeys)
  );
}

/**
 * Do a call to findlibrary/all endpoint.
 * @param context
 * @returns {*}
 */
function getLibraries(context) {
  const service = context.get('services.openagency');
  const path = '/findlibrary/all';
  const api = service + path;

  return context
    .call(api, {})
    .then(response => openAgencyPromiseHandler(context, response));
}

/**
 * Handle the request.
 * @param params
 *   May hold one or more branch/agency - ids to filter on
 * @param context
 *   @see context.json
 * @param libraries
 *   a list of pickupagencies - from service or cache
 * @returns {{data, statusCode: number}}
 */
function getLibrariesTransformPromiseHandler(params, context, libraries) {
  if (Date.now() - timestamp > timeout) {
    setTimeout(() => getLibraries(context), 1000);
    timestamp = Date.now();
  }

  if (Array.isArray(params.agencyIds)) {
    const agencies = {};
    for (let i = 0; i < params.agencyIds.length; ++i) {
      agencies[IsilUtils.getIdFromIsil(params.agencyIds[i])] = true;
    }

    libraries = libraries.filter(o => agencies[o.agencyId]);
  }

  if (Array.isArray(params.branchIds)) {
    const branches = {};
    for (let i = 0; i < params.branchIds.length; ++i) {
      branches[IsilUtils.getIdFromIsil(params.branchIds[i])] = true;
    }

    libraries = libraries.filter(o => branches[o.branchId]);
  }

  return {statusCode: 200, data: libraries};
}

/**
 * Entrypoint for this transformer.
 * @param params
 * @param context
 * @returns {Promise<any>}
 */
export default function getLibrariesTransform(params, context) {
  let promise;

  if (cache) {
    promise = Promise.resolve(cache);
  } else {
    promise = getLibraries(context);
  }

  return promise.then(
    getLibrariesTransformPromiseHandler.bind(null, params, context)
  );
}
<commit_msg>sort NOT filter<commit_after>/**
 * @file - handle information from vip. @see openagency.addi.dk
 * Internally (DBC) we use vipcore : http://vipcore.iscrum-vip-prod.svc.cloud.dbc.dk:8080/1.0/api
 * For documentation @see https://dbcjira.atlassian.net/wiki/spaces/IS/pages/884998162/VipCore+API+beskrivelse
 *
 * Bssically this transformer gets ALL pickupagencies and orderparameters from vipcore. When a single
 * library/branch is requested it returns a filtered result of the pickupagencies.
 *
 */

import * as IsilUtils from './utils/isil.utils';

const timeout = 60 * 60 * 1000;
let cache;
let timestamp;

/**
 * Insert orderparameters in the list of pickupagencies.
 *
 * @param results
 *   all the pickupagencies retrieved from vipcore
 * @param agencyKeys
 *    agencyIds of all pickupagencies
 * @param orderParameters
 *    order parameters (eg. userid, username ...) to insert
 * @returns {*}
 */
function orderParameterPromiseHandler(results, agencyKeys, orderParameters) {
  const agencyOrderParameters = {};
  for (let i = 0; i < agencyKeys.length; ++i) {
    agencyOrderParameters[agencyKeys[i]] = orderParameters[i];
  }
  for (let i = 0; i < results.length; ++i) {
    results[i].orderParameters = agencyOrderParameters[results[i].agencyId];
  }
  cache = results;
  timestamp = Date.now();
  return results;
}

/**
 * Do a call to vipcore service endpoint
 * e.g http://vipcore.iscrum-vip-prod.svc.cloud.dbc.dk/1.0/api/service/710100/userOrderParameters/
 * Parse and return orderparamters from service
 *
 * @param context
 * @param agencyId
 * @returns {*}
 */
function getOrderParameters(context, agencyId) {
  const service = context.get('services.openagency');
  const path = `/service/${agencyId}/userOrderParameters/`;
  const api = service + path;

  return context.call(api, {}).then(response => {
    const result = [];

    // @TODO datacheck - service may return an error e.g service_unavailable

    let parameters = response.data.userOrderParameters.userParameter
      ? response.data.userOrderParameters.userParameter
      : null;

    // map selected parameters
    const parameterMap = {
      userName: 'name',
      userAddress: 'address',
      userMail: 'email',
      userTelephone: 'phone'
    };

    if (parameters) {
      for (let i = 0; i < parameters.length; ++i) {
        if (parameters[i].parameterRequired === true) {
          let parameter = parameters[i].userParameterType;
          parameter = parameterMap[parameter] || parameter;
          result.push(parameter);
        }
      }
    }

    return Promise.resolve(result);
  });
}

/**
 * For backward compatibility - use the danish value for some of the fields.
 * Use "1" for true & "0" for false
 * @param key
 * @param library
 * @returns {string|*}
 */
function libraryFilter(key, library) {
  // which fields to change - for all of them - they are in an array - get the danish value
  const keysToChange = [
    'branchName',
    'branchShortName',
    'openingHours',
    'illOrderReceiptText',
    'temporarilyClosedReason'
  ];

  if (keysToChange.includes(key)) {
    return (
      library[key]
        // sort on language
        .sort(field => field.language === 'dan')
        // return the value(s)
        .map(field => {
          return field.value;
        })
    );
  }
  if (library[key] === true) {
    return '1';
  }
  if (library[key] === false) {
    return '0';
  }

  return library[key];
}

/**
 * Parse response from findlibrary/all endpoint. Filter out ncip info.
 * Bind getOrderParameters to add order parameters to result.
 * @param context
 * @param response
 * @returns {Promise<unknown[]>}
 */
function openAgencyPromiseHandler(context, response) {
  const results = response.data.pickupAgency.map(library => {
    const result = {};

    // filter out ncip info
    Object.keys(library)
      .filter(
        libraryKey =>
          libraryKey !== '@' &&
          libraryKey.indexOf('ncip') !== 0 &&
          library[libraryKey] !== null
      )
      .forEach(key => (result[key] = libraryFilter(key, library)));

    // check if mainagencyid is set - it might not be the case for single branch
    // libraries
    if (!result.agencyId) {
      result.agencyId = result.branchId;
    }

    return result;
  });

  // collect agencyids as keys for getOrderParameters service call
  const agencies = {};
  for (let i = 0; i < results.length; ++i) {
    agencies[results[i].agencyId] = true;
  }
  const agencyKeys = Object.keys(agencies);
  // iterate agencyIds - get orderparameters
  const agencyPromises = agencyKeys.map(getOrderParameters.bind(null, context));
  return Promise.all(agencyPromises).then(
    orderParameterPromiseHandler.bind(null, results, agencyKeys)
  );
}

/**
 * Do a call to findlibrary/all endpoint.
 * @param context
 * @returns {*}
 */
function getLibraries(context) {
  const service = context.get('services.openagency');
  const path = '/findlibrary/all';
  const api = service + path;

  return context
    .call(api, {})
    .then(response => openAgencyPromiseHandler(context, response));
}

/**
 * Handle the request.
 * @param params
 *   May hold one or more branch/agency - ids to filter on
 * @param context
 *   @see context.json
 * @param libraries
 *   a list of pickupagencies - from service or cache
 * @returns {{data, statusCode: number}}
 */
function getLibrariesTransformPromiseHandler(params, context, libraries) {
  if (Date.now() - timestamp > timeout) {
    setTimeout(() => getLibraries(context), 1000);
    timestamp = Date.now();
  }

  if (Array.isArray(params.agencyIds)) {
    const agencies = {};
    for (let i = 0; i < params.agencyIds.length; ++i) {
      agencies[IsilUtils.getIdFromIsil(params.agencyIds[i])] = true;
    }

    libraries = libraries.filter(o => agencies[o.agencyId]);
  }

  if (Array.isArray(params.branchIds)) {
    const branches = {};
    for (let i = 0; i < params.branchIds.length; ++i) {
      branches[IsilUtils.getIdFromIsil(params.branchIds[i])] = true;
    }

    libraries = libraries.filter(o => branches[o.branchId]);
  }

  return { statusCode: 200, data: libraries };
}

/**
 * Entrypoint for this transformer.
 * @param params
 * @param context
 * @returns {Promise<any>}
 */
export default function getLibrariesTransform(params, context) {
  let promise;

  if (cache) {
    promise = Promise.resolve(cache);
  } else {
    promise = getLibraries(context);
  }

  return promise.then(
    getLibrariesTransformPromiseHandler.bind(null, params, context)
  );
}
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import PropTypes from 'prop-types';
import Relay from 'react-relay/classic';
import { FormattedMessage, injectIntl } from 'react-intl';
import ListItem from '@material-ui/core/ListItem';
import ListItemIcon from '@material-ui/core/ListItemIcon';
import ListItemText from '@material-ui/core/ListItemText';
import ListItemSecondaryAction from '@material-ui/core/ListItemSecondaryAction';
import Button from '@material-ui/core/Button';
import FASlack from 'react-icons/lib/fa/slack';
import FAFacebook from 'react-icons/lib/fa/facebook-official';
import FATwitter from 'react-icons/lib/fa/twitter';
import ConfirmDialog from '../layout/ConfirmDialog';
import UserDisconnectLoginAccountMutation from '../../relay/mutations/UserDisconnectLoginAccountMutation';
import { login } from '../../redux/actions';
import {
  FlexRow,
  slackGreen,
  twitterBlue,
  facebookBlue,
} from '../../styles/js/shared';

class UserConnectedAccount extends Component {
  static renderLabel(userAction) {
    switch (userAction) {
    case 'connect':
      return <FormattedMessage id="UserConnectedAccount.connectButton" defaultMessage="Connect" />;
    case 'disconnect':
      return <FormattedMessage id="UserConnectedAccount.disconnectButton" defaultMessage="Disconnect" />;
    default:
      return null;
    }
  }

  constructor(props) {
    super(props);
    this.state = { dialogOpen: false };
  }

  handleOpenDialog() {
    this.setState({ dialogOpen: true });
  }

  handleCloseDialog() {
    this.setState({ dialogOpen: false });
  }

  handleUserClick(userAction, uid = '') {
    if (userAction === 'connect') {
      login(this.props.provider.key, this.props.loginCallback);
    } else if (userAction === 'disconnect') {
      this.handleRequestDisconnectAccount(uid);
      this.setState({ dialogOpen: false });
    }
  }

  handleRequestDisconnectAccount(uid) {
    const onFailure = () => {
    };
    const onSuccess = () => {
    };
    const { provider } = this.props;
    Relay.Store.commitUpdate(
      new UserDisconnectLoginAccountMutation({
        provider,
        uid,
      }),
      { onSuccess, onFailure },
    );
  }

  socialIcon() {
    switch (this.props.provider.key) {
    case 'twitter':
      return <FATwitter style={{ color: twitterBlue }} className="logo" />;
    case 'slack':
      return <FASlack style={{ color: slackGreen }} className="logo" />;
    case 'facebook':
      return <FAFacebook style={{ color: facebookBlue }} className="logo" />;
    default:
      return null;
    }
  }

  render() {
    const { provider } = this.props;
    const buttonStyle = {
      color: 'rgb(46, 119, 252)',
    };
    const confirmDialog = {
      title: <FormattedMessage
        id="UserConnectedAccount.disconnectAccountTitle"
        defaultMessage="Disconnect account"
      />,
      blurb: <FormattedMessage
        id="UserConnectedAccount.disconnectAccountConfirmationText"
        defaultMessage="Are you sure? This will disconnect login account."
      />,
    };

    const listIcon = this.socialIcon();

    return (

        { provider.values.map((socialAccount, index) => {
          const userAction = (socialAccount.connected === true) ? 'disconnect' : 'connect';
          let disableDisconnect = false;
          if (userAction === 'disconnect' && socialAccount.allow_disconnect === false) {
            disableDisconnect = true;
          }
          return (
            <ListItem className="user-connect__list-item" key={`account-connect-disconnect-raw-${index.toString()}`}>
              <ListItemIcon className="user-connect__list-icon">
                {listIcon}
              </ListItemIcon>
              <ListItemText style={{ minWidth: '500px', padding: '0px' }} primary={socialAccount.info} />
              <ListItemSecondaryAction>
                <Button
                  style={buttonStyle}
                  onClick={userAction === 'connect' ? this.handleUserClick.bind(this, userAction) : this.handleOpenDialog.bind(this)}
                  className="team-connect-account-button--disconnect"
                  disabled={disableDisconnect}
                >
                  {UserConnectedAccount.renderLabel(userAction)}
                </Button>
                <ConfirmDialog
                  open={this.state.dialogOpen}
                  title={confirmDialog.title}
                  blurb={confirmDialog.blurb}
                  handleClose={this.handleCloseDialog.bind(this)}
                  handleConfirm={this.handleUserClick.bind(this, userAction, socialAccount.uid)}
                />
              </ListItemSecondaryAction>
            </ListItem>
          );
        })}
        { provider.add_another === true ?
          <FlexRow style={{ padding: '0px 10px' }} >
            <Button
              style={buttonStyle}
              onClick={this.handleUserClick.bind(this, 'connect')}
              className="team-connect-account-button--disconnect"
            >
              {<FormattedMessage id="UserConnectedAccount.addAnother" defaultMessage="Add another account" />}
            </Button>
          </FlexRow>
          : null}

    );
  }
}
UserConnectedAccount.contextTypes = {
  store: PropTypes.object,
};
export default injectIntl(UserConnectedAccount);
<commit_msg>Ticket #6601 - style diconnected button<commit_after>import React, { Component } from 'react';
import PropTypes from 'prop-types';
import Relay from 'react-relay/classic';
import { FormattedMessage, injectIntl } from 'react-intl';
import ListItem from '@material-ui/core/ListItem';
import ListItemIcon from '@material-ui/core/ListItemIcon';
import ListItemText from '@material-ui/core/ListItemText';
import ListItemSecondaryAction from '@material-ui/core/ListItemSecondaryAction';
import Button from '@material-ui/core/Button';
import FASlack from 'react-icons/lib/fa/slack';
import FAFacebook from 'react-icons/lib/fa/facebook-official';
import FATwitter from 'react-icons/lib/fa/twitter';
import ConfirmDialog from '../layout/ConfirmDialog';
import UserDisconnectLoginAccountMutation from '../../relay/mutations/UserDisconnectLoginAccountMutation';
import { login } from '../../redux/actions';
import {
  FlexRow,
  slackGreen,
  twitterBlue,
  facebookBlue,
} from '../../styles/js/shared';

class UserConnectedAccount extends Component {
  static renderLabel(userAction) {
    switch (userAction) {
    case 'connect':
      return <FormattedMessage id="UserConnectedAccount.connectButton" defaultMessage="Connect" />;
    case 'disconnect':
      return <FormattedMessage id="UserConnectedAccount.disconnectButton" defaultMessage="Disconnect" />;
    default:
      return null;
    }
  }

  constructor(props) {
    super(props);
    this.state = { dialogOpen: false };
  }

  handleOpenDialog() {
    this.setState({ dialogOpen: true });
  }

  handleCloseDialog() {
    this.setState({ dialogOpen: false });
  }

  handleUserClick(userAction, uid = '') {
    if (userAction === 'connect') {
      login(this.props.provider.key, this.props.loginCallback);
    } else if (userAction === 'disconnect') {
      this.handleRequestDisconnectAccount(uid);
      this.setState({ dialogOpen: false });
    }
  }

  handleRequestDisconnectAccount(uid) {
    const onFailure = () => {
    };
    const onSuccess = () => {
    };
    const { provider } = this.props;
    Relay.Store.commitUpdate(
      new UserDisconnectLoginAccountMutation({
        provider,
        uid,
      }),
      { onSuccess, onFailure },
    );
  }

  socialIcon() {
    switch (this.props.provider.key) {
    case 'twitter':
      return <FATwitter style={{ color: twitterBlue }} className="logo" />;
    case 'slack':
      return <FASlack style={{ color: slackGreen }} className="logo" />;
    case 'facebook':
      return <FAFacebook style={{ color: facebookBlue }} className="logo" />;
    default:
      return null;
    }
  }

  render() {
    const { provider } = this.props;
    const buttonStyle = {
      color: 'rgb(46, 119, 252)',
    };
    const confirmDialog = {
      title: <FormattedMessage
        id="UserConnectedAccount.disconnectAccountTitle"
        defaultMessage="Disconnect account"
      />,
      blurb: <FormattedMessage
        id="UserConnectedAccount.disconnectAccountConfirmationText"
        defaultMessage="Are you sure? This will disconnect login account."
      />,
    };

    const listIcon = this.socialIcon();

    return (

        { provider.values.map((socialAccount, index) => {
          const userAction = (socialAccount.connected === true) ? 'disconnect' : 'connect';
          let disableDisconnect = false;
          if (userAction === 'disconnect' && socialAccount.allow_disconnect === false) {
            disableDisconnect = true;
          }
          return (
            <ListItem className="user-connect__list-item" key={`account-connect-disconnect-raw-${index.toString()}`}>
              <ListItemIcon className="user-connect__list-icon">
                {listIcon}
              </ListItemIcon>
              <ListItemText style={{ minWidth: '500px', padding: '0px' }} primary={socialAccount.info} />
              <ListItemSecondaryAction>
                <Button
                  style={disableDisconnect === false ? buttonStyle : {}}
                  onClick={userAction === 'connect' ? this.handleUserClick.bind(this, userAction) : this.handleOpenDialog.bind(this)}
                  className="team-connect-account-button--disconnect"
                  disabled={disableDisconnect}
                >
                  {UserConnectedAccount.renderLabel(userAction)}
                </Button>
                <ConfirmDialog
                  open={this.state.dialogOpen}
                  title={confirmDialog.title}
                  blurb={confirmDialog.blurb}
                  handleClose={this.handleCloseDialog.bind(this)}
                  handleConfirm={this.handleUserClick.bind(this, userAction, socialAccount.uid)}
                />
              </ListItemSecondaryAction>
            </ListItem>
          );
        })}
        { provider.add_another === true ?
          <FlexRow style={{ padding: '0px 10px' }} >
            <Button
              style={buttonStyle}
              onClick={this.handleUserClick.bind(this, 'connect')}
              className="team-connect-account-button--disconnect"
            >
              {<FormattedMessage id="UserConnectedAccount.addAnother" defaultMessage="Add another account" />}
            </Button>
          </FlexRow>
          : null}

    );
  }
}
UserConnectedAccount.contextTypes = {
  store: PropTypes.object,
};
export default injectIntl(UserConnectedAccount);
<|endoftext|>


<commit_before>'use strict';

const config = require('../config');

let knex = require('knex')(config.knex);
let twit = new (require('twit'))(config.twitter);

let request = require('request');
let cheerio = require('cheerio');

const platforms = [ '01', '03', '04', '05' ];
const ratings = [ 'rating_all', 'rating_12', 'rating_15', 'rating_18', 'icon_reject', 'icon_cancel1', 'icon_cancel2' ];
const table_name = 'gcrb_bot';

class App {
	constructor() {
		let self = this;

		knex.schema.hasTable(table_name).then((exists) => {
			if(exists) {
				return Promise.resolve();
			}
			else {
				return knex.schema.createTableIfNotExists(table_name, (table) => {
					table.string('id').primary().notNullable();
					table.string('date').notNullable();
					table.string('title').notNullable();
					table.integer('platform').notNullable();
					table.string('applicant').notNullable();
					table.integer('rating').notNullable();
					table.string('code');
					table.integer('tweet', 1).notNullable();
					table.timestamp('created_at').defaultTo(knex.fn.now());
				});
			}
		}).then(() => {
			if(process.env.NODE_ENV !== "test") {
				Promise.resolve(0).then(function loop(i) {
					console.log(i);

					return self.start().then((data) => {
						let promises = platforms.map((platform) => {
							return self.parse(platform, data.startdate, data.enddate, data.page).then(function loop(data) {
								if(data.items.length > 0) {
									return self.insert(data.items).then(() => {
										return self.parse(platform, data.startdate, data.enddate, data.page + 1).then(loop).catch((e) => {
											console.log(e);
										});
									}).catch((e) => {
										console.log(e);
									});
								}
								else {
									return Promise.resolve();
								}
							});
						});
						return Promise.all(promises).then(() => {
							return self.tweet();
						}).then(() => {
							return new Promise((resolve, reject) => {
								setTimeout(() => {
									resolve(i + 1);
								}, 5 * 60 * 1000);
							});
						}).then(loop).catch((e) => {
							console.log(e);
						});
					}).catch((e) => {
						console.log(e);
					});
				});
			}
		}).catch((e) => {
			console.log(e);
		});
	}

	start() {
		let self = this;

		return new Promise((resolve, reject) => {
			let date = new Date();
			let enddate = date.toISOString().substr(0, 10);
			date.setDate(date.getDate() - 3);
			let startdate = date.toISOString().substr(0, 10);

			resolve({
				startdate: startdate,
				enddate: enddate,
				page: 0
			});
		});
	}

	parse(platform, startdate, enddate, page) {
		let self = this;

		let data = {
			items: [],
			startdate: startdate,
			enddate: enddate,
			page: page
		};

		const url = `http://www.grac.or.kr/Statistics/GameStatistics.aspx?type=search&enddate=${enddate}&startdate=${startdate}&platform=${platform}&pageindex=${page}`;

		return new Promise((resolve, reject) => {
			request(url, (err, res, body) => {
				if(!err && res.statusCode === 200) {
					let $ = cheerio.load(body);

					let items = [];
					$('table.statistics tr').each((i, e) => {
						if(i > 0) {
							let item = {};

							$(e).find('td').each((i, e) => {
								let str = $(e).text().trim();

								item.platform = platforms.indexOf(platform);
								item.tweet = 0;

								switch(i) {
								case 0:
									item.title = str;

									item.id = $(e).find('a').attr('href').split('\'')[1];

									break;
								case 1:
									item.applicant = str;

									break;
								case 2:
									item.date = str.replace(/,/g, '-');

									break;
								case 3:
									let rating = $(e).find('img').attr('src').split('/').pop().split('.').shift();

									item.rating = ratings.indexOf(rating);

									break;
								case 4:
									item.code = str;

									break;
								}
							});

							items.push(item);
						}
					});

					data.items = items;
					resolve(data);
				}
				else {
					resolve(data);
				}
			});
		});
	}

	insert(items) {
		let self = this;

		return new Promise((resolve, reject) => {
			let promises = items.map((item) => {
				return knex(table_name).where({
					id: item.id
				}).then((rows) => {
					if(rows.length === 0) {
						return knex(table_name).insert(item);
					}
					else {
						return Promise.resolve();
					}
				}).catch((e) => {
					console.log(e);
				});
			});
			Promise.all(promises).then(() => {
console.log(1);
				resolve();
			}).catch((e) => {
				console.log(e);
			});
		});
	}

	tweet() {
		let self = this;

		return new Promise((resolve, reject) => {
			knex(table_name).where({
				tweet: 0
			}).then((rows) => {
				let promises = rows.map((row) => {
					return new Promise((resolve, reject) => {
						let date = row.date;
						let title = row.title;
							let platform;
						switch(row.platform) {
						case -1: platform = ''; break;
						case 0: platform = 'PC/온라인 게임'; break;
						case 1: platform = '비디오 게임'; break;
						case 2: platform = '모바일 게임'; break;
						case 3: platform = '아케이드 게임'; break;
						}
						let rating;
						switch(row.rating) {
						case -1: rating = ''; break;
						case 0: rating = '전체이용가'; break;
						case 1: rating = '12세 이용가'; break;
						case 2: rating = '15세 이용가'; break;
						case 3: rating = '청소년 이용불가'; break;
						case 4: rating = '등급거부'; break;
						case 5: rating = '등급취소예정'; break;
						case 6: rating = '등급취소'; break;
						}
						let applicant = row.applicant;

						let status = `[${date}]\n[${platform}]\n[${title}]\n[${applicant}]\n[${rating}]\n`;

						let excess = status.length - (140 - 23);
						if(excess > 0) {
							var tokens = status.match(/\[.*\]/g);
							tokens[2] = '[' + title.substr(0, title.length - excess - 1) + '…]';
							status = tokens.join('\n');
							status += '\n';
						}
						status += `http://www.grac.or.kr/Statistics/Popup/Pop_ReasonInfo.aspx?${row.id}`;

						twit.post('statuses/update', {
							status: status
						}, (err, res) => {
							if(err) {
								throw new Error(err);
							}

							knex(table_name).where({
								id: row.id
							}).update({
								tweet: 1
							}).then(() => {
								resolve();
							}).catch((e) => {
								console.log(e);
							});
						});
					});
				});
				Promise.all(promises).then(() => {
					resolve();
				}).catch((e) => {
					console.log(e);
				});
			});
		});
	}
}

if(process.env.NODE_ENV !== "test") {
	let app = new App();
}

module.exports = App;

<commit_msg>fix build<commit_after>'use strict';

const config = require('../config');

let knex = require('knex')(config.knex);
let twit;
if(process.env.NODE_ENV !== 'test') {
	twit = new (require('twit'))(config.twitter);
}

let request = require('request');
let cheerio = require('cheerio');

const platforms = [ '01', '03', '04', '05' ];
const ratings = [ 'rating_all', 'rating_12', 'rating_15', 'rating_18', 'icon_reject', 'icon_cancel1', 'icon_cancel2' ];
const table_name = 'gcrb_bot';

class App {
	constructor() {
		let self = this;

		knex.schema.hasTable(table_name).then((exists) => {
			if(exists) {
				return Promise.resolve();
			}
			else {
				return knex.schema.createTableIfNotExists(table_name, (table) => {
					table.string('id').primary().notNullable();
					table.string('date').notNullable();
					table.string('title').notNullable();
					table.integer('platform').notNullable();
					table.string('applicant').notNullable();
					table.integer('rating').notNullable();
					table.string('code');
					table.integer('tweet', 1).notNullable();
					table.timestamp('created_at').defaultTo(knex.fn.now());
				});
			}
		}).then(() => {
			if(process.env.NODE_ENV !== "test") {
				Promise.resolve(0).then(function loop(i) {
					console.log(i);

					return self.start().then((data) => {
						let promises = platforms.map((platform) => {
							return self.parse(platform, data.startdate, data.enddate, data.page).then(function loop(data) {
								if(data.items.length > 0) {
									return self.insert(data.items).then(() => {
										return self.parse(platform, data.startdate, data.enddate, data.page + 1).then(loop).catch((e) => {
											console.log(e);
										});
									}).catch((e) => {
										console.log(e);
									});
								}
								else {
									return Promise.resolve();
								}
							});
						});
						return Promise.all(promises).then(() => {
							return self.tweet();
						}).then(() => {
							return new Promise((resolve, reject) => {
								setTimeout(() => {
									resolve(i + 1);
								}, 5 * 60 * 1000);
							});
						}).then(loop).catch((e) => {
							console.log(e);
						});
					}).catch((e) => {
						console.log(e);
					});
				});
			}
		}).catch((e) => {
			console.log(e);
		});
	}

	start() {
		let self = this;

		return new Promise((resolve, reject) => {
			let date = new Date();
			let enddate = date.toISOString().substr(0, 10);
			date.setDate(date.getDate() - 3);
			let startdate = date.toISOString().substr(0, 10);

			resolve({
				startdate: startdate,
				enddate: enddate,
				page: 0
			});
		});
	}

	parse(platform, startdate, enddate, page) {
		let self = this;

		let data = {
			items: [],
			startdate: startdate,
			enddate: enddate,
			page: page
		};

		const url = `http://www.grac.or.kr/Statistics/GameStatistics.aspx?type=search&enddate=${enddate}&startdate=${startdate}&platform=${platform}&pageindex=${page}`;

		return new Promise((resolve, reject) => {
			request(url, (err, res, body) => {
				if(!err && res.statusCode === 200) {
					let $ = cheerio.load(body);

					let items = [];
					$('table.statistics tr').each((i, e) => {
						if(i > 0) {
							let item = {};

							$(e).find('td').each((i, e) => {
								let str = $(e).text().trim();

								item.platform = platforms.indexOf(platform);
								item.tweet = 0;

								switch(i) {
								case 0:
									item.title = str;

									item.id = $(e).find('a').attr('href').split('\'')[1];

									break;
								case 1:
									item.applicant = str;

									break;
								case 2:
									item.date = str.replace(/,/g, '-');

									break;
								case 3:
									let rating = $(e).find('img').attr('src').split('/').pop().split('.').shift();

									item.rating = ratings.indexOf(rating);

									break;
								case 4:
									item.code = str;

									break;
								}
							});

							items.push(item);
						}
					});

					data.items = items;
					resolve(data);
				}
				else {
					resolve(data);
				}
			});
		});
	}

	insert(items) {
		let self = this;

		return new Promise((resolve, reject) => {
			let promises = items.map((item) => {
				return knex(table_name).where({
					id: item.id
				}).then((rows) => {
					if(rows.length === 0) {
						return knex(table_name).insert(item);
					}
					else {
						return Promise.resolve();
					}
				}).catch((e) => {
					console.log(e);
				});
			});
			Promise.all(promises).then(() => {
console.log(1);
				resolve();
			}).catch((e) => {
				console.log(e);
			});
		});
	}

	tweet() {
		let self = this;

		return new Promise((resolve, reject) => {
			knex(table_name).where({
				tweet: 0
			}).then((rows) => {
				let promises = rows.map((row) => {
					return new Promise((resolve, reject) => {
						let date = row.date;
						let title = row.title;
							let platform;
						switch(row.platform) {
						case -1: platform = ''; break;
						case 0: platform = 'PC/온라인 게임'; break;
						case 1: platform = '비디오 게임'; break;
						case 2: platform = '모바일 게임'; break;
						case 3: platform = '아케이드 게임'; break;
						}
						let rating;
						switch(row.rating) {
						case -1: rating = ''; break;
						case 0: rating = '전체이용가'; break;
						case 1: rating = '12세 이용가'; break;
						case 2: rating = '15세 이용가'; break;
						case 3: rating = '청소년 이용불가'; break;
						case 4: rating = '등급거부'; break;
						case 5: rating = '등급취소예정'; break;
						case 6: rating = '등급취소'; break;
						}
						let applicant = row.applicant;

						let status = `[${date}]\n[${platform}]\n[${title}]\n[${applicant}]\n[${rating}]\n`;

						let excess = status.length - (140 - 23);
						if(excess > 0) {
							var tokens = status.match(/\[.*\]/g);
							tokens[2] = '[' + title.substr(0, title.length - excess - 1) + '…]';
							status = tokens.join('\n');
							status += '\n';
						}
						status += `http://www.grac.or.kr/Statistics/Popup/Pop_ReasonInfo.aspx?${row.id}`;

						twit.post('statuses/update', {
							status: status
						}, (err, res) => {
							if(err) {
								throw new Error(err);
							}

							knex(table_name).where({
								id: row.id
							}).update({
								tweet: 1
							}).then(() => {
								resolve();
							}).catch((e) => {
								console.log(e);
							});
						});
					});
				});
				Promise.all(promises).then(() => {
					resolve();
				}).catch((e) => {
					console.log(e);
				});
			});
		});
	}
}

if(process.env.NODE_ENV !== "test") {
	let app = new App();
}

module.exports = App;

<|endoftext|>


<commit_before>/**
 * Base Avatar
 *
 * @param {Player} player
 */
function BaseAvatar(player)
{
    EventEmitter.call(this);

    this.id              = player.id;
    this.name            = player.name;
    this.color           = player.color;
    this.player          = player;
    this.x               = 0;
    this.y               = 0;
    this.trail           = new Trail(this);
    this.bonusStack      = new BonusStack(this);
    this.angle           = 0;
    this.velocityX       = 0;
    this.velocityY       = 0;
    this.angularVelocity = 0;
    this.alive           = true;
    this.printing        = false;
    this.score           = 0;
    this.roundScore      = 0;
    this.ready           = false;
    this.present         = true;
	BaseAvatar.prototype.velocity = 16;

    this.updateVelocities();
}

BaseAvatar.prototype = Object.create(EventEmitter.prototype);
BaseAvatar.prototype.constructor = BaseAvatar;

if( BaseAvatar.prototype.speed === true){
	BaseAvatar.prototype.velocity = 56;
	this.updateVelocities();
	console.log('speed mode');
}
if(	BaseAvatar.prototype.speed === false){
	BaseAvatar.prototype.velocity = 16;
	this.updateVelocities();
	console.log('normal mode');
}
/**
 * Movement velocity
 *
 * @type {Number}
 */

var doneTheStuff;

	function boosta(){
		return;
	}

/**
 * Turn velocity
 *
 * @type {Float}
 */
BaseAvatar.prototype.angularVelocityBase = 2.8/1000;

/**
 * Radius
 *
 * @type {Number}
 */
BaseAvatar.prototype.radius = 0.6;

/**
 * Number of trail points that don't kill the player
 *
 * @type {Number}
 */
BaseAvatar.prototype.trailLatency = 3;

/**
 * Inverted controls
 *
 * @type {Boolean}
 */
BaseAvatar.prototype.inverse = false;

/**
 * Invincible
 *
 * @type {Boolean}
 */
BaseAvatar.prototype.invincible = false;

/**
 * Type of tunrn: round or straight
 *
 * @type {Boolean}
 */
BaseAvatar.prototype.directionInLoop = true;

/**
 * Equal
 *
 * @param {Avatar} avatar
 *
 * @return {Boolean}
 */

function updater()
{
    var velocity = this.velocity/1000;

    this.velocityX = Math.cos(this.angle) * velocity;
    this.velocityY = Math.sin(this.angle) * velocity;

    this.updateBaseAngularVelocity();
};
 function sp1(){
	 BaseAvatar.prototype.speed = true;
	 boosta();
	 //BaseAvatar.prototype.setVelocity.call(this, 'velocity', 0.75 * 16);
	 //BaseAvatar.prototype.setVelocity.call(velocity);

		this.velocity = 28;
		updater();
	 if(!doneTheStuff){

	 console.log(BaseAvatar.prototype.velocity);
	 doneTheStuff = true;
	 }else{
	 }
 }
 function sp2(){
	 BaseAvatar.prototype.speed = false;
	 boosta();
		this.velocity = 16;
		updater();
	 if(!doneTheStuff){

	 console.log(BaseAvatar.prototype.velocity);
	 doneTheStuff = true;
	 }else{
	 }
 }
BaseAvatar.prototype.equal = function(avatar)
{
    return this.id === avatar.id;
};

/**
 * Set Point
 *
 * @param {Float} x
 * @param {Float} y
 */
BaseAvatar.prototype.setPosition = function(x, y)
{
    this.x = x;
    this.y = y;
};
BaseAvatar.prototype.setPrinting = function(printing)
{
    printing = printing ? true : false;

    if (this.printing !== printing) {
        this.printing = printing;

        this.addPoint(this.x, this.y, true);

        if (!this.printing) {
            this.trail.clear();
        }
    }
	console.log(BaseAvatar.prototype.velocity);
	console.log(BaseAvatar.prototype.speed);
	boosta();
	if(BaseAvatar.prototype.speed === true){
	this.updateVelocities();
    this.velocity = 28;
    this.updateVelocities();
	}
};
/**
 * Add point
 *
 * @param {Float} x
 * @param {Float} y
 */
BaseAvatar.prototype.addPoint = function(x, y)
{
    this.trail.addPoint(x, y);
};

/**
 * Update angular velocity
 *
 * @param {Number} factor
 */
BaseAvatar.prototype.updateAngularVelocity = function(factor)
{
    if (typeof(factor) === 'undefined') {
        if (this.angularVelocity === 0) { return; }
        factor = (this.angularVelocity > 0 ? 1 : -1) * (this.inverse ? -1 : 1);
    }

    this.setAngularVelocity(factor * this.angularVelocityBase * (this.inverse ? -1 : 1));
};

/**
 * Set angular velocity
 *
 * @param {Float} angularVelocity
 */
BaseAvatar.prototype.setAngularVelocity = function(angularVelocity)
{
    this.angularVelocity = angularVelocity;
};

/**
 * Set angle
 *
 * @param {Float} angle
 */
BaseAvatar.prototype.setAngle = function(angle)
{
    if (this.angle !== angle) {
        this.angle = angle;
        this.updateVelocities();
    }
};

/**
 * Update
 *
 * @param {Number} step
 */
BaseAvatar.prototype.update = function(step) {
boosta();
this.updateVelocities();
};

/**
 * Add angle
 *
 * @param {Number} step
 */
BaseAvatar.prototype.updateAngle = function(step)
{
    if (this.angularVelocity) {
        if (this.directionInLoop) {
            this.setAngle(this.angle + this.angularVelocity * step);
        } else {
            this.setAngle(this.angle + this.angularVelocity * step);
            this.updateAngularVelocity(0);

        }
    }
};

/**
 * Update position
 *
 * @param {Number} step
 */
BaseAvatar.prototype.updatePosition = function(step)
{
    this.setPosition(
        this.x + this.velocityX * step,
        this.y + this.velocityY * step
    );
};

/**
 * Set velocity
 *
 * @param {Number} step
 */
BaseAvatar.prototype.setVelocity = function(velocity)
{
	if( BaseAvatar.prototype.speed === true){
		this.velocity = 56;
		BaseAvatar.prototype.velocity = 56;
		velocity = Math.max(velocity, BaseAvatar.prototype.velocity);
	    this.updateVelocities();
	}
	else{
		this.velocity = 16;
		BaseAvatar.prototype.velocity = 56;
		velocity = Math.max(velocity, BaseAvatar.prototype.velocity/2);
	    this.updateVelocities();
	}

    if (this.velocity !== velocity) {
        this.velocity = velocity;
        this.updateVelocities();
    }
};
/**
 * Update velocities
 */
BaseAvatar.prototype.updateVelocities = function()
{
    var velocity = this.velocity/1000;

    this.velocityX = Math.cos(this.angle) * velocity;
    this.velocityY = Math.sin(this.angle) * velocity;

    this.updateBaseAngularVelocity();
};

/**
 * Update base angular velocity
 */
BaseAvatar.prototype.updateBaseAngularVelocity = function()
{
    if (this.directionInLoop) {
        var ratio = this.velocity / BaseAvatar.prototype.velocity;
        this.angularVelocityBase = ratio*1.4 * BaseAvatar.prototype.angularVelocityBase + Math.log(1/ratio)/3000;
        this.updateAngularVelocity();
    }
};

/**
 * Set radius
 *
 * @param {Number} radius
 */
BaseAvatar.prototype.setRadius = function(radius)
{
    this.radius = Math.max(radius, BaseAvatar.prototype.radius/8);
};

/**
 * Set inverse
 *
 * @param {Number} inverse
 */
BaseAvatar.prototype.setInverse = function(inverse)
{
    if (this.inverse !== inverse) {
        this.inverse = inverse ? true : false;
        this.updateAngularVelocity();
    }
};

/**
 * Set invincible
 *
 * @param {Number} invincible
 */
BaseAvatar.prototype.setInvincible = function(invincible)
{
    this.invincible = invincible ? true : false;
};

/**
 * Get distance
 *
 * @param {Number} fromX
 * @param {Number} fromY
 * @param {Number} toX
 * @param {Number} toY
 *
 * @return {Number}
 */
BaseAvatar.prototype.getDistance = function(fromX, fromY, toX, toY)
{
    return Math.sqrt(Math.pow(fromX - toX, 2) + Math.pow(fromY - toY, 2));
};

/**
 * Die
 */
BaseAvatar.prototype.die = function()
{
    this.bonusStack.clear();
    this.alive = false;
    this.addPoint(this.x, this.y);
};

/**
 * Set printing
 *
 * @param {Boolean} printing
 */

/**
 * This score
 *
 * @param {Number} score
 */
BaseAvatar.prototype.addScore = function(score)
{
    this.setRoundScore(this.roundScore + score);
};

/**
 * Resolve score
 *
 * @param {Number} score
 */
BaseAvatar.prototype.resolveScore = function()
{
    this.setScore(this.score + this.roundScore);
    this.roundScore = 0;
};

/**
 * This round score
 *
 * @param {Number} score
 */
BaseAvatar.prototype.setRoundScore = function(score)
{
    this.roundScore = score;
};

/**
 * This score
 *
 * @param {Number} score
 */
BaseAvatar.prototype.setScore = function(score)
{
    this.score = score;
};

/**
 * Set color
 *
 * @param {Number} color
 */
BaseAvatar.prototype.setColor = function(color)
{
    this.color = color;
};

/**
 * Clear
 */
BaseAvatar.prototype.clear = function()
{
    this.bonusStack.clear();

    this.x                   = this.radius;
    this.y                   = this.radius;
    this.angle               = 0;
    this.velocityX           = 0;
    this.velocityY           = 0;
    this.angularVelocity     = 0;
    this.roundScore          = 0;
    this.velocity            = BaseAvatar.prototype.velocity;
    this.alive               = true;
    this.printing            = false;
    this.color               = this.player.color;
    this.radius              = BaseAvatar.prototype.radius;
    this.inverse             = BaseAvatar.prototype.inverse;
    this.invincible          = BaseAvatar.prototype.invincible;
    this.directionInLoop     = BaseAvatar.prototype.directionInLoop;
    this.angularVelocityBase = BaseAvatar.prototype.angularVelocityBase;

    if (this.body) {
        this.body.radius = BaseAvatar.prototype.radius;
    }

    // useless? this.updateVelocities();
};

/**
 * Destroy
 */
BaseAvatar.prototype.destroy = function()
{
    this.clear();
    this.present = false;
    this.alive   = false;
};

/**
 * Serialize
 *
 * @return {Object}
 */
BaseAvatar.prototype.serialize = function()
{
    return {
        id: this.id,
        name: this.name,
        color: this.color,
        score: this.score
    };
};
<commit_msg>agsag<commit_after>/**
 * Base Avatar
 *
 * @param {Player} player
 */
function BaseAvatar(player)
{
    EventEmitter.call(this);

    this.id              = player.id;
    this.name            = player.name;
    this.color           = player.color;
    this.player          = player;
    this.x               = 0;
    this.y               = 0;
    this.trail           = new Trail(this);
    this.bonusStack      = new BonusStack(this);
    this.angle           = 0;
    this.velocityX       = 0;
    this.velocityY       = 0;
    this.angularVelocity = 0;
    this.alive           = true;
    this.printing        = false;
    this.score           = 0;
    this.roundScore      = 0;
    this.ready           = false;
    this.present         = true;
	BaseAvatar.prototype.velocity = 16;

    this.updateVelocities();
}

BaseAvatar.prototype = Object.create(EventEmitter.prototype);
BaseAvatar.prototype.constructor = BaseAvatar;

if( BaseAvatar.prototype.speed === true){
	BaseAvatar.prototype.velocity = 56;
	this.updateVelocities();
	console.log('speed mode');
}
if(	BaseAvatar.prototype.speed === false){
	BaseAvatar.prototype.velocity = 16;
	this.updateVelocities();
	console.log('normal mode');
}
/**
 * Movement velocity
 *
 * @type {Number}
 */

var doneTheStuff;

	function boosta(){
		return;
	}

/**
 * Turn velocity
 *
 * @type {Float}
 */
BaseAvatar.prototype.angularVelocityBase = 2.8/1000;

/**
 * Radius
 *
 * @type {Number}
 */
BaseAvatar.prototype.radius = 0.6;

/**
 * Number of trail points that don't kill the player
 *
 * @type {Number}
 */
BaseAvatar.prototype.trailLatency = 3;

/**
 * Inverted controls
 *
 * @type {Boolean}
 */
BaseAvatar.prototype.inverse = false;

/**
 * Invincible
 *
 * @type {Boolean}
 */
BaseAvatar.prototype.invincible = false;

/**
 * Type of tunrn: round or straight
 *
 * @type {Boolean}
 */
BaseAvatar.prototype.directionInLoop = true;

/**
 * Equal
 *
 * @param {Avatar} avatar
 *
 * @return {Boolean}
 */

function updater()
{
    var velocity = this.velocity/1000;

    this.velocityX = Math.cos(this.angle) * velocity;
    this.velocityY = Math.sin(this.angle) * velocity;

    this.updateBaseAngularVelocity();
}
 function sp1(){
	 BaseAvatar.prototype.speed = true;
	 boosta();
	 //BaseAvatar.prototype.setVelocity.call(this, 'velocity', 0.75 * 16);
	 //BaseAvatar.prototype.setVelocity.call(velocity);

		this.velocity = 28;
		updater();
	 if(!doneTheStuff){

	 console.log(BaseAvatar.prototype.velocity);
	 doneTheStuff = true;
	 }else{
	 }
 }
 function sp2(){
	 BaseAvatar.prototype.speed = false;
	 boosta();
		this.velocity = 16;
		updater();
	 if(!doneTheStuff){

	 console.log(BaseAvatar.prototype.velocity);
	 doneTheStuff = true;
	 }else{
	 }
 }
BaseAvatar.prototype.equal = function(avatar)
{
    return this.id === avatar.id;
};

/**
 * Set Point
 *
 * @param {Float} x
 * @param {Float} y
 */
BaseAvatar.prototype.setPosition = function(x, y)
{
    this.x = x;
    this.y = y;
};
BaseAvatar.prototype.setPrinting = function(printing)
{
    printing = printing ? true : false;

    if (this.printing !== printing) {
        this.printing = printing;

        this.addPoint(this.x, this.y, true);

        if (!this.printing) {
            this.trail.clear();
        }
    }
	console.log(BaseAvatar.prototype.velocity);
	console.log(BaseAvatar.prototype.speed);
	boosta();
	if(BaseAvatar.prototype.speed === true){
	this.updateVelocities();
    this.velocity = 28;
    this.updateVelocities();
	}
};
/**
 * Add point
 *
 * @param {Float} x
 * @param {Float} y
 */
BaseAvatar.prototype.addPoint = function(x, y)
{
    this.trail.addPoint(x, y);
};

/**
 * Update angular velocity
 *
 * @param {Number} factor
 */
BaseAvatar.prototype.updateAngularVelocity = function(factor)
{
    if (typeof(factor) === 'undefined') {
        if (this.angularVelocity === 0) { return; }
        factor = (this.angularVelocity > 0 ? 1 : -1) * (this.inverse ? -1 : 1);
    }

    this.setAngularVelocity(factor * this.angularVelocityBase * (this.inverse ? -1 : 1));
};

/**
 * Set angular velocity
 *
 * @param {Float} angularVelocity
 */
BaseAvatar.prototype.setAngularVelocity = function(angularVelocity)
{
    this.angularVelocity = angularVelocity;
};

/**
 * Set angle
 *
 * @param {Float} angle
 */
BaseAvatar.prototype.setAngle = function(angle)
{
    if (this.angle !== angle) {
        this.angle = angle;
        this.updateVelocities();
    }
};

/**
 * Update
 *
 * @param {Number} step
 */
BaseAvatar.prototype.update = function(step) {
boosta();
this.updateVelocities();
};

/**
 * Add angle
 *
 * @param {Number} step
 */
BaseAvatar.prototype.updateAngle = function(step)
{
    if (this.angularVelocity) {
        if (this.directionInLoop) {
            this.setAngle(this.angle + this.angularVelocity * step);
        } else {
            this.setAngle(this.angle + this.angularVelocity * step);
            this.updateAngularVelocity(0);

        }
    }
};

/**
 * Update position
 *
 * @param {Number} step
 */
BaseAvatar.prototype.updatePosition = function(step)
{
    this.setPosition(
        this.x + this.velocityX * step,
        this.y + this.velocityY * step
    );
};

/**
 * Set velocity
 *
 * @param {Number} step
 */
BaseAvatar.prototype.setVelocity = function(velocity)
{
	if( BaseAvatar.prototype.speed === true){
		this.velocity = 56;
		BaseAvatar.prototype.velocity = 56;
		velocity = Math.max(velocity, BaseAvatar.prototype.velocity);
	    this.updateVelocities();
	}
	else{
		this.velocity = 16;
		BaseAvatar.prototype.velocity = 56;
		velocity = Math.max(velocity, BaseAvatar.prototype.velocity/2);
	    this.updateVelocities();
	}

    if (this.velocity !== velocity) {
        this.velocity = velocity;
        this.updateVelocities();
    }
};
/**
 * Update velocities
 */
BaseAvatar.prototype.updateVelocities = function()
{
    var velocity = this.velocity/1000;

    this.velocityX = Math.cos(this.angle) * velocity;
    this.velocityY = Math.sin(this.angle) * velocity;

    this.updateBaseAngularVelocity();
};

/**
 * Update base angular velocity
 */
BaseAvatar.prototype.updateBaseAngularVelocity = function()
{
    if (this.directionInLoop) {
        var ratio = this.velocity / BaseAvatar.prototype.velocity;
        this.angularVelocityBase = ratio*1.4 * BaseAvatar.prototype.angularVelocityBase + Math.log(1/ratio)/3000;
        this.updateAngularVelocity();
    }
};

/**
 * Set radius
 *
 * @param {Number} radius
 */
BaseAvatar.prototype.setRadius = function(radius)
{
    this.radius = Math.max(radius, BaseAvatar.prototype.radius/8);
};

/**
 * Set inverse
 *
 * @param {Number} inverse
 */
BaseAvatar.prototype.setInverse = function(inverse)
{
    if (this.inverse !== inverse) {
        this.inverse = inverse ? true : false;
        this.updateAngularVelocity();
    }
};

/**
 * Set invincible
 *
 * @param {Number} invincible
 */
BaseAvatar.prototype.setInvincible = function(invincible)
{
    this.invincible = invincible ? true : false;
};

/**
 * Get distance
 *
 * @param {Number} fromX
 * @param {Number} fromY
 * @param {Number} toX
 * @param {Number} toY
 *
 * @return {Number}
 */
BaseAvatar.prototype.getDistance = function(fromX, fromY, toX, toY)
{
    return Math.sqrt(Math.pow(fromX - toX, 2) + Math.pow(fromY - toY, 2));
};

/**
 * Die
 */
BaseAvatar.prototype.die = function()
{
    this.bonusStack.clear();
    this.alive = false;
    this.addPoint(this.x, this.y);
};

/**
 * Set printing
 *
 * @param {Boolean} printing
 */

/**
 * This score
 *
 * @param {Number} score
 */
BaseAvatar.prototype.addScore = function(score)
{
    this.setRoundScore(this.roundScore + score);
};

/**
 * Resolve score
 *
 * @param {Number} score
 */
BaseAvatar.prototype.resolveScore = function()
{
    this.setScore(this.score + this.roundScore);
    this.roundScore = 0;
};

/**
 * This round score
 *
 * @param {Number} score
 */
BaseAvatar.prototype.setRoundScore = function(score)
{
    this.roundScore = score;
};

/**
 * This score
 *
 * @param {Number} score
 */
BaseAvatar.prototype.setScore = function(score)
{
    this.score = score;
};

/**
 * Set color
 *
 * @param {Number} color
 */
BaseAvatar.prototype.setColor = function(color)
{
    this.color = color;
};

/**
 * Clear
 */
BaseAvatar.prototype.clear = function()
{
    this.bonusStack.clear();

    this.x                   = this.radius;
    this.y                   = this.radius;
    this.angle               = 0;
    this.velocityX           = 0;
    this.velocityY           = 0;
    this.angularVelocity     = 0;
    this.roundScore          = 0;
    this.velocity            = BaseAvatar.prototype.velocity;
    this.alive               = true;
    this.printing            = false;
    this.color               = this.player.color;
    this.radius              = BaseAvatar.prototype.radius;
    this.inverse             = BaseAvatar.prototype.inverse;
    this.invincible          = BaseAvatar.prototype.invincible;
    this.directionInLoop     = BaseAvatar.prototype.directionInLoop;
    this.angularVelocityBase = BaseAvatar.prototype.angularVelocityBase;

    if (this.body) {
        this.body.radius = BaseAvatar.prototype.radius;
    }

    // useless? this.updateVelocities();
};

/**
 * Destroy
 */
BaseAvatar.prototype.destroy = function()
{
    this.clear();
    this.present = false;
    this.alive   = false;
};

/**
 * Serialize
 *
 * @return {Object}
 */
BaseAvatar.prototype.serialize = function()
{
    return {
        id: this.id,
        name: this.name,
        color: this.color,
        score: this.score
    };
};
<|endoftext|>


<commit_before>/*
 Copyright 2015 Google Inc. All Rights Reserved.
 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at
 http://www.apache.org/licenses/LICENSE-2.0
 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
*/

'use strict';

// Incrementing CACHE_VERSION will kick off the install event and force previously cached
// resources to be cached again.
const CACHE_VERSION = 1;
let CURRENT_CACHES = {
  offline: 'offline-v' + CACHE_VERSION
};
const OFFLINE_URL = 'offline.html';

function createCacheBustedRequest(url) {
  let request = new Request(url, {cache: 'reload'});
  // See https://fetch.spec.whatwg.org/#concept-request-mode
  // This is not yet supported in Chrome as of M48, so we need to explicitly check to see
  // if the cache: 'reload' option had any effect.
  if ('cache' in request) {
    return request;
  }

  // If {cache: 'reload'} didn't have any effect, append a cache-busting URL parameter instead.
  let bustedUrl = new URL(url, self.location.href);
  bustedUrl.search += (bustedUrl.search ? '&' : '') + 'cachebust=' + Date.now();
  return new Request(bustedUrl);
}

self.addEventListener('install', event => {
  event.waitUntil(
    // We can't use cache.add() here, since we want OFFLINE_URL to be the cache key, but
    // the actual URL we end up requesting might include a cache-busting parameter.
    fetch(createCacheBustedRequest(OFFLINE_URL)).then(function(response) {
      return caches.open(CURRENT_CACHES.offline).then(function(cache) {
        return cache.put(OFFLINE_URL, response);
      });
    })
  );
});

self.addEventListener('activate', event => {
  // Delete all caches that aren't named in CURRENT_CACHES.
  // While there is only one cache in this example, the same logic will handle the case where
  // there are multiple versioned caches.
  let expectedCacheNames = Object.keys(CURRENT_CACHES).map(function(key) {
    return CURRENT_CACHES[key];
  });

  event.waitUntil(
    caches.keys().then(cacheNames => {
      return Promise.all(
        cacheNames.map(cacheName => {
          if (expectedCacheNames.indexOf(cacheName) === -1) {
            // If this cache name isn't present in the array of "expected" cache names,
            // then delete it.
            console.log('Deleting out of date cache:', cacheName);
            return caches.delete(cacheName);
          }
        })
      );
    })
  );
});

self.addEventListener('fetch', event => {
  // We only want to call event.respondWith() if this is a navigation request
  // for an HTML page.
  // request.mode of 'navigate' is unfortunately not supported in Chrome
  // versions older than 49, so we need to include a less precise fallback,
  // which checks for a GET request with an Accept: text/html header.
  if (event.request.mode === 'navigate' ||
      (event.request.method === 'GET' &&
       event.request.headers.get('accept').includes('text/html'))) {
    console.log('Handling fetch event for', event.request.url);
    event.respondWith(
      fetch(event.request).catch(error => {
        // The catch is only triggered if fetch() throws an exception, which will most likely
        // happen due to the server being unreachable.
        // If fetch() returns a valid HTTP response with an response code in the 4xx or 5xx
        // range, the catch() will NOT be called. If you need custom handling for 4xx or 5xx
        // errors, see https://github.com/GoogleChrome/samples/tree/gh-pages/service-worker/fallback-response
        console.log('Fetch failed; returning offline page instead.', error);
        return caches.match(OFFLINE_URL);
      })
    );
  }

  // If our if() condition is false, then this fetch handler won't intercept the request.
  // If there are any other fetch handlers registered, they will get a chance to call
  // event.respondWith(). If no fetch handlers call event.respondWith(), the request will be
  // handled by the browser as if there were no service worker involvement.
});
<commit_msg>Custom offline page service worker revamp (#657)<commit_after>/*
Copyright 2015, 2019 Google Inc. All Rights Reserved.
 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at
 http://www.apache.org/licenses/LICENSE-2.0
 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
*/

// Incrementing OFFLINE_VERSION will kick off the install event and force
// previously cached resources to be updated from the network.
const OFFLINE_VERSION = 1;
const CACHE_NAME = 'offline';
// Customize this with a different URL if needed.
const OFFLINE_URL = 'offline.html';

self.addEventListener('install', (event) => {
  event.waitUntil((async () => {
    const cache = await caches.open(CACHE_NAME);
    // Setting {cache: 'reload'} in the new request will ensure that the response
    // isn't fulfilled from the HTTP cache; i.e., it will be from the network.
    await cache.add(new Request(OFFLINE_URL, {cache: 'reload'}));
  })());
});

self.addEventListener('activate', (event) => {
  event.waitUntil((async () => {
    // Enable navigation preload if it's supported.
    // See https://developers.google.com/web/updates/2017/02/navigation-preload
    if ('navigationPreload' in self.registration) {
      await self.registration.navigationPreload.enable();
    }
  })());

  // Tell the active service worker to take control of the page immediately.
  self.clients.claim();
});

self.addEventListener('fetch', (event) => {
  // We only want to call event.respondWith() if this is a navigation request
  // for an HTML page.
  if (event.request.mode === 'navigate') {
    event.respondWith((async () => {
      try {
        // First, try to use the navigation preload response if it's supported.
        const preloadResponse = await event.preloadResponse;
        if (preloadResponse) {
          return preloadResponse;
        }

        const networkResponse = await fetch(event.request);
        return networkResponse;
      } catch (error) {
        // catch is only triggered if an exception is thrown, which is likely
        // due to a network error.
        // If fetch() returns a valid HTTP response with a response code in
        // the 4xx or 5xx range, the catch() will NOT be called.
        console.log('Fetch failed; returning offline page instead.', error);

        const cache = await caches.open(CACHE_NAME);
        const cachedResponse = await cache.match(OFFLINE_URL);
        return cachedResponse;
      }
    })());
  }

  // If our if() condition is false, then this fetch handler won't intercept the
  // request. If there are any other fetch handlers registered, they will get a
  // chance to call event.respondWith(). If no fetch handlers call
  // event.respondWith(), the request will be handled by the browser as if there
  // were no service worker involvement.
});
<|endoftext|>


<commit_before>'use strict';

import path from 'path';
import bodyParser from 'body-parser';
import compress from 'compression';
import express from 'express';
import favicon from 'serve-favicon';
import helmet from 'helmet';
import jade from 'jade';
import jadeBabel from 'jade-babel';
import mongoose from 'mongoose';
import logger from './app/helpers/logger';

// BASIC CONFIG
const config = {
  // address of mongodb
  db: process.env.MONGOURI || 'mongodb://localhost:27017/mapper',
  // environment
  env: process.env.NODE_ENV || 'development',
  // port on which to listen
  port: 5000,
  // path to root directory of this app
  root: path.normalize(__dirname)
};

// EXPRESS SET-UP
// create app
const app = express();
// use jade and set views and static directories
jade.filters.babel = jadeBabel();
app.set('view engine', 'jade');
app.set('views', path.join(config.root, 'app/views'));
app.use(express.static(path.join(config.root, 'static')));
//add middlewares
app.use(bodyParser.urlencoded({
  extended: false
}));
app.use(compress());
app.use(favicon(path.join(config.root, 'static/img/favicon.png')));
app.use(helmet());
// load all models
require(path.join(config.root, 'app/models'));
// load all controllers
app.use('/', require(path.join(config.root, 'app/controllers')));
// catch 404 and forward to error handler
app.use((req, res, next) => {
  const err = new Error('Not Found');
  err.status = 404;
  return next(err);
});
// general errors
app.use((err, req, res, next) => {
  const sc = err.status || 500;
  res.status(sc);
  return res.render('error', {
    title: '*error*',
    status: sc,
    message: err.message,
    stack: config.env === 'development' ? err.stack : ''
  });
});

// MONGOOSE SET-UP
mongoose.connect(config.db);
const db = mongoose.connection;
db.on('error', () => {
  throw new Error(`unable to connect to database at ${config.db}`);
});

// START AND STOP
const server = app.listen(config.port, () => {
  logger.info(`listening on port ${config.port}`);
});
process.on('SIGINT', () => {
  logger.info('shutting down!');
  db.close();
  server.close();
  process.exit();
});
<commit_msg>changed favicon<commit_after>'use strict';

import path from 'path';
import bodyParser from 'body-parser';
import compress from 'compression';
import express from 'express';
import favicon from 'serve-favicon';
import helmet from 'helmet';
import jade from 'jade';
import jadeBabel from 'jade-babel';
import mongoose from 'mongoose';
import logger from './app/helpers/logger';

// BASIC CONFIG
const config = {
  // address of mongodb
  db: process.env.MONGOURI || 'mongodb://localhost:27017/mapper',
  // environment
  env: process.env.NODE_ENV || 'development',
  // port on which to listen
  port: 5000,
  // path to root directory of this app
  root: path.normalize(__dirname)
};

// EXPRESS SET-UP
// create app
const app = express();
// use jade and set views and static directories
jade.filters.babel = jadeBabel();
app.set('view engine', 'jade');
app.set('views', path.join(config.root, 'app/views'));
app.use(express.static(path.join(config.root, 'static')));
//add middlewares
app.use(bodyParser.urlencoded({
  extended: false
}));
app.use(compress());
app.use(favicon(path.join(config.root, 'static/img/pin.png')));
app.use(helmet());
// load all models
require(path.join(config.root, 'app/models'));
// load all controllers
app.use('/', require(path.join(config.root, 'app/controllers')));
// catch 404 and forward to error handler
app.use((req, res, next) => {
  const err = new Error('Not Found');
  err.status = 404;
  return next(err);
});
// general errors
app.use((err, req, res, next) => {
  const sc = err.status || 500;
  res.status(sc);
  return res.render('error', {
    title: '*error*',
    status: sc,
    message: err.message,
    stack: config.env === 'development' ? err.stack : ''
  });
});

// MONGOOSE SET-UP
mongoose.connect(config.db);
const db = mongoose.connection;
db.on('error', () => {
  throw new Error(`unable to connect to database at ${config.db}`);
});

// START AND STOP
const server = app.listen(config.port, () => {
  logger.info(`listening on port ${config.port}`);
});
process.on('SIGINT', () => {
  logger.info('shutting down!');
  db.close();
  server.close();
  process.exit();
});
<|endoftext|>