<commit_before>var i=['Jakarta','Bandung','Denpasar','Medan','Surabaya','Semarang','Yogyakarta','Samarinda','Padang','Bogor','Balikpapan','Banjarmasin','Makassar','Aceh','Solo','Sukabumi','Manado','Pekanbaru','Jayapura','Maluku','Ambon','Gorontalo','Palu','Jambi','Batam','Bekasi','Tangerang','Cilacap','Berau','Malang','Sidoarjo','Kendal','Ambarawa','Kudus','Pati','Demak','Banten','Magelang','NTT','Buton'];var j=Math.random()*i.length;j=parseInt(j,10);var o='';var k='<data:blog.pageName/> | ';
document.write(k+i[j]+o);

var a=12;
var b=Math.floor((Math.random()*a));var c=new Array();var d=[];var e=[];var f=[];var g=' - ';var h=' <data:blog.title/> ';var l=' <data:blog.pageName/>, ';var m=' kategori <data:label.name/>,';

c[0]='Hallo sahabat';
d[0]='sekalian, kali ini kami persembahkan';
e[0]='telah dipilih dari aquarium dunia perlendiran. Semoga kali ini ';
f[0]='dapat memuaskan hasrat kisanak. Selamat menikmati.';
c[1]='Apakabar kawan';
d[1]='semuanya, saat ini kami suguhkan';
e[1]='telah disortir dari kolam kenikmatan dunia. Mudah-mudahan ';
f[1]='bisa menyenangkan diri kawan. Selamat menghayati.';
c[2]='Hai perkumpulan';
d[2]='yang terhormat, kesempatan ini kami hadirkan';
e[2]='sukses diselamatkan dari kejamnya alam maya. Semoga saja ';
f[2]='bisa membuat suasana lebih gembira. Silahkan dinikmati.';
c[3]='Salam abang-abang peminat';
d[3]='yang tersayang, pada kali ini adinda menayangkan';
e[3]='sudah adinda pilih dengan sebaiknya dari koleksi pribadi. Mudah-mudahan ';
f[3]='bisa membuat abang mabuk kepayang. Jangan malu-malu, silahkan ya abang.';
c[4]='Halo colimania penggemar';
d[4]='disana, sekarang ini kita akan menikmati sajian';
e[4]='baru saja disadur oleh tim rekdasi percolian. Andaikan saja ';
f[4]='bisa membuat colimania muncrat berkali-kali. Selamat menyelami.';
c[5]='Terimakasih telah mengunjungi';
d[5]='yang akan selalu setia menemani, pada momen indah ini kami akan berbagi';
e[5]='berhasil kami unduh dengan sempurna. Silahkan beri penilaian pada ';
f[5]='yang mungkin akan membuat anda terlena sesaat. Mari kita lanjutkan.';
c[6]='Sugeng rawuh poro tamu';
d[6]='sedoyo, sakmeniko kulo bade ngaturaken';
e[6]='sing pasti jos gandos kotos-kotos nganti mbledos. Mugi-mugi serat ';
f[6]='saget kangge bahan coli. Monggo dipunsekecaaken.';
c[7]='Brotherhood';
d[7]='yang saya hormati, pada tour dunia maya kali ini';
e[7]='sudah bro sisihkan yang terbaik. Semoga jodoh dari ';
f[7]='dapat membuat bro sekalian terhibur. Selamat menyaksikan.';
c[8]='Hai kakakku tersayang pengunjung';
d[8]=', kali ini Icha mau berbagi';
e[8]='yang udah Icha susun sedemikian rupa. Biarlah agak ngawur, semoga ';
f[8]='bisa bikin adik kecil kakak kesemutan. Yuk simak dibawah ini.';
c[9]='Kabar sukacita untuk member';
d[9]='yang selalu haus hasrat seksual, saat ini telah hadir info';
e[9]='untuk melengkapi perburuan di alam lendir. Biarlah kali ini ';
f[9]='yang mengambil alih kesadaran kalian sementara. Selamat menikmati.';
c[10]='Dalam cahaya temaram';
d[10]='yang selalu membius pemirsa, suguhan kali ini adalah';
e[10]='nan akan membawa birahi pemirsa ke tingkat yang lebih tinggi. Pilihan kali ini ada dalam ';
f[10]='yang semoga saja tepat sasaran ke titik kepuasan. Mari kita simak bersama.';
c[11]='Jumpa lagi di';
d[11]='blog ladang cuci mata nusantara, etalase saat ini berisi tentang';
e[11]='juga merupakan bahan unggulan dari blog kami. Diambil dari ';
f[11]='yang mana diharapkan menjadi bahan primadona para pembaca sekalian. Langsung saja berikut ini.';

document.write(g+c[b]+h+d[b]+l+e[b]+m+f[b]);document.write('

Keterangan
Judul : <data:post.title/>
Tautan : <data:post.title/>
');document.write(unescape('%3C%69%66%72%61%6D%65%20%73%72%63%3D%22%2F%2F%61%64%73%2E%65%78%6F%63%6C%69%63%6B%2E%63%6F%6D%2F%69%66%72%61%6D%65%2E%70%68%70%3F%69%64%7A%6F%6E%65%3D%32%32%33%30%39%32%39%26%73%69%7A%65%3D%37%32%38%78%39%30%22%20%77%69%64%74%68%3D%22%37%32%38%22%20%68%65%69%67%68%74%3D%22%39%30%22%20%73%63%72%6F%6C%6C%69%6E%67%3D%22%6E%6F%22%20%6D%61%72%67%69%6E%77%69%64%74%68%3D%22%30%22%20%6D%61%72%67%69%6E%68%65%69%67%68%74%3D%22%30%22%20%66%72%61%6D%65%62%6F%72%64%65%72%3D%22%30%22%3E%3C%2F%69%66%72%61%6D%65%3E'));document.write('

');
<commit_msg>Delete icha.head.v1.js<commit_after><|endoftext|>


<commit_before>(function (root, factory) {
  if (typeof exports === 'object') {
    // CommonJS
    module.exports = factory();
  } else if (typeof define === 'function' && define.amd) {
    // AMD
    define(['corsRequest'], function() {
      return (root.corsRequest = factory());
    });
  } else {
    // Global variable
    root.corsRequest = factory();
  }
}(this, function() {

  // Determine the underlying implementation to be used.
  var useXhr = 'withCredentials' in new XMLHttpRequest();
  var useXdr = !useXhr && typeof XDomainRequest !== 'undefined';
  var Request;
  if (useXhr) {
    Request = XMLHttpRequest;
  } else if (useXdr) {
    Request = XDomainRequest;
  } else {
    throw new Error('corsRequest requires either XMLHttpRequest2 or XDomainRequest');
  }

  // A function that does nothing.
  var noop = function() {};

  // Return a function that only calls fn once.
  function once(fn) {
    var called = false;
    return function() {
      if (!called) {
        called = true;
        return fn.apply(null, arguments);
      }
    };
  }

  // Curry fn on the remaining arguments.
  function curry(fn) {
    var curriedArgs = [].slice.call(arguments, 1);
    return function() {
      var remainingArgs = [].slice.call(arguments);
      return fn.apply(null, curriedArgs.concat(remainingArgs));
    };
  }

  // Encode object as JSON, returning undefined if unsuccessful.
  function toJSON(obj) {
    try {
      return JSON.stringify(obj, null, 0);
    } catch (e) {
      return;
    }
  }

  // Parse string as JSON, returning undefined if unsuccessful.
  function fromJSON(str) {
    try {
      return JSON.parse(str);
    } catch (e) {
      return;
    }
  }

  // Return whether o is a non-null object.
  function isObject(obj) {
    return typeof obj === 'object' && obj !== null;
  }

  // Encode data to JSON representation or string, according to its type.
  function encode(data) {
    if (isObject(data)) {
      return toJSON(data);
    } else {
      return data.toString();
    }
  }

  // Perform and store state for an HTTP request.
  function CorsRequest(method, url, data, done) {

    var self = this;

    done = once(done);

    function error(msg) {
      return new Error('corsRequest: ' + method + ' ' + url + ': ' + msg);
    }

    this.method = method;
    this.url = url;
    this.data = data;

    this.req = new Request();

    this.req.open(this.method, this.url);

    this.req.onerror = function() {
      self.err = error('error');
      done(self.err);
    };

    this.req.onload = function() {
      if (useXhr && self.req.readyState !== 4) {
        // XMLHttpRequest not yet complete.
        return;
      }
      if (useXhr && self.req.status === 0) {
        // XMLHttpRequest aborted, e.g. CORS error or connection reset.
        self.err = error('incomplete');
        done(self.err);
        return;
      }
      // Request complete.
      self.err = null;
      self.res = {
        status: useXhr ? self.req.status : 200,
        text: self.req.responseText,
        json: fromJSON(self.req.responseText)
      };
      done(self.err, self.res);
    };

    // Setting all handlers seems to increase the probability
    // of the request being sucessful on old IE versions.
    if (useXdr) {
      this.req.ontimeout = noop;
      this.req.onprogress = noop;
    }

    this.abort = function() {
      if (self.err === void 0) {
        self.req.abort();
        self.err = error('aborted');
        done(self.err);
      }
    };

    if (this.data !== void 0) {
      var payload = encode(data);
    }

    // Calling send() right away sometimes causes the request
    // to fail on old IE versions.
    setTimeout(function() {
      if (self.err === void 0) {
        self.req.send(payload || null);
      }
    }, 0);

    // Perform our own timeout logic instead of relying on
    // the underlying implementation.
    if (corsRequest.timeout > 0) {
      setTimeout(function() {
        if (self.err === void 0) {
          self.err = error('timeout');
          done(self.err);
        }
      }, corsRequest.timeout);
    }
  }

  // Instantiate CorsRequest with default arguments.
  function corsRequest() {

    var method, url, data, done;

    if (arguments.length < 2) {
      throw new Error('corsRequest: missing argument');
    }

    // corsRequest(method, url, ...)
    method = arguments[0].toUpperCase();
    url = arguments[1];

    if (method !== 'GET' && method !== 'POST') {
      throw new Error('corsRequest: bad method');
    }

    if (arguments.length === 3) {
      if (typeof arguments[2] === 'function') {
        // corsRequest(method, url, done)
        done = arguments[2];
      } else {
        // corsRequest(method, url, data)
        data = arguments[2];
      }
    }

    if (arguments.length > 3) {
      // corsRequest(method, url, data, done)
      data = arguments[2];
      done = arguments[3];
    }

    return new CorsRequest(method, url, data, done || noop);
  }

  // Default timeout value.
  corsRequest.timeout = 0;

  // Report implementation in use.
  corsRequest.usingXhr = useXhr;
  corsRequest.usingXdr = useXdr;

  // Utility functions for individual methods.
  corsRequest.get = curry(corsRequest, 'GET');
  corsRequest.post = curry(corsRequest, 'POST');

  // Export public interface.
  return corsRequest;

}));<commit_msg>Fix UMD boilerplate<commit_after>(function (root, factory) {
  if (typeof exports === 'object') {
    // CommonJS
    module.exports = factory();
  } else if (typeof define === 'function' && define.amd) {
    // AMD
    define(function() {
      return (root.corsRequest = factory());
    });
  } else {
    // Global variable
    root.corsRequest = factory();
  }
}(this, function() {

  // Determine the underlying implementation to be used.
  var useXhr = 'withCredentials' in new XMLHttpRequest();
  var useXdr = !useXhr && typeof XDomainRequest !== 'undefined';
  var Request;
  if (useXhr) {
    Request = XMLHttpRequest;
  } else if (useXdr) {
    Request = XDomainRequest;
  } else {
    throw new Error('corsRequest requires either XMLHttpRequest2 or XDomainRequest');
  }

  // A function that does nothing.
  var noop = function() {};

  // Return a function that only calls fn once.
  function once(fn) {
    var called = false;
    return function() {
      if (!called) {
        called = true;
        return fn.apply(null, arguments);
      }
    };
  }

  // Curry fn on the remaining arguments.
  function curry(fn) {
    var curriedArgs = [].slice.call(arguments, 1);
    return function() {
      var remainingArgs = [].slice.call(arguments);
      return fn.apply(null, curriedArgs.concat(remainingArgs));
    };
  }

  // Encode object as JSON, returning undefined if unsuccessful.
  function toJSON(obj) {
    try {
      return JSON.stringify(obj, null, 0);
    } catch (e) {
      return;
    }
  }

  // Parse string as JSON, returning undefined if unsuccessful.
  function fromJSON(str) {
    try {
      return JSON.parse(str);
    } catch (e) {
      return;
    }
  }

  // Return whether o is a non-null object.
  function isObject(obj) {
    return typeof obj === 'object' && obj !== null;
  }

  // Encode data to JSON representation or string, according to its type.
  function encode(data) {
    if (isObject(data)) {
      return toJSON(data);
    } else {
      return data.toString();
    }
  }

  // Perform and store state for an HTTP request.
  function CorsRequest(method, url, data, done) {

    var self = this;

    done = once(done);

    function error(msg) {
      return new Error('corsRequest: ' + method + ' ' + url + ': ' + msg);
    }

    this.method = method;
    this.url = url;
    this.data = data;

    this.req = new Request();

    this.req.open(this.method, this.url);

    this.req.onerror = function() {
      self.err = error('error');
      done(self.err);
    };

    this.req.onload = function() {
      if (useXhr && self.req.readyState !== 4) {
        // XMLHttpRequest not yet complete.
        return;
      }
      if (useXhr && self.req.status === 0) {
        // XMLHttpRequest aborted, e.g. CORS error or connection reset.
        self.err = error('incomplete');
        done(self.err);
        return;
      }
      // Request complete.
      self.err = null;
      self.res = {
        status: useXhr ? self.req.status : 200,
        text: self.req.responseText,
        json: fromJSON(self.req.responseText)
      };
      done(self.err, self.res);
    };

    // Setting all handlers seems to increase the probability
    // of the request being sucessful on old IE versions.
    if (useXdr) {
      this.req.ontimeout = noop;
      this.req.onprogress = noop;
    }

    this.abort = function() {
      if (self.err === void 0) {
        self.req.abort();
        self.err = error('aborted');
        done(self.err);
      }
    };

    if (this.data !== void 0) {
      var payload = encode(data);
    }

    // Calling send() right away sometimes causes the request
    // to fail on old IE versions.
    setTimeout(function() {
      if (self.err === void 0) {
        self.req.send(payload || null);
      }
    }, 0);

    // Perform our own timeout logic instead of relying on
    // the underlying implementation.
    if (corsRequest.timeout > 0) {
      setTimeout(function() {
        if (self.err === void 0) {
          self.err = error('timeout');
          done(self.err);
        }
      }, corsRequest.timeout);
    }
  }

  // Instantiate CorsRequest with default arguments.
  function corsRequest() {

    var method, url, data, done;

    if (arguments.length < 2) {
      throw new Error('corsRequest: missing argument');
    }

    // corsRequest(method, url, ...)
    method = arguments[0].toUpperCase();
    url = arguments[1];

    if (method !== 'GET' && method !== 'POST') {
      throw new Error('corsRequest: bad method');
    }

    if (arguments.length === 3) {
      if (typeof arguments[2] === 'function') {
        // corsRequest(method, url, done)
        done = arguments[2];
      } else {
        // corsRequest(method, url, data)
        data = arguments[2];
      }
    }

    if (arguments.length > 3) {
      // corsRequest(method, url, data, done)
      data = arguments[2];
      done = arguments[3];
    }

    return new CorsRequest(method, url, data, done || noop);
  }

  // Default timeout value.
  corsRequest.timeout = 0;

  // Report implementation in use.
  corsRequest.usingXhr = useXhr;
  corsRequest.usingXdr = useXdr;

  // Utility functions for individual methods.
  corsRequest.get = curry(corsRequest, 'GET');
  corsRequest.post = curry(corsRequest, 'POST');

  // Export public interface.
  return corsRequest;

}));<|endoftext|>


<commit_before>/*!
 * A very, very simple Event Queue
 *
 * The MIT License (MIT)
 * Copyright (c) 2015 Jonathon Hibbard
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
( function() {
    'use strict';

    var self = this;

    // The primary object being produced
    var AVBCEvent;

    var processedEventDefaults = {
        wasTriggered: false,
        callbackArgs: []
    };

    // A Process Queue for handling Queued Requests.
    function AVBCEvent( obj ) {
        if( obj instanceof AVBCEvent ) {
            return obj;
        }

        if( !( this instanceof AVBCEvent ) ) {
            return new AVBCEvent;
        }

        this._AVBCEvent = obj;  // in case we need it...
    }

    self.AVBCEvent = AVBCEvent;

    if( typeof self['AVBCEventQueue'] === 'undefined' ) {
        self.AVBCEventQueue = {};
    }

    if( typeof self['AVBCEventProcessed'] === 'undefined' ) {
        self.AVBCEventProcessed = {};
    }

    AVBCEvent.trigger = function( event ) {
        var queue = self.AVBCEventQueue[event];
        // we only need to populate this variables at the last responsible moment
        var args, i, listenerCount, enqueuedItem;

        if( typeof queue === 'undefined' ) {
            // nothing to do if this event doesn't exist in the queue
            return;
        }

        args = Array.prototype.slice.call( arguments, 1 );

        for( i = 0; i < queue.length; i++ ) {
            enqueuedItem = queue[i];

            enqueuedItem.callback( args );

            if( !!enqueuedItem.dequeueAfter ) {
                queue.splice( i, 1 );
            }
        }

        self.AVBCEventProcessed[event] = {
            wasTriggered: true,
            callbackArgs: args
        };
    };

    /**
     * @param {Bool} dequeueAfter  When true, the callback being registered along with this event will only be executed once ever if the event is triggered multiple times.
     */
    AVBCEvent.on = function( event, callback, dequeueAfter ) {
        if( typeof self.AVBCEventQueue[event] === 'undefined' ) {
            self.AVBCEventQueue[event] = [];
        }

        if( typeof self.AVBCEventProcessed[event] === 'undefined' ) {
            self.AVBCEventProcessed[event] = Object.create( processedEventDefaults );
        }

        // If this event has already been triggered then execute the callback immediately
        if( AVBCEventProcessed[event].wasTriggered ) {
            callback( self.AVBCEventProcessed[event].callbackArgs );

            // bypass enqueing this callback to this event and execute the callback
            if( !!dequeueAfter ) {
                return;
            }
        }

        self.AVBCEventQueue[event].push({
            callback: callback,
            dequeueAfter: dequeueAfter
        });
    };

    // Completely remove this event and all listeners from the pool
    AVBCEvent.dequeue = function( event ) {
        if( typeof self.AVBCEventQueue[event] !== 'undefined' ) {
            delete self.AVBCEventQueue[event];
        }

        if( typeof self.AVBCEventProcessed[event] !== 'undefined' ) {
            delete self.AVBCEventProcessed[event];
        }
    };

    // Completely remove all events (queued and processed)
    AVBCEvent.drainPool = function() {
        self.AVBCEventQueue = [];
        self.AVBCEventProcessed = [];
    };
}).call( this );
<commit_msg>Updated to return a "copy" of the data we're returning back - so that we don't lose it when it goes out of scope (or is deleted) via AVBCEvent heh...whoops<commit_after>/*!
 * A very, very simple Event Queue
 *
 * The MIT License (MIT)
 * Copyright (c) 2015 Jonathon Hibbard
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
( function() {
    'use strict';

    var self = this;

    // The primary object being produced
    var AVBCEvent;

    var processedEventDefaults = {
        wasTriggered: false,
        callbackArgs: []
    };

    // A Process Queue for handling Queued Requests.
    function AVBCEvent( obj ) {
        if( obj instanceof AVBCEvent ) {
            return obj;
        }

        if( !( this instanceof AVBCEvent ) ) {
            return new AVBCEvent;
        }

        this._AVBCEvent = obj;  // in case we need it...
    }

    self.AVBCEvent = AVBCEvent;

    if( typeof self['AVBCEventQueue'] === 'undefined' ) {
        self.AVBCEventQueue = {};
    }

    if( typeof self['AVBCEventProcessed'] === 'undefined' ) {
        self.AVBCEventProcessed = {};
    }

    AVBCEvent.trigger = function( event ) {
        var queue = self.AVBCEventQueue[event];
        // we only need to populate this variables at the last responsible moment
        var args, i, listenerCount, enqueuedItem;

        if( typeof queue === 'undefined' ) {
            // nothing to do if this event doesn't exist in the queue
            return;
        }

        args = Array.prototype.slice.call( arguments, 1 );

        for( i = 0; i < queue.length; i++ ) {
            enqueuedItem = queue[i];

            enqueuedItem.callback( args.slice() );

            if( !!enqueuedItem.dequeueAfter ) {
                queue.splice( i, 1 );
            }
        }

        self.AVBCEventProcessed[event] = {
            wasTriggered: true,
            callbackArgs: args
        };
    };

    /**
     * @param {Bool} dequeueAfter  When true, the callback being registered along with this event will only be executed once ever if the event is triggered multiple times.
     */
    AVBCEvent.on = function( event, callback, dequeueAfter ) {
        if( typeof self.AVBCEventQueue[event] === 'undefined' ) {
            self.AVBCEventQueue[event] = [];
        }

        if( typeof self.AVBCEventProcessed[event] === 'undefined' ) {
            self.AVBCEventProcessed[event] = Object.create( processedEventDefaults );
        }

        // If this event has already been triggered then execute the callback immediately
        if( AVBCEventProcessed[event].wasTriggered ) {
            callback( self.AVBCEventProcessed[event].callbackArgs.slice() );

            // bypass enqueing this callback to this event and execute the callback
            if( !!dequeueAfter ) {
                return;
            }
        }

        self.AVBCEventQueue[event].push({
            callback: callback,
            dequeueAfter: dequeueAfter
        });
    };

    // Completely remove this event and all listeners from the pool
    AVBCEvent.dequeue = function( event ) {
        if( typeof self.AVBCEventQueue[event] !== 'undefined' ) {
            delete self.AVBCEventQueue[event];
        }

        if( typeof self.AVBCEventProcessed[event] !== 'undefined' ) {
            delete self.AVBCEventProcessed[event];
        }
    };

    // Completely remove all events (queued and processed)
    AVBCEvent.drainPool = function() {
        self.AVBCEventQueue = [];
        self.AVBCEventProcessed = [];
    };
}).call( this );
<|endoftext|>


<commit_before>App.TagField = Em.TextField.extend({
    keyUp: function(e){
        if (e.keyCode == 188) {
            e.preventDefault();
            var val = this.get('value');
            val = val.replace(',','');
            this.set('parentView.new_tag', val);
            this.get('parentView').addTag();
        }
    }
});

App.TagWidget = Em.View.extend({
    templateName: 'tag_widget',
    actions: {
        addTag: function(){
            if (this.get('new_tag')) {
                var new_tag = this.get('new_tag').toLowerCase();
                var tags = this.get('tags');
                // Try to create a new tag, it will fail if it's already in the local store, so catch that.
                try {
                    var tag = App.Tag.createRecord({'id': new_tag});
                } catch(err) {
                    var tag = App.Tag.find(new_tag);
                }
                tag.transitionTo('created.loaded.saved');
                tags.pushObject(tag);
                this.set('new_tag', '');
            }
        },
        removeTag: function(tag) {
            var tags = this.get('tags');
            tags.removeObject(tag);
        }
    },

    didInsertElement: function(){
        var $tag = this.$('.tag');
        if ($tag.length && typeof $tag.typeahead == 'function') {
          $tag.typeahead({
              source: function (query, process) {
                  return $.get('/api/metadata/tags/' + query, function (data) {
                      return process(data);
                  });
              }
          })
        }
    }
});

/**
 * Generic view to plug-in social sharing functionality anywhere in the app.
 * e.g. {{view App.SocialShareView classNames="your-styling-class-name"}}
 *
 * Gets the entire current URL to share, and if available, extra metadata from the API.
 *
 * @class SocialShareView
 * @namespace App
 * @extends Ember.View
 *
 * NOTE: maybe we should look into url shortening?
 */
App.SocialShareView = Em.View.extend({
    templateName: 'social_share',
    dialogW: 626,
    dialogH: 436,

    actions: {
        shareOnFacebook: function() {
            var meta_data = this.get('context').get('meta_data');
            if(meta_data.url){
                var currentLink = encodeURIComponent(meta_data.url);
            } else {
                var currentLink = encodeURIComponent(location.href);
            }
            this.showDialog('https://www.facebook.com/sharer/sharer.php?u=', currentLink, 'facebook');
        },

        shareOnTwitter: function() {
            var meta_data = this.get('context').get('meta_data');

            if(meta_data.url){
                var currentLink = encodeURIComponent(meta_data.url);
            } else {
                var currentLink = encodeURIComponent(location.href);
            }

            // status: e.g. Women first in Botswana {{URL}} via @1percentclub'
            var status = meta_data.tweet.replace('{URL}', currentLink);

            this.showDialog('https://twitter.com/home?status=', status, 'twitter');
        }
    },

    showDialog: function(shareUrl, urlArgs, type) {
        window.open(shareUrl + urlArgs, type + '-share-dialog', 'width=' + this.get('dialogW') + ',height=' + this.get('dialogH'));
    }
});

// See/Use App.DatePicker
App.DatePickerValue = Ember.TextField.extend({
    type: 'hidden',
    valueBinding: "parentView.value"
});

// See/Use App.DatePicker
App.DatePickerWidget = Ember.TextField.extend({

    dateBinding: "parentView.value",
    configBinding: "parentView.config",

    didInsertElement: function(){
        var config = this.get('config');
        this.$().datepicker(config);
        this.$().datepicker('setDate', this.get('date'));
    },

    change: function(){
        this.set('date', this.$().datepicker('getDate'));
    }
});

App.DatePickerButtonWidget = Ember.View.extend({
    templateName: 'date_picker_button',
    dateBinding: "parentView.value",
    configBinding: "parentView.config",
    didInsertElement: function(){
        var config = this.get('config');
        var view = this;
        config.onSelect = function(date, dp){
            view.set('date', view.$('input').datepicker('getDate'));
        }
        this.$('input').datepicker(config);
        this.$('input').datepicker('setDate', this.get('date'));

    },
    actions: {
        showDatePicker: function(){
            this.$('input').datepicker('show');
        }
    }
});

// This renders a TextField with the localized date.
// On click it will use jQuery UI date picker dialog so the user can select a date.
// valueBinding should bind to a  DS.attr('date') property of an Ember model.
App.DatePicker = Ember.ContainerView.extend({
    config: {changeMonth: true, changeYear: true, yearRange: "c-100:c+10"},
    childViews: [App.DatePickerValue, App.DatePickerWidget]
});

App.DateSliderWidget = Ember.TextField.extend({
    type: 'range',
    dateBinding: "parentView.value",
    configBinding: "parentView.config",
    didInsertElement: function(){
        var config = this.get('config');
        var view = this;
        config.callback = function(days){
            var date = new Date(Date.now() + days * 24*3600*1000);
            view.set('date', date);
        },
        config.dimension = ' days';
        config.className = 'slider';
        this.$().slider(config);
        this.updateSlider();
    },
    updateSlider: function(){
        var date = this.get('date');
        var now = new Date();
        var microseconds = date.getTime() - now.getTime();
        var days =  Math.ceil(microseconds / (1000 * 60 * 60 * 24));
        this.set('value', days);
        this.$().slider('value', days);
    }.observes('date')
});

// This renders a slider and datepicker button.
// The slider counts in days. minDate and maxDate should be formated as '+30d'.
App.DatePickerSlider = Ember.ContainerView.extend({
    config: {minDate: 0, maxDate: '+100d'},
    init: function(){
        this._super();
        if (this.get("minDate") != undefined) {
            this.config.minDate = this.get("minDate");
        }
        if (this.get("maxDate") != undefined) {
            this.config.maxDate = this.get("maxDate");
        }
        this.config.from = parseInt(this.config.minDate.replace(/[\+d]/g, ''));
        this.config.to = parseInt(this.config.maxDate.replace(/[\+d]/g, ''));
    },
    childViews: [App.DatePickerValue, App.DateSliderWidget, App.DatePickerButtonWidget]
});

App.CustomDatePicker = App.DatePicker.extend({
    init: function(){
        this._super();
        if (this.get("minDate") != undefined) {
            this.config.minDate = this.get("minDate");
        }
    }
});
<commit_msg>set a default date for slider<commit_after>App.TagField = Em.TextField.extend({
    keyUp: function(e){
        if (e.keyCode == 188) {
            e.preventDefault();
            var val = this.get('value');
            val = val.replace(',','');
            this.set('parentView.new_tag', val);
            this.get('parentView').addTag();
        }
    }
});

App.TagWidget = Em.View.extend({
    templateName: 'tag_widget',
    actions: {
        addTag: function(){
            if (this.get('new_tag')) {
                var new_tag = this.get('new_tag').toLowerCase();
                var tags = this.get('tags');
                // Try to create a new tag, it will fail if it's already in the local store, so catch that.
                try {
                    var tag = App.Tag.createRecord({'id': new_tag});
                } catch(err) {
                    var tag = App.Tag.find(new_tag);
                }
                tag.transitionTo('created.loaded.saved');
                tags.pushObject(tag);
                this.set('new_tag', '');
            }
        },
        removeTag: function(tag) {
            var tags = this.get('tags');
            tags.removeObject(tag);
        }
    },

    didInsertElement: function(){
        var $tag = this.$('.tag');
        if ($tag.length && typeof $tag.typeahead == 'function') {
          $tag.typeahead({
              source: function (query, process) {
                  return $.get('/api/metadata/tags/' + query, function (data) {
                      return process(data);
                  });
              }
          })
        }
    }
});

/**
 * Generic view to plug-in social sharing functionality anywhere in the app.
 * e.g. {{view App.SocialShareView classNames="your-styling-class-name"}}
 *
 * Gets the entire current URL to share, and if available, extra metadata from the API.
 *
 * @class SocialShareView
 * @namespace App
 * @extends Ember.View
 *
 * NOTE: maybe we should look into url shortening?
 */
App.SocialShareView = Em.View.extend({
    templateName: 'social_share',
    dialogW: 626,
    dialogH: 436,

    actions: {
        shareOnFacebook: function() {
            var meta_data = this.get('context').get('meta_data');
            if(meta_data.url){
                var currentLink = encodeURIComponent(meta_data.url);
            } else {
                var currentLink = encodeURIComponent(location.href);
            }
            this.showDialog('https://www.facebook.com/sharer/sharer.php?u=', currentLink, 'facebook');
        },

        shareOnTwitter: function() {
            var meta_data = this.get('context').get('meta_data');

            if(meta_data.url){
                var currentLink = encodeURIComponent(meta_data.url);
            } else {
                var currentLink = encodeURIComponent(location.href);
            }

            // status: e.g. Women first in Botswana {{URL}} via @1percentclub'
            var status = meta_data.tweet.replace('{URL}', currentLink);

            this.showDialog('https://twitter.com/home?status=', status, 'twitter');
        }
    },

    showDialog: function(shareUrl, urlArgs, type) {
        window.open(shareUrl + urlArgs, type + '-share-dialog', 'width=' + this.get('dialogW') + ',height=' + this.get('dialogH'));
    }
});

// See/Use App.DatePicker
App.DatePickerValue = Ember.TextField.extend({
    type: 'hidden',
    valueBinding: "parentView.value"
});

// See/Use App.DatePicker
App.DatePickerWidget = Ember.TextField.extend({

    dateBinding: "parentView.value",
    configBinding: "parentView.config",

    didInsertElement: function(){
        var config = this.get('config');
        this.$().datepicker(config);
        this.$().datepicker('setDate', this.get('date'));
    },

    change: function(){
        this.set('date', this.$().datepicker('getDate'));
    }
});

App.DatePickerButtonWidget = Ember.View.extend({
    templateName: 'date_picker_button',
    dateBinding: "parentView.value",
    configBinding: "parentView.config",
    didInsertElement: function(){
        var config = this.get('config');
        var view = this;
        config.onSelect = function(date, dp){
            view.set('date', view.$('input').datepicker('getDate'));
        }
        this.$('input').datepicker(config);
        this.$('input').datepicker('setDate', this.get('date'));

    },
    actions: {
        showDatePicker: function(){
            this.$('input').datepicker('show');
        }
    }
});

// This renders a TextField with the localized date.
// On click it will use jQuery UI date picker dialog so the user can select a date.
// valueBinding should bind to a  DS.attr('date') property of an Ember model.
App.DatePicker = Ember.ContainerView.extend({
    config: {changeMonth: true, changeYear: true, yearRange: "c-100:c+10"},
    childViews: [App.DatePickerValue, App.DatePickerWidget]
});

App.DateSliderWidget = Ember.TextField.extend({
    type: 'range',
    dateBinding: "parentView.value",
    configBinding: "parentView.config",
    didInsertElement: function(){
        var config = this.get('config');
        var view = this;
        config.callback = function(days){
            var date = new Date(Date.now() + days * 24*3600*1000);
            view.set('date', date);
        },
        config.dimension = ' days';
        config.className = 'slider';
        this.$().slider(config);
        this.updateSlider();
    },
    updateSlider: function(){
        var date = this.get('date') || new Date();
        var now = new Date();
        var microseconds = date.getTime() - now.getTime();
        var days =  Math.ceil(microseconds / (1000 * 60 * 60 * 24));
        this.set('value', days);
        this.$().slider('value', days);
    }.observes('date')
});

// This renders a slider and datepicker button.
// The slider counts in days. minDate and maxDate should be formated as '+30d'.
App.DatePickerSlider = Ember.ContainerView.extend({
    config: {minDate: 0, maxDate: '+100d'},
    init: function(){
        this._super();
        if (this.get("minDate") != undefined) {
            this.config.minDate = this.get("minDate");
        }
        if (this.get("maxDate") != undefined) {
            this.config.maxDate = this.get("maxDate");
        }
        this.config.from = parseInt(this.config.minDate.replace(/[\+d]/g, ''));
        this.config.to = parseInt(this.config.maxDate.replace(/[\+d]/g, ''));
    },
    childViews: [App.DatePickerValue, App.DateSliderWidget, App.DatePickerButtonWidget]
});

App.CustomDatePicker = App.DatePicker.extend({
    init: function(){
        this._super();
        if (this.get("minDate") != undefined) {
            this.config.minDate = this.get("minDate");
        }
    }
});
<|endoftext|>


<commit_before>import React from 'react';
import Link from 'gatsby-link';
import Octokit from '@octokit/rest';
import styled, { injectGlobal } from 'styled-components';
import Assistant from '../../styles/fonts/Assistant-ExtraLight.ttf';

function addProject(prevState, repo) {
  if(!repo) {
    return prevState;
  }

  else {
    const previousProjects = prevState.projects;
    return {
      projects: [...previousProjects, {reponame : repo.name , forks : repo.forks, updatedat : repo.updated_at, stars : repo.stargazers_count}]
    }
  }
}

export default class Projects extends React.Component {
	constructor(props) {
		super(props);
		this.state = {projects : [] , sortBy : ''};
    this.octokit = new Octokit();
	}

	getLeaderboard() {
    this.octokit.repos.getForOrg({ org: 'osdc' }).then(repos => {
      repos.data.forEach((repo) => {
        this.setState(prevState => addProject(prevState, repo));
      });
    });
  }

  componentDidMount() {
    this.getLeaderboard();
  }

	render() {

    const projectList = this.state.projects.slice(0);

    let sortByForks = projectList.sort((a, b) => {
      return b.forks - a.forks;
    });

    // let sortByStars = sorted.sort((a, b) => {
    //   return b.stars - a.stars;
    // });

    // let sortByUpdatedat = projectList.sort((a, b) => {
    //   return b.updatedat - a.updatedat;
    // });

    console.log(sortByForks);

    const list = this.state.projects.map((project, i) => (

{project.reponame} || {project.forks} || {project.updatedat} || {project.stars}

    ));

		return(

        <button onClick={() => this.setState({sortBy : 'stars'})}>Sort by stars</button>

        List of projects

          {list}

		);
	}
}<commit_msg>some changes<commit_after>import React from 'react';
import Link from 'gatsby-link';
import Octokit from '@octokit/rest';
import styled, { injectGlobal } from 'styled-components';
import Assistant from '../../styles/fonts/Assistant-ExtraLight.ttf';

function addProject(prevState, repo) {
  if(!repo) {
    return prevState;
  }

  else {
    const previousProjects = prevState.projects;
    return {
      projects: [...previousProjects, {reponame : repo.name , forks : repo.forks, updatedat : repo.updated_at, stars : repo.stargazers_count}]
    }
  }
}

export default class Projects extends React.Component {
	constructor(props) {
		super(props);
		this.state = {projects : [] , sortBy : ''};
    this.octokit = new Octokit();
	}

	getProjects() {
    this.octokit.repos.getForOrg({ org: 'osdc' }).then(repos => {
      repos.data.forEach((repo) => {
        this.setState(prevState => addProject(prevState, repo));
      });
    });
  }

  componentDidMount() {
    this.getProjects();
  }

	render() {
    const projectList = this.state.projects.slice(0);

    let sortByForks = projectList.sort((a, b) => {
      return b.forks - a.forks;
    });

    let sortByStars = sortByForks.sort((a, b) => {
      return b.stars - a.stars;
    });

    let sortByUpdatedat = sortByStars.sort((a, b) => {
      return b.updatedat - a.updatedat;
    });

    console.log(sortByForks);
    console.log('===========');
    console.log(sortByStars);
    console.log('===========');
    console.log(sortByUpdatedat);

    let list = this.state.projects.map((project, i) => (

{project.reponame} || {project.forks} || {project.updatedat} || {project.stars}

    ));

		return(

        <button onClick={() => this.setState({sortBy : 'stars'})}>Sort by stars</button>

        List of projects

          {list}

		);
	}
}<|endoftext|>


<commit_before>function chatController(postId) {

  var chatDAO = new ChatDAO(postId);
  var lastChatId;
  var firstChatId;
  var isScrollingUp;
  var isWindowActive = true;
  chatDAO.getChatsInfo({limit: 30}, function(chatsInfo) {
    var members = [];
    var membersMap = {};
    chatsInfo.members.forEach(function(m) {
      var user = new User(m);
      members.push(user);
      membersMap[user.id] = user;
    });

    var chat = new Chat(new User(current_user), members, {}, function(message, callback) {
      myMessageSent = true;
      chatDAO.sendMessage(message, function(error, data) {
        if (callback) {
          callback(error, data);
        }
      });
    });

    if (chatsInfo.chats.length > 0) {
      lastChatId = chatsInfo.chats[chatsInfo.chats.length - 1].id;
      firstChatId = chatsInfo.chats[0].id; // handle case when no messages.
    }

    chat.setScrollTopEventCallback(function() {
      if (!isScrollingUp) {
        isScrollingUp = true;
        chatDAO.getChatsInfo({before_id: firstChatId, limit: 10}, function(ci) {
          if (ci.chats.length > 0) {
            firstChatId = ci.chats[0].id; // move this to a function
          }
          var messages = getMessagesFromChatInfo(ci);
          chat.addMessagesToTop(messages);
          isScrollingUp = false;
        });
      }
    });
    chat.addMessages(getMessagesFromChatInfo(chatsInfo));
    $('.js_upload_form').on("ajax:remotipartComplete", function(e, data) {
      var c = JSON.parse(data.responseText).chat;
      var msg = new Message(c, membersMap[c.user.id]);
      chat.addMessage(msg);
    });

    setInterval(function() {
      fetchLattestMessages(lastChatId);
    }, 5000);

    function getMessagesFromChatInfo(chatsInfo, excludeMyMessages) {
      var messages = [];
      chatsInfo.chats.forEach(function(chat) {
        if (!(excludeMyMessages && chat.user.id == current_user.id)) {
          var message = new Message(chat, membersMap[chat.user.id]);
          messages.push(message);
        } // TODO this will not work if multiple windows are open FIX
      });
      return messages;
    }

    function getUsersFromChatInfo(chatsInfo) {
      var members = [];
      chatsInfo.members.forEach(function(m) {
        var user = new User(m);
        members.push(user);
      });
      return members;
    }

    function fetchLattestMessages() {
      chatDAO.getChatsInfo({after_id: lastChatId}, function(ci) {
        if (ci.chats.length > 0) {
          lastChatId = ci.chats[ci.chats.length - 1].id; // move this to a function
        }
        var messages = getMessagesFromChatInfo(ci, true);
        chat.addMessages(messages);
        chat.addUsersToUserArea(getUsersFromChatInfo(ci));
        notifyMe(messages);
      });
    }

  });

  $(window).blur(function(){
    isWindowActive = false;
  });
  $(window).focus(function(){
    isWindowActive = true;
  });

  function notifyMe(messages) {
    var m = messages[0];
    if (Notification.permission !== "granted")
      Notification.requestPermission();
    else {
      var notification = new Notification('New chat message', {
        icon: m.user.picture,
        body: m.text,
      });

      notification.onclick = function () {
        window.focus(); this.cancel();
        //window.open("http://stackoverflow.com/a/13328397/1269037");
      };

    }

  }
}
document.addEventListener('DOMContentLoaded', function () {
  if (!Notification) {
    alert('Desktop notifications not available in your browser. Try Chromium.');
    return;
  }

  if (Notification.permission !== "granted")
    Notification.requestPermission();
});

<commit_msg>notification only on inactive window<commit_after>function chatController(postId) {
  if (!Notification) {
    alert('Desktop notifications not available in your browser. Try Chromium.');
    return;
  }
  if (Notification.permission !== "granted") {
    Notification.requestPermission().then(function(permission) {

    });;
  }
  var chatDAO = new ChatDAO(postId);
  var lastChatId;
  var firstChatId;
  var isScrollingUp;
  var isWindowActive = true;
  $(window).blur(function(){
    isWindowActive = false;
  });
  $(window).focus(function(){
    isWindowActive = true;
  });
  chatDAO.getChatsInfo({limit: 30}, function(chatsInfo) {
    var members = [];
    var membersMap = {};
    chatsInfo.members.forEach(function(m) {
      var user = new User(m);
      members.push(user);
      membersMap[user.id] = user;
    });

    var chat = new Chat(new User(current_user), members, {}, function(message, callback) {
      myMessageSent = true;
      chatDAO.sendMessage(message, function(error, data) {
        if (callback) {
          callback(error, data);
        }
      });
    });

    if (chatsInfo.chats.length > 0) {
      lastChatId = chatsInfo.chats[chatsInfo.chats.length - 1].id;
      firstChatId = chatsInfo.chats[0].id; // handle case when no messages.
    }

    chat.setScrollTopEventCallback(function() {
      if (!isScrollingUp) {
        isScrollingUp = true;
        chatDAO.getChatsInfo({before_id: firstChatId, limit: 10}, function(ci) {
          if (ci.chats.length > 0) {
            firstChatId = ci.chats[0].id; // move this to a function
          }
          var messages = getMessagesFromChatInfo(ci);
          chat.addMessagesToTop(messages);
          isScrollingUp = false;
        });
      }
    });
    chat.addMessages(getMessagesFromChatInfo(chatsInfo));
    $('.js_upload_form').on("ajax:remotipartComplete", function(e, data) {
      var c = JSON.parse(data.responseText).chat;
      var msg = new Message(c, membersMap[c.user.id]);
      chat.addMessage(msg);
    });

    setInterval(function() {
      fetchLattestMessages(lastChatId);
    }, 5000);

    function getMessagesFromChatInfo(chatsInfo, excludeMyMessages) {
      var messages = [];
      chatsInfo.chats.forEach(function(chat) {
        if (!(excludeMyMessages && chat.user.id == current_user.id)) {
          var message = new Message(chat, membersMap[chat.user.id]);
          messages.push(message);
        } // TODO this will not work if multiple windows are open FIX
      });
      return messages;
    }

    function getUsersFromChatInfo(chatsInfo) {
      var members = [];
      chatsInfo.members.forEach(function(m) {
        var user = new User(m);
        members.push(user);
      });
      return members;
    }

    function fetchLattestMessages() {
      chatDAO.getChatsInfo({after_id: lastChatId}, function(ci) {
        if (ci.chats.length > 0) {
          lastChatId = ci.chats[ci.chats.length - 1].id; // move this to a function
        }
        var messages = getMessagesFromChatInfo(ci, true);
        chat.addMessages(messages);
        chat.addUsersToUserArea(getUsersFromChatInfo(ci));
        desktopNotification(messages);
      });
    }

  });

  function desktopNotification(messages) {
    if (!isWindowActive) {
      if (Notification.permission !== "granted") {
        Notification.requestPermission();
      } else {
        messages.forEach(function(message) {
          var notification = new Notification('New message from ' + message.user.name, {
            icon: message.user.picture,
            body: message.text
            //sound: path //TODO
          });

          notification.onclick = function () {
            window.focus();
            //window.open("http://stackoverflow.com/a/13328397/1269037");
          };
        });
      }
    }
  }

}

<|endoftext|>


<commit_before>'use strict';

// The name of your game, no spaces or special characters.
const name = 'Monogatari';

// The version of the cache, changing this will force everything to be cached
// again.
const version = '0.1.0';

const files = [

	'/',

	// General Files
	'manifest.json',

	// Engine Files
	'engine/core/monogatari.css',
	'engine/core/monogatari.js',

	// HTML Files
	'index.html',

	// Style Sheets
	'style/main.css',

	// JavaScript Files
	'js/options.js',
	'js/storage.js',
	'js/script.js',
	'js/main.js',

	// App Images
	'favicon.ico',
	'assets/icons/icon_48x48.png',
	'assets/icons/icon_60x60.png',
	'assets/icons/icon_70x70.png',
	'assets/icons/icon_76x76.png',
	'assets/icons/icon_96x96.png',
	'assets/icons/icon_120x120.png',
	'assets/icons/icon_128x128.png',
	'assets/icons/icon_150x150.png',
	'assets/icons/icon_152x152.png',
	'assets/icons/icon_167x167.png',
	'assets/icons/icon_180x180.png',
	'assets/icons/icon_192x192.png',
	'assets/icons/icon_310x150.png',
	'assets/icons/icon_310x310.png',
	'assets/icons/icon_512x512.png'
];

self.addEventListener ('install', (event) => {
	self.skipWaiting ();
	event.waitUntil (
		caches.open (`${name}-v${version}`).then ((cache) => {
			return cache.addAll (files);
		})
	);
});

self.addEventListener ('activate', (event) => {
	event.waitUntil (
		caches.keys ().then ((keyList) => {
			return Promise.all (keyList.map ((key) => {
				if (key !== `${name}-v${version}`) {
					return caches.delete (key);
				}
			}));
		})
	);
	return self.clients.claim ();
});

self.addEventListener ('fetch', (event) => {

	if (event.request.method !== 'GET') {
		return;
	}

	event.respondWith (
		caches.match (event.request).then ((cached) => {
			function fetchedFromNetwork (response) {
				const cacheCopy = response.clone ();

				caches.open (`${name}-v${version}`).then (function add (cache) {
					cache.put (event.request, cacheCopy);
				});
				return response;
			}

			function unableToResolve () {
				return new Response (`
					<!DOCTYPE html><title>Bad Request</title><meta charset=UTF-8><meta content="width=device-width,initial-scale=1"name=viewport>

Service Unavailable

Sorry, the server is currently unavailable or under mantainance, try again later.

				`, {
					status: 503,
					statusText: 'Service Unavailable',
					headers: new Headers ({
						'Content-Type': 'text/html'
					})
				});
			}

			const networked = fetch (event.request)
				.then (fetchedFromNetwork, unableToResolve)
				.catch (unableToResolve);

			return cached || networked;
		})
	);
});<commit_msg>Fix typo<commit_after>'use strict';

// The name of your game, no spaces or special characters.
const name = 'Monogatari';

// The version of the cache, changing this will force everything to be cached
// again.
const version = '0.1.0';

const files = [

	'/',

	// General Files
	'manifest.json',

	// Engine Files
	'engine/core/monogatari.css',
	'engine/core/monogatari.js',

	// HTML Files
	'index.html',

	// Style Sheets
	'style/main.css',

	// JavaScript Files
	'js/options.js',
	'js/storage.js',
	'js/script.js',
	'js/main.js',

	// App Images
	'favicon.ico',
	'assets/icons/icon_48x48.png',
	'assets/icons/icon_60x60.png',
	'assets/icons/icon_70x70.png',
	'assets/icons/icon_76x76.png',
	'assets/icons/icon_96x96.png',
	'assets/icons/icon_120x120.png',
	'assets/icons/icon_128x128.png',
	'assets/icons/icon_150x150.png',
	'assets/icons/icon_152x152.png',
	'assets/icons/icon_167x167.png',
	'assets/icons/icon_180x180.png',
	'assets/icons/icon_192x192.png',
	'assets/icons/icon_310x150.png',
	'assets/icons/icon_310x310.png',
	'assets/icons/icon_512x512.png'
];

self.addEventListener ('install', (event) => {
	self.skipWaiting ();
	event.waitUntil (
		caches.open (`${name}-v${version}`).then ((cache) => {
			return cache.addAll (files);
		})
	);
});

self.addEventListener ('activate', (event) => {
	event.waitUntil (
		caches.keys ().then ((keyList) => {
			return Promise.all (keyList.map ((key) => {
				if (key !== `${name}-v${version}`) {
					return caches.delete (key);
				}
			}));
		})
	);
	return self.clients.claim ();
});

self.addEventListener ('fetch', (event) => {

	if (event.request.method !== 'GET') {
		return;
	}

	event.respondWith (
		caches.match (event.request).then ((cached) => {
			function fetchedFromNetwork (response) {
				const cacheCopy = response.clone ();

				caches.open (`${name}-v${version}`).then (function add (cache) {
					cache.put (event.request, cacheCopy);
				});
				return response;
			}

			function unableToResolve () {
				return new Response (`
					<!DOCTYPE html><title>Bad Request</title><meta charset=UTF-8><meta content="width=device-width,initial-scale=1"name=viewport>

Service Unavailable

Sorry, the server is currently unavailable or under maintenance, try again later.

				`, {
					status: 503,
					statusText: 'Service Unavailable',
					headers: new Headers ({
						'Content-Type': 'text/html'
					})
				});
			}

			const networked = fetch (event.request)
				.then (fetchedFromNetwork, unableToResolve)
				.catch (unableToResolve);

			return cached || networked;
		})
	);
});<|endoftext|>


<commit_before>var path = require('path'),
    webpack = require('webpack'),
    HtmlWebpackPlugin = require('html-webpack-plugin')

var DIST_DIR   = path.join(__dirname, 'dist/client'),
    SRC_DIR = path.join(__dirname, 'src/client')

module.exports = {
  context: SRC_DIR,

  entry: ['./index'],

  output: {
    path:   DIST_DIR,
    publicPath: "/",
    filename: 'bundle.js'
  },

  plugins: [
    new webpack.EnvironmentPlugin(),
    new HtmlWebpackPlugin({
      template: 'index.html',
      inject: 'body',
      filename: 'index.html'
    })
  ],

  module: {

    rules: [
      {
        test:  /\.jsx?$/,
        exclude: /node_modules/,
        use:  ['babel-loader', 'eslint-loader']
			},
      {
        test:  /\.css$/,
        exclude: /node_modules/,
        use: [
          {
            loader: 'style-loader',
          },
          {
            loader: 'css-loader',
            options: {
              modules: true,
              localIdentName: '[name]---[local]---[hash:base64:5]'
            }
          }
        ]
      },
      {
        test:  /\.(png|jpg|ttf|eot)$/,
        exclude: /node_modules/,
        use: [
          {
            loader: 'url-loader',
            options: {limit: 10000}
          }
        ]
      }
    ]
  },

  resolve: {
    modules: ['node_modules', 'vendor'],
    extensions: ['.js', '.json', '.css']
  }

}
<commit_msg>put name and hash in bundle<commit_after>var path = require('path'),
    webpack = require('webpack'),
    HtmlWebpackPlugin = require('html-webpack-plugin')

var DIST_DIR   = path.join(__dirname, 'dist/client'),
    SRC_DIR = path.join(__dirname, 'src/client')

module.exports = {
  context: SRC_DIR,

  entry: ['./index'],

  output: {
    path:   DIST_DIR,
    publicPath: "/",
    filename: '[name]-[hash].js'
  },

  plugins: [
    new webpack.EnvironmentPlugin(),
    new HtmlWebpackPlugin({
      template: 'index.html',
      inject: 'body',
      filename: 'index.html'
    })
  ],

  module: {

    rules: [
      {
        test:  /\.jsx?$/,
        exclude: /node_modules/,
        use:  ['babel-loader', 'eslint-loader']
			},
      {
        test:  /\.css$/,
        exclude: /node_modules/,
        use: [
          {
            loader: 'style-loader',
          },
          {
            loader: 'css-loader',
            options: {
              modules: true,
              localIdentName: '[name]---[local]---[hash:base64:5]'
            }
          }
        ]
      },
      {
        test:  /\.(png|jpg|ttf|eot)$/,
        exclude: /node_modules/,
        use: [
          {
            loader: 'url-loader',
            options: {limit: 10000}
          }
        ]
      }
    ]
  },

  resolve: {
    modules: ['node_modules', 'vendor'],
    extensions: ['.js', '.json', '.css']
  }

}
<|endoftext|>


<commit_before>const mat4 = require('gl-mat4')
const bunny = require('bunny')
const fit = require('canvas-fit')
const normals = require('angle-normals')

const canvas = document.body.appendChild(document.createElement('canvas'))
const regl = require('../regl')(canvas)
const camera = require('canvas-orbit-camera')(canvas)
window.addEventListener('resize', fit(canvas), false)

const cube = regl({
  frag: `
    precision mediump float;
    varying vec3 vnormal;
    void main () {
      gl_FragColor = vec4(abs(vnormal), 1.0);
    }`,
  vert: `
    precision mediump float;
    uniform mat4 proj;
    uniform mat4 model;
    uniform mat4 view;
    attribute vec3 position;
    attribute vec3 normal;
    varying vec3 vnormal;
    void main () {
      vnormal = normal;
      gl_Position = proj * view * model * vec4(position, 1.0);
    }`,
  attributes: {
    position: regl.buffer(bunny.positions),
    normal: regl.buffer(normals(bunny.cells, bunny.positions))
  },
  elements: regl.elements(bunny.cells),
  uniforms: {
    proj: mat4.perspective([], Math.PI / 2, window.innerWidth / window.innerHeight, 0.01, 1000),
    model: mat4.identity([]),
    view: regl.prop('view')
  }
})

regl.frame(function (props, count) {
  regl.clear({
    color: [0, 0, 0, 1]
  })
  camera.tick()
  cube({
    view: camera.view()
  })
})
<commit_msg>update camera example<commit_after>const mat4 = require('gl-mat4')
const bunny = require('bunny')
const fit = require('canvas-fit')
const normals = require('angle-normals')

const canvas = document.body.appendChild(document.createElement('canvas'))
const regl = require('../regl')(canvas)
const camera = require('canvas-orbit-camera')(canvas)
window.addEventListener('resize', fit(canvas), false)

const cube = regl({
  frag: `
    precision mediump float;
    varying vec3 vnormal;
    void main () {
      gl_FragColor = vec4(abs(vnormal), 1.0);
    }`,
  vert: `
    precision mediump float;
    uniform mat4 proj;
    uniform mat4 model;
    uniform mat4 view;
    attribute vec3 position;
    attribute vec3 normal;
    varying vec3 vnormal;
    void main () {
      vnormal = normal;
      gl_Position = proj * view * model * vec4(position, 1.0);
    }`,
  attributes: {
    position: bunny.positions,
    normal: normals(bunny.cells, bunny.positions)
  },
  elements: bunny.cells,
  uniforms: {
    proj: ({viewportWidth, viewportHeight}) =>
      mat4.perspective([],
        Math.PI / 2,
        viewportWidth / viewportHeight,
        0.01,
        1000),
    model: mat4.identity([]),
    view: () => camera.view()
  }
})

regl.frame(function (props, count) {
  regl.clear({
    color: [0, 0, 0, 1]
  })
  camera.tick()
  cube()
})
<|endoftext|>


<commit_before>'use strict'

import http from 'http'
import querystring from 'query-string'
import _ from 'lodash'

export class ProgrammableJsonServer {
	constructor({port}) {
		this._server = http.createServer(this._handler.bind(this))
		this._port = port
		this.reset()
	}

	start() {
		this._server.listen(this._port, '127.0.0.1')
	}

	stop() {
		this._server.close()
	}

	reset() {
		this._rules = []
	}

	addRule({resource, params = {}, headers = {}, cookies = {}, delay = 0, responseText}) {
		this._rules.push({resource, params, headers, cookies, delay, responseText})
	}

	_handler(req, res) {
		const headers = req.headers
		const query = querystring.extract(req.url)
		const resource = (query.length > 0) ? req.url.substr(0, req.url.length - query.length - 1) : req.url
		const params = querystring.parse(query)

		const cookieValue = headers['cookie'] || ''
		const cookieValues = cookieValue.split('; ')
		const cookies = _(cookieValues).map((value) => {
			return value.split('=')
		}).fromPairs().value()

		const rule = _.find(this._rules, (rule) => {
			return (rule.resource === resource) && _.isEqual(rule.params, params) && _.matches(rule.cookies)(cookies) && _.matches(rule.headers)(headers)
		})

		if (rule) {
			_.delay(() => {
				res.writeHead(200)
				res.end(rule.responseText)
			}, rule.delay)
		} else {
			res.writeHead(404)
			res.end()
		}
	}
}
<commit_msg>Code beautification<commit_after>import http from 'http'
import querystring from 'query-string'
import _ from 'lodash'

export class ProgrammableJsonServer {
	constructor({port}) {
		this._server = http.createServer(this._handler.bind(this))
		this._port = port
		this.reset()
	}

	start() {
		this._server.listen(this._port, '127.0.0.1')
	}

	stop() {
		this._server.close()
	}

	reset() {
		this._rules = []
	}

	addRule({resource, params = {}, headers = {}, cookies = {}, delay = 0, responseText}) {
		this._rules.push({resource, params, headers, cookies, delay, responseText})
	}

	_handler(req, res) {
		const headers = req.headers
		const query = querystring.extract(req.url)
		const resource = (query.length > 0) ? req.url.substr(0, req.url.length - query.length - 1) : req.url
		const params = querystring.parse(query)

		const cookieValue = headers['cookie'] || ''
		const cookieValues = cookieValue.split('; ')
		const cookies = _(cookieValues)
			.map(value => value.split('='))
			.fromPairs()
			.value()

		const rule = _.find(this._rules, (rule) => {
			return (rule.resource === resource) && _.isEqual(rule.params, params) && _.matches(rule.cookies)(cookies) && _.matches(rule.headers)(headers)
		})

		if (rule) {
			_.delay(() => {
				res.writeHead(200)
				res.end(rule.responseText)
			}, rule.delay)
		} else {
			res.writeHead(404)
			res.end()
		}
	}
}
<|endoftext|>


<commit_before>var request = require("request");
var intents = ['EarthIntent',
               'MarsIntent',
               'GirlfriendIntent',
               'SpaceIntent',
               'OrbitIntent',
               'StratosphereIntent',
               'SunIntent',
               'FalconIntent'];

exports.handler = function(event, context) { eventHandler(event, context); };

function eventHandler(event, context) {
  try { if (event.request.type === "LaunchRequest") {
          welcomeOnBoard(function callback(speechResponse) {
            context.succeed(buildResponse(event.session.attributes, speechResponse));
          });
        } else if (event.request.type === "IntentRequest") {
            sortIntents(event.request, function callback(speechResponse) {
              context.succeed(buildResponse(event.session.attributes, speechResponse));
            });
        }
  } catch (e) {
    context.fail("Exception: " + e);
  }
}

function welcomeOnBoard(callback) {
  callback(buildSpeechResponse("welcome aboard", "where to captain?", false));
}

function sortIntents(intentRequest, callback) {
    var intentName = intentRequest.intent.name;
    if (intentName == 'RandomIntent') {
      intentName = intents[Math.floor(Math.random() * intents.length)];
    }
    if (intentName == 'EarthIntent') {
      callFirebase('earth', callback);
    } else if (intentName == 'MarsIntent') {
      callFirebase('mars', callback);
    } else if (intentName == 'GirlfriendIntent') {
      callFirebase('girlfriend', callback);
    } else if (intentName == 'SpaceIntent') {
      callFirebase('space', callback);
    } else if (intentName == 'OrbitIntent') {
      callFirebase('orbit', callback);
    } else if (intentName == 'StratosphereIntent') {
      callFirebase('stratosphere', callback);
    } else if (intentName == 'SunIntent') {
      callFirebase('sun', callback);
    } else if (intentName == 'FalconIntent') {
      callFirebase('falcon', callback);
    } else if (intentName == 'AddMonolithIntent') {
      callFirebase('addMonolith', callback);
    } else if (intentName == 'RemoveMonolithIntent') {
      callFirebase('removeMonolith', callback);
    } else if (intentName == 'AddRainIntent') {
      callFirebase('addRain', callback);
    } else if (intentName == 'StopRainIntent') {
      callFirebase('stopRain', callback);
    } else if (intentName == 'AMAZON.HelpIntent') {
      helpUser(callback);
    } else {
      throw "Invalid intent";
    }
}

function helpUser(callback) {
  callback(buildSpeechResponse("You can go to Mars, Earth or even to the depths of the universe", "Where would you like to go?", true))
};

function callFirebase(planet, callback) {
  var url = 'https://fcm.googleapis.com/fcm/send';
  var serverKey = "key=AAAAaI2ZfFw:APA91bGqDh70rNfC8Gtwdxhut5sKhG7td0okEetwnhjWtzvTSC4jJIOReD2nEXkpT4OqMIciJptTxk7Du8MJmvrcW7jTKhiAh7XJYq2kBG2wIQOiwUerx014rpk7nt1JknAS-jdpUJxB";
  var clientToken = "dHfPorgxbLU:APA91bEyxYwDE3QugzQ9ASk-qQMk4zOxJ3auHc3_aedd1GvYX2ObTpCgUqWmkvsy9OVqTEvv2paUbIBs8SoaaV5e6CoIWWnb6Dkqj3qWQ100Ih_0SbaVNMK2w4qTcNBXUU_BqlHNkNRt";
  var options = {
    url: url,
    headers: {
      'Authorization': serverKey,
      'Content-Type': 'application/json'
    },
    json: {"to": clientToken,"priority":"high","notification":{"title": planet}}
  };
  request.post(options, function(error, response, body) {
    if(body.success == 1) {
      callback(buildSpeechResponse("this is " + planet, "", true));
    } else {
      callback(buildSpeechResponse("lost in space above all drifting", "", true));
    }
  });
}

function buildSpeechResponse(output, repromptText, shouldEndSession) {
    return {
        outputSpeech: {
            type: "PlainText",
            text: output
        },
        reprompt: {
            outputSpeech: {
                type: "PlainText",
                text: repromptText
            }
        },
        shouldEndSession: shouldEndSession
    };
}

function buildResponse(sessionAttributes, speechResponse) {
    return {
        version: "1.0",
        sessionAttributes: sessionAttributes,
        response: speechResponse
    };
}
<commit_msg>corrected with ruan refactor for Alexa code<commit_after>var request = require("request");
var intents = ['EarthIntent',
               'MarsIntent',
               'GirlfriendIntent',
               'SpaceIntent',
               'OrbitIntent',
               'StratosphereIntent',
               'SunIntent',
               'FalconIntent',
               ];

exports.handler = function(event, context) { eventHandler(event, context); };

function eventHandler(event, context) {
  try { if (event.request.type === "LaunchRequest") {
          welcomeOnBoard(function callback(speechResponse) {
            context.succeed(buildResponse(event.session.attributes, speechResponse));
          });
        } else if (event.request.type === "IntentRequest") {
            sortIntents(event.request, function callback(speechResponse) {
              context.succeed(buildResponse(event.session.attributes, speechResponse));
            });
        }
  } catch (e) {
    context.fail("Exception: " + e);
  }
}

function welcomeOnBoard(callback) {
  callback(buildSpeechResponse("welcome aboard", "where to captain?", false));
}

function sortIntents(intentRequest, callback) {
  var intentName = intentRequest.intent.name;
  var intentsMapping = {"EarthIntent": "earth",
                       "MarsIntent": "mars",
                       "GirlfriendIntent": "girlfriend",
                       "SpaceIntent": "space",
                       "OrbitIntent": "orbit",
                       "StratosphereIntent": "stratosphere",
                       "SunIntent": "sun",
                       "FalconIntent": "falcon",
                       "AddMonolithIntent": "addMonolith",
                       "RemoveMonolithIntent": "removeMonolith",
                       "AddRainIntent": "addRain",
                       "StopRainIntent": "stopRain"
                      };

  if (intentName == 'AMAZON.HelpIntent') {
    helpUser(callback);
  } else if (intentName == 'RandomIntent') {
    intentName = intents[Math.floor(Math.random() * intents.length)];
  } else if (intentName in intentsMapping) {
    callFirebase(intentsMapping[intentName], callback);
  } else {
    throw "Invalid intent";
  }
}

function helpUser(callback) {
  callback(buildSpeechResponse("You can go to Mars, Earth or even to the depths of the universe", "Where would you like to go?", true))
};

function callFirebase(planet, callback) {
  var url = 'https://fcm.googleapis.com/fcm/send';
  var serverKey = "key=AAAAaI2ZfFw:APA91bGqDh70rNfC8Gtwdxhut5sKhG7td0okEetwnhjWtzvTSC4jJIOReD2nEXkpT4OqMIciJptTxk7Du8MJmvrcW7jTKhiAh7XJYq2kBG2wIQOiwUerx014rpk7nt1JknAS-jdpUJxB";
  var clientToken = "dHfPorgxbLU:APA91bEyxYwDE3QugzQ9ASk-qQMk4zOxJ3auHc3_aedd1GvYX2ObTpCgUqWmkvsy9OVqTEvv2paUbIBs8SoaaV5e6CoIWWnb6Dkqj3qWQ100Ih_0SbaVNMK2w4qTcNBXUU_BqlHNkNRt";
  var options = {
    url: url,
    headers: {
      'Authorization': serverKey,
      'Content-Type': 'application/json'
    },
    json: {"to": clientToken,"priority":"high","notification":{"title": planet}}
  };
  request.post(options, function(error, response, body) {
    if(body.success == 1) {
      callback(buildSpeechResponse("this is " + planet, "", true));
    } else {
      callback(buildSpeechResponse("lost in space above all drifting", "", true));
    }
  });
}

function buildSpeechResponse(output, repromptText, shouldEndSession) {
    return {
        outputSpeech: {
            type: "PlainText",
            text: output
        },
        reprompt: {
            outputSpeech: {
                type: "PlainText",
                text: repromptText
            }
        },
        shouldEndSession: shouldEndSession
    };
}

function buildResponse(sessionAttributes, speechResponse) {
    return {
        version: "1.0",
        sessionAttributes: sessionAttributes,
        response: speechResponse
    };
}
<|endoftext|>


<commit_before>import { animate, stop } from "liquid-fire";

export default function (oldView, insertNewView) {

  // Stop any currently running animation on oldView
  stop(oldView);

  // Fade out the old view
  return animate(oldView, { opacity: 0 })
  // Render the new view
    .then(insertNewView)
  // And fade it in, from opacity 0 to 1
    .then(function(newView){
      return animate(newView, { opacity: [1, 0]});
    });
}
<commit_msg>Update transition blueprint<commit_after>import { animate, stop } from "liquid-fire";

// arguments are passed directly from use statements in transition rules, e.g.
// this.use('myTransition', arg1, arg2)

export default function (/* arg1, arg2 */) {
  // Stop any currently running animation on oldElement
  stop(this.oldElement);

  // Fade out the old element
  return animate(this.oldElement, { opacity: 0 })
    // And then fade in the new element, from opacity 0 to 1
    .then( () =>
      animate(this.newElement, { opacity: [1, 0] })
    );
}
<|endoftext|>


<commit_before>// FIXME: Tell people that this is a manifest file, real code should go into discrete files
// FIXME: Tell people how Sprockets and CoffeeScript works
//
<% unless options[:skip_javascript] -%>
//= require <%= options[:javascript] %>
//= require <%= options[:javascript] %>_ujs
<% end -%>
//= require_tree .
//= require tiny_mce/tiny_mce.js
<commit_msg>Screwing with tinyMCE, doesn't work yet<commit_after>// FIXME: Tell people that this is a manifest file, real code should go into discrete files
// FIXME: Tell people how Sprockets and CoffeeScript works
//
<% unless options[:skip_javascript] -%>
//= require <%= options[:javascript] %>
//= require <%= options[:javascript] %>_ujs
<% end -%>
//= require_tree .
<|endoftext|>


<commit_before>var WebSocketServer = require('ws').Server
var messageProcessor = require('./messageProcessor.js');
var messageTransmitter = require('./messageTransmitter.js');
var datamodel = require('./datamodel.js');
var port = 8888;
var wss = new WebSocketServer({port: port});
console.log("server startet on port " +  port);

module.exports = {
  connect: function (datamodel) {

    var connectedClients = datamodel.getConnectedClients();
    wss.on('connection', function(ws) {
      console.log("client connected");
        connectedClients.push({
            webSocketConnection: ws,
            data: {},
            id: connectedClients.length
        });

        ws.on('message', function incoming(message) {

            try {
              var jsonMessage = JSON.parse(message);

              console.log(datamodel.displayTime() +' received: %s, Message: %s', jsonMessage.eventType, message + "\n");
            } catch (e) {
              console.log("not a valid json message: " + e);
              return;
            }

            var connectedClient = getClientByWsConnection(ws);
            if (jsonMessage.eventType === "connect") {
              messageProcessor.processConnect(connectedClient, jsonMessage);
              messageTransmitter.transmitClients(connectedClients);
            }
            else if (jsonMessage.eventType === "speed") {
              messageProcessor.processSpeed(connectedClient, jsonMessage);
              messageTransmitter.transmitSpeed(connectedClient, datamodel);
            }
            else if (jsonMessage.eventType === "selectRobo") {
              messageProcessor.processRoboSelected(connectedClient, jsonMessage, datamodel);
              messageTransmitter.transmitClients(connectedClients);
            }
            else if (jsonMessage.eventType === "deselectRobo") {
              messageProcessor.processRoboDeselect(connectedClient, datamodel);
              messageTransmitter.transmitClients(connectedClients);
            }
            else if (jsonMessage.eventType === "ready") {
              messageProcessor.processReady(connectedClient, jsonMessage, connectedClients);
              messageTransmitter.transmitClients(connectedClients);
            }
            else if (jsonMessage.eventType === "move") {
              messageTransmitter.transmitMove(connectedClient, jsonMessage, datamodel);
            }
            else if (jsonMessage.eventType === "leftTrack") {
              messageTransmitter.transmitLeftTrack(connectedClient, jsonMessage, datamodel);
            }else {
              ws.send(JSON.stringify({eventType: "error", data: { message: "unknownEventtype"}}));
            }
        });

        ws.on('close', function(errorcode) {
          var disconnectedClient = getClientByWsConnection(ws);
          if(disconnectedClient.data.type === "robo") {
            console.log("robo losing connection");
            if (disconnectedClient.data.controlledBy) {
	            var app = datamodel.getClientByName(disconnectedClient.data.controlledBy);
              if(app != null) {
  	            app.data.selectedRobo = null;
  	            app.data.ready = "waiting";
              }
	          }
          } else if(disconnectedClient.data.type === "app") {
            if(disconnectedClient.data.selectedRobo) {
              var robo = datamodel.getClientByName(disconnectedClient.data.selectedRobo.name);
              if(robo) {
                delete robo.data.controlledBy;
                robo.data.speed = 0;
              }
            }
          }
          connectedClients.splice(connectedClients.indexOf(disconnectedClient), 1);
          messageTransmitter.transmitClients(connectedClients);
        });

        function getClientByWsConnection(ws){

            for (i = 0; i <= connectedClients.length - 1; i++) {
                if (connectedClients[i].webSocketConnection === ws) {
                    return connectedClients[i];
                }
            }
            return null;
        }
    });
  }
};
<commit_msg>3. Versuch Speed vom Robo auf 0 zu setzen, wenn dessen App disconnected<commit_after>var WebSocketServer = require('ws').Server
var messageProcessor = require('./messageProcessor.js');
var messageTransmitter = require('./messageTransmitter.js');
var datamodel = require('./datamodel.js');
var port = 8888;
var wss = new WebSocketServer({port: port});
console.log("server startet on port " +  port);

module.exports = {
  connect: function (datamodel) {

    var connectedClients = datamodel.getConnectedClients();
    wss.on('connection', function(ws) {
      console.log("client connected");
        connectedClients.push({
            webSocketConnection: ws,
            data: {},
            id: connectedClients.length
        });

        ws.on('message', function incoming(message) {

            try {
              var jsonMessage = JSON.parse(message);

              console.log(datamodel.displayTime() +' received: %s, Message: %s', jsonMessage.eventType, message + "\n");
            } catch (e) {
              console.log("not a valid json message: " + e);
              return;
            }

            var connectedClient = getClientByWsConnection(ws);
            if (jsonMessage.eventType === "connect") {
              messageProcessor.processConnect(connectedClient, jsonMessage);
              messageTransmitter.transmitClients(connectedClients);
            }
            else if (jsonMessage.eventType === "speed") {
              messageProcessor.processSpeed(connectedClient, jsonMessage);
              messageTransmitter.transmitSpeed(connectedClient, datamodel);
            }
            else if (jsonMessage.eventType === "selectRobo") {
              messageProcessor.processRoboSelected(connectedClient, jsonMessage, datamodel);
              messageTransmitter.transmitClients(connectedClients);
            }
            else if (jsonMessage.eventType === "deselectRobo") {
              messageProcessor.processRoboDeselect(connectedClient, datamodel);
              messageTransmitter.transmitClients(connectedClients);
            }
            else if (jsonMessage.eventType === "ready") {
              messageProcessor.processReady(connectedClient, jsonMessage, connectedClients);
              messageTransmitter.transmitClients(connectedClients);
            }
            else if (jsonMessage.eventType === "move") {
              messageTransmitter.transmitMove(connectedClient, jsonMessage, datamodel);
            }
            else if (jsonMessage.eventType === "leftTrack") {
              messageTransmitter.transmitLeftTrack(connectedClient, jsonMessage, datamodel);
            }else {
              ws.send(JSON.stringify({eventType: "error", data: { message: "unknownEventtype"}}));
            }
        });

        ws.on('close', function(errorcode) {
          var disconnectedClient = getClientByWsConnection(ws);
          if(disconnectedClient.data.type === "robo") {
            console.log("robo losing connection");
            if (disconnectedClient.data.controlledBy) {
	            var app = datamodel.getClientByName(disconnectedClient.data.controlledBy);
              if(app != null) {
  	            app.data.selectedRobo = null;
  	            app.data.ready = "waiting";
              }
	          }
          } else if(disconnectedClient.data.type === "app") {
            if(disconnectedClient.data.selectedRobo) {
              var robo = datamodel.getClientByName(disconnectedClient.data.selectedRobo.name);
              if(robo) {
                delete robo.data.controlledBy;
                robo.data.speed = "0";
                var speedMessage = {
                  eventType: "move",
                  data: {
                    speed: "0"
                  }
                }
                console.log(datamodel.displayTime() + " Send to " + robo.name + JSON.stringify(speedMessage) + "\n");
                robo.webSocketConnection.send(JSON.stringify(speedMessage));
              }
            }
          }
          connectedClients.splice(connectedClients.indexOf(disconnectedClient), 1);
          messageTransmitter.transmitClients(connectedClients);
        });

        function getClientByWsConnection(ws){

            for (i = 0; i <= connectedClients.length - 1; i++) {
                if (connectedClients[i].webSocketConnection === ws) {
                    return connectedClients[i];
                }
            }
            return null;
        }
    });
  }
};
<|endoftext|>


<commit_before>module.exports = {
  afterInstall: function () {
    return this.addBowerPackageToProject('z-schema', '3.16.1')
      .then(() => {
        return this.addAddonsToProject({
          packages: [
            {name: 'ember-frost-core', target: '>=0.0.14 <2.0.0'},
            {name: 'ember-lodash', target: '>=0.0.6 <2.0.0'},
            {name: 'ember-prop-types', target: '^1.1.0'},
            {name: 'ember-redux', target: '^1.0.0'}
          ]
        })
      })
  },

  normalizeEntityName: function () {
    // this prevents an error when the entityName is
    // not specified (since that doesn't actually matter
    // to us
  }
}
<commit_msg>Add ember-browserify to blueprints<commit_after>module.exports = {
  afterInstall: function () {
    return this.addBowerPackageToProject('z-schema', '3.16.1')
      .then(() => {
        return this.addAddonsToProject({
          packages: [
            {name: 'ember-browserify', target: '^1.1.8'},
            {name: 'ember-frost-core', target: '>=0.0.14 <2.0.0'},
            {name: 'ember-lodash', target: '>=0.0.6 <2.0.0'},
            {name: 'ember-prop-types', target: '^1.1.0'},
            {name: 'ember-redux', target: '^1.0.0'}
          ]
        })
      })
  },

  normalizeEntityName: function () {
    // this prevents an error when the entityName is
    // not specified (since that doesn't actually matter
    // to us
  }
}
<|endoftext|>


<commit_before>const HTMLElement=(e=>{function t(){}return t.prototype=window.HTMLElement.prototype,t})();class DOMTokenList{constructor(e){const t=e=>/{(\w+|#)}/.test(e.textContent)&&(e.text=e.textContent).match(/[^{]+(?=})/g).map(t=>(this[t]||(this[t]=[])).push(e)),n=document.createNodeIterator(e,NodeFilter.SHOW_ELEMENT|NodeFilter.SHOW_TEXT,e=>e.attributes&&[].slice.call(e.attributes).map(t)||t(e),null);for(;n.nextNode(););}bind(e){Object.keys(this).map(e=>this[e].map(e=>e.textContent=e.text)&&e).map(t=>this[t].map(n=>n.textContent=n.textContent.split("{"+t+"}").join(e[t])))}}(e=>{function t(e){let t=new XMLHttpRequest;t.link=e,t.onload=n,t.open("GET",e.href),t.responseType="document",t.send()}function n(e){e=this.link;let t=this.response,n=e.nextChild,o=e.content=t.querySelector("template");for(let s of document.querySelectorAll(e.id))o&&l.call(s,o);for(let l of t.querySelectorAll("style,link,script"))s(e,l,n)}function s(e,t,n){let s=t.getAttribute("as"),l=document.createElement("script"==s?s:t.localName);["id","rel","href","src","textContent","as","defer","crossOrigin"].map(e=>t[e]&&e in l&&(l[e]=t[e])),"style"==s&&(l.rel="stylesheet"),"script"==s&&(l.src=l.href),e.parentNode.insertBefore(l,n)}function l(e){e=document.importNode(e,!0);let t;[].slice.call(e.attributes).map(e=>!this.attributes[e.name]&&this.setAttribute(e.name,e.value));for(let n of this.querySelectorAll("[slot]"))(t=(e.content||e).querySelector("slot[name="+n.getAttribute("slot")+"]"))&&t.parentNode.replaceChild(n,t);return this.innerHTML=e.innerHTML}new MutationObserver(e=>{for(let n of e)for(let e of n.addedNodes)/^p/.test(e.rel)&&/\-/.test(e.id)&&t(e),!!/\-/.test(e.localName)&&(link=document.querySelector("#"+e.localName))&&link.content&&l.call(e,link.content)&&customElements.upgrade(e)}).observe(document.documentElement,{childList:!0,subtree:!0}),[].slice.call(document.querySelectorAll('[rel^=pre][id~="-"]')).map(t)})();const Template=e=>{e.length&&(e=document.querySelector("template[name="+e+"]"));let t=e.innerHTML,n=e.nextSibling;return e.innerHTML="",e.bind=function(e){const s=document.createElement("section");for(let t of this.dependents||[])t.parentNode.removeChild(t);s.innerHTML=[].concat(e).reduce((e,n,s)=>{let l=t;"object"!=typeof n&&(n={self:n}),n["#"]=s;for(let t in n)l=l.split("{"+t+"}").join(n[t]);return e+l},"");for(let t of this.dependents=[].slice.call(s.childNodes))this.parentNode.insertBefore(t,n)}.bind(e),e};new class{constructor(){window.customElements=window.customElements||{},customElements.define=this.define.bind(this),customElements.upgrade=this.upgrade.bind(this)}define(e,t){this[e]=t,[].slice.call(document.getElementsByTagName(e)).map(this.upgrade,this)}upgrade(e){this[e.localName]&&Object.setPrototypeOf(e,this[e.localName].prototype).connectedCallback()}};const ParentNode=e=>class extends e{select(){return this.selectAll(...arguments)[0]}selectAll(e,...t){return e=[].concat(e),[].slice.call(this.querySelectorAll(t.reduce((t,n)=>t+n+e.shift(),e.shift())))}},EventTarget=e=>class extends e{on(e,t){this.addEventListener(e,this.renderable(t))}renderable(e){return t=>!1!==e.call(this,t)&&t.defaultPrevented||this.render()}},GlobalEventHandlers=e=>class extends e{onconnect(){this.templates=this.selectAll("template[name]").map(Template),this.tokens=new DOMTokenList(this),super.onconnect&&super.onconnect()}reflect(e){/^on/.test(e)&&e in HTMLElement.prototype&&this.on(e.substr(2),this[e])}register(e,t,n){for(let s of[].slice.call(e.attributes))/^on/.test(n=s.name)&&(t=(/{\s*(\w+)/.exec(e[n])||[])[1])&&(e[n]=this.renderable(this[t]))}},Custom=e=>class extends(ParentNode(EventTarget(GlobalEventHandlers(e)))){connectedCallback(){this.context={},super.initialize&&super.initialize(),Object.getOwnPropertyNames(e.prototype).map(this.reflect,this),this.onconnect(),this.render()}render(){for(let e of this.templates)e.bind(this[e.getAttribute("name")]);this.tokens.bind(this),[this].concat(this.selectAll("*")).map(this.register,this),super.onidle&&super.onidle()}},Element=e=>t=>customElements.define(e+"",Custom(t));<commit_msg>:muscle: bump ??? distribution dist/snuggsi.min.es.js<commit_after>const HTMLElement=(e=>{function t(){}return t.prototype=window.HTMLElement.prototype,t})();class DOMTokenList{constructor(e){const t=e=>/{(\w+|#)}/.test(e.textContent)&&(e.text=e.textContent).match(/[^{]+(?=})/g).map(t=>(this[t]||(this[t]=[])).push(e)),n=document.createNodeIterator(e,NodeFilter.SHOW_ELEMENT|NodeFilter.SHOW_TEXT,e=>e.attributes&&[].slice.call(e.attributes).map(t)||t(e),null);for(;n.nextNode(););}bind(e){Object.keys(this).map(e=>this[e].map(e=>e.textContent=e.text)&&e).map(t=>this[t].map(n=>n.textContent=n.textContent.split("{"+t+"}").join(e[t])))}}(e=>{function t(e){let t=new XMLHttpRequest;t.link=e,t.onload=n,t.open("GET",e.href),t.responseType="document",t.send()}function n(e){e=this.link;let t=this.response,n=e.nextChild,o=e.content=t.querySelector("template");for(let s of document.querySelectorAll(e.id))o&&l.call(s,o);for(let l of t.querySelectorAll("style,link,script"))s(e,l,n)}function s(e,t,n){let s=t.getAttribute("as"),l=document.createElement("script"==s?s:t.localName);["id","rel","href","src","textContent","as","defer","crossOrigin"].map(e=>t[e]&&e in l&&(l[e]=t[e])),"style"==s&&(l.rel="stylesheet"),"script"==s&&(l.src=l.href),e.parentNode.insertBefore(l,n)}function l(e){e=document.importNode(e,!0);let t;[].slice.call(e.attributes).map(e=>!this.attributes[e.name]&&this.setAttribute(e.name,e.value));for(let n of this.querySelectorAll("[slot]"))(t=(e.content||e).querySelector("slot[name="+n.getAttribute("slot")+"]"))&&t.parentNode.replaceChild(n,t);return this.innerHTML=e.innerHTML}new MutationObserver(e=>{for(let n of e)for(let e of n.addedNodes)/^p/.test(e.rel)&&/\-/.test(e.id)&&t(e),!!/\-/.test(e.localName)&&(link=document.querySelector("#"+e.localName))&&link.content&&l.call(e,link.content)&&customElements.upgrade(e)}).observe(document.documentElement,{childList:!0,subtree:!0}),[].slice.call(document.querySelectorAll('[rel^=pre][id~="-"]')).map(t)})();const Template=e=>{e.length&&(e=document.querySelector("template[name="+e+"]"));let t=e.innerHTML,n=e.nextSibling;return e.innerHTML="",e.bind=function(e){const s=document.createElement("section");for(let t of this.dependents||[])t.parentNode.removeChild(t);s.innerHTML=[].concat(e).reduce((e,n,s)=>{let l=t;"object"!=typeof n&&(n={self:n}),n["#"]=s;for(let t in n)l=l.split("{"+t+"}").join(n[t]);return e+l},"");for(let t of this.dependents=[].slice.call(s.childNodes))this.parentNode.insertBefore(t,n)}.bind(e),e};new class{constructor(){customElements=window.customElements||{},customElements.define=this.define.bind(this),customElements.upgrade=this.upgrade.bind(this)}define(e,t){this[e]=t,[].slice.call(document.getElementsByTagName(e)).map(this.upgrade,this)}upgrade(e){this[e.localName]&&Object.setPrototypeOf(e,this[e.localName].prototype).connectedCallback()}};const ParentNode=e=>class extends e{select(){return this.selectAll(...arguments)[0]}selectAll(e,...t){return e=[].concat(e),[].slice.call(this.querySelectorAll(t.reduce((t,n)=>t+n+e.shift(),e.shift())))}},EventTarget=e=>class extends e{on(e,t){this.addEventListener(e,this.renderable(t))}renderable(e){return t=>!1!==e.call(this,t)&&t.defaultPrevented||this.render()}},GlobalEventHandlers=e=>class extends e{onconnect(){this.templates=this.selectAll("template[name]").map(Template),this.tokens=new DOMTokenList(this),super.onconnect&&super.onconnect()}reflect(e){/^on/.test(e)&&e in HTMLElement.prototype&&this.on(e.substr(2),this[e])}register(e,t,n){for(let s of[].slice.call(e.attributes))/^on/.test(n=s.name)&&(t=(/{\s*(\w+)/.exec(e[n])||[])[1])&&(e[n]=this.renderable(this[t]))}},Custom=e=>class extends(ParentNode(EventTarget(GlobalEventHandlers(e)))){connectedCallback(){this.context={},super.initialize&&super.initialize(),Object.getOwnPropertyNames(e.prototype).map(this.reflect,this),this.onconnect(),this.render()}render(){for(let e of this.templates)e.bind(this[e.getAttribute("name")]);this.tokens.bind(this),[this].concat(this.selectAll("*")).map(this.register,this),super.onidle&&super.onidle()}},Element=e=>t=>customElements.define(e+"",Custom(t));<|endoftext|>


<commit_before>const nodeExternals = require('webpack-node-externals');

module.exports = {
    entry: './src/index.ts',
    resolve: {
        extensions: ['.ts', '.js', '.tsx', '.jsx'],
    },
    externals: [nodeExternals()],
    module: {
        loaders: [{
            test: /\.ts?$/,
            exclude: /node_modules/,
            loader: 'ts-loader',
        }]
    },
    target: 'node',
};
<commit_msg>rm unused exts<commit_after>const nodeExternals = require('webpack-node-externals');

module.exports = {
    entry: './src/index.ts',
    resolve: {
        extensions: ['.ts', '.js'],
    },
    externals: [nodeExternals()],
    module: {
        loaders: [{
            test: /\.ts?$/,
            exclude: /node_modules/,
            loader: 'ts-loader',
        }]
    },
    target: 'node',
};
<|endoftext|>