working on it ...

Filters

Explore Public Snippets

Sort by

Found 16 snippets matching: evented

    public by sTiLL-iLL @ SniPitz-KND  532556  3  8  21

    Ajax again?? Wrap it!! XHR Agent 4Ya

    XHR wrapper! object pooling and cueing!!! EveryOneZ dOing IT!
    
    var myXHR = {
           ESpec: function (wrap, evt) {
               return { xhrWrap: wrap, event: evt };
           },
           Agent: function(maxConnect) {
               var bCued = [], slf = this,
                   max = maxConnect || 3;
                   this.curCon = 0;
               function inCue() {
                   if (self.bCued < max) {
                       self.bCued++;
                       var itm = is.Readied.shift();
                       itm.evt.addEventListener(['EVENT_COMPLETE'], 
                         function (e) {
                             self.bCued--;
                             if (this.Readied.length !== 0) {
                               inCue();
                             }
                         });
                       itm.wrap.call(itm, args, itm.evt);
                    }
               }
               this.Readied = function (ESpec) {
                   bCued.push(ESpec);
                   inCue();
                   return ESpec.evt;
               };
            }
       };
    
                

    public by sTiLL-iLL @ SniPitz-KND  1804  0  7  17

    KuSTum DisPAtCHer Fo yer EvenTZ

    manage your evented objects.... yeah please do, thanks.
    //event delegation/management
    
      var EventPush = function(events) {
        
            var listeners = [];
            if (events) {
                for (var i = 0; i < events.length; i++) {
                    this[events[i]] = events[i];
                }
            }
            
            this.getListeners = function (title) {
                return listeners[title] || [];
            };
            
            this.on = function (name, mthd, hndlr) {
                function add(name) {
                    if (!listeners[name]) { listeners[name] = []; }
                    listeners[name].push({ method: mthd, handler: hndlr });
                }
                if (typeof(name) == 'object' && name.length) {
                    for(var i = 0; i < name.length; i++) {
                        add(name[i]);
                    }
                } 
                else {
                    add(name);
                }
                return this;
            };
            
            this.off = function (name, methd) {
                if (listeners[name]) {
                    for (var i = 0; i < listeners[name].length; i++) {
                        if (listeners[name][i].method == methd) {
                            listeners[name].splice(i, 1);
                        }
                    }
                }
                return this;
            };
            
            this.pushEvent = function (name, args) {
                if (listeners[name]) {
                	  for (var i = 0; i < listeners[name].length; i++) {
                		    var mthd = listeners[name][i].method;
                            mthd.apply(mthd, [args]);
                        }
                    }
                return this;
            };
            
            this.removeAll = function () {
                listeners = [];
                return this;
            };
            
            this.offForHandler = function (name, hndlr) {
                if (listeners[name]) {
                    for (var i = 0; i < listeners[name].length; i++) {
                        if (listeners[name][i].handler == hndlr) {
                            listeners[name].splice(i, 1);
                        }
                    }
                }
                return this;
            };
            
            return this;
        }

    external by Pablo Viral  23  0  1  0

    Evented ping-pong

    Evented ping-pong: pingpong-evented.js
    // golang version: https://code.google.com/p/go/source/browse/2013/advconc/pingpong/pingpong.go?repo=talks
    // js-csp version: https://github.com/ubolonton/js-csp/blob/master/examples/go/pingpong.js
    
    var EventEmitter = require('events').EventEmitter;
    
    var table = new EventEmitter();
    var players = ['ping', 'pong'];
    
    function player(name, table, ball) {
        setTimeout(function () {
            if (!table.emit) return console.log(name + ": table's gone");
            table.emit(name, table, ball = {
                "hits": ball.hits + 1
            });
            console.log(name + ' ' + ball.hits)
        }, 100)
    }
    
    players.forEach(function (name, nth, players) {
        table.on(players[nth], player.bind(null, players[players.length - nth - 1]))
    });
    
    table.on('end', function () {
        table.removeAllListeners();
        players.forEach(player)
    });
    
    table.emit('ping', table, {
        "hits": 0
    });
    
    setTimeout(table.emit.bind(table, 'end'), 1000)
    
    
    

    external by cleesmith  562  0  3  0

    Evented TCP server in 50 lines of ruby code

    Evented TCP server in 50 lines of ruby code: evented_tcp_server.md
    Evented TCP server using eventmachine.
    
    TCP server:
    
    ```
    require 'eventmachine'
    
    PORT = 4545
    puts "Listening on #{PORT}...\n"
    
    class Counter
      attr_accessor :total_data
    
      def initialize
        @total_data = 0
      end
    
      def total_data=(num)
        @total_data += num
      end
    end
    
    class EchoServer < EM::Connection
      def initialize(counter)
        @total = 0
        @total_data = 0
        @counter = counter
      end
    
      def receive_data(data)
        @total += 1
        @total_data += data.length
        @counter.total_data = data.length
        # puts "\ntotal=#{@total} \t #{data.length}\n"
        # send_data(data)
        # do some work, monkey with the data, kill some time:
        lines = data.split("\n")
        # puts "lines=#{lines.length}"
        lines.each do |line|
          fields = line.split("\t")
          # puts "\tfields=#{fields.length}"
          fields.each do |field|
            # puts "\t\tfield=#{field.length}"
          end
        end
      end
    end
    
    EventMachine.run do
      counter = Counter.new
      Signal.trap("INT")  { EventMachine.stop }
      Signal.trap("TERM") { EventMachine.stop }
      EventMachine.start_server("127.0.0.1", PORT, EchoServer, counter)
      EM.add_periodic_timer(30) { puts "counter=#{counter.inspect}" }
    end
    ```
    
    ***
    
    TCP client:
    
    ```
    require 'socket'
    start = Time.now
    begin
      if ARGV.empty?
        port = 4545
      else
        port = ARGV[0].to_i
      end
      client = TCPSocket.new('127.0.0.1', port)
      # puts "Socket::TCP_NODELAY=#{Socket::TCP_NODELAY}"
      client.setsockopt(Socket::IPPROTO_TCP, Socket::TCP_NODELAY, 1) # Nagle off
      # 420_000_000.times do |x| <<--- took about 40 minutes to process 128,100,000,000 of data (OS X)
      1_000_000.times do |x|
        # send 305 bytes:
        msg  = "Lorem \t ipsum \t dolor sit amet, consectetur adipiscing elit. Donec luctus enim mollis eros interdum egestas. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec vitae est pellentesque, suscipit nisl et, rutrum nulla. Nullam sed justo nisl. Donec rutrum velit odio, non sollicitudin lorem amet.\n"
        # msg += "Lorem \t ipsum \t dolor sit amet, consectetur adipiscing elit. Donec luctus enim mollis eros interdum egestas. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec vitae est pellentesque, suscipit nisl et, rutrum nulla. Nullam sed justo nisl. Donec rutrum velit odio, non sollicitudin lorem amet.\n"
        # msg += "Lorem \t ipsum \t dolor sit amet, consectetur adipiscing elit. Donec luctus enim mollis eros interdum egestas. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec vitae est pellentesque, suscipit nisl et, rutrum nulla. Nullam sed justo nisl. Donec rutrum velit odio, non sollicitudin lorem amet.\n"
        # msg += "Lorem \t ipsum \t dolor sit amet, consectetur adipiscing elit. Donec luctus enim mollis eros interdum egestas. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec vitae est pellentesque, suscipit nisl et, rutrum nulla. Nullam sed justo nisl. Donec rutrum velit odio, non sollicitudin lorem amet.\n"
        # puts "#{msg.length}\n"
        client.puts(msg)
        # ignore response:
        # resp = client.gets
        # puts "resp=#{resp}"
      end
    ensure
      client.close if client
      puts "elapsed: #{(Time.now - start)}"
    end
    ```
    
    Why ?
    Well, it's all the rage (or was), it's very fast, it doesn't use a lot of memory (hovered around 30K) compared to 
    what it's processing, and there's no worries about threading and forking and all those entail.
    
    Sure, you are not going to traipse off to the bonneville salt flats with this server and break any speed records, 
    but after trying all of the other options this seems to work the best for pushing data into a server for various 
    purposes.  It's amazing what 50 lines of ruby code, not counting eventmachine itself, and *nix can do.  Also,
    all of my testing was done with ruby MRI.
    
    ***
    fin
    
    

    external by krisleech  372  0  3  0

    Distributed evented processing

    Distributed evented processing: gistfile1.txt
    -input1->
    -event4+5-> [Process1] -event1-> [Process2] -event2-> [process4] -event4->
                           -event1-> [Process3] -event3-> [process5] -event5->
    
    Each process could be a pool of processes. Each process can use the Actor model.
    
    Events need to include a uuid so inputs and results (event4 + event5) can be matched up.
    
    Event1 is consumed by two different processes break up different processing of input.
    
    Process1 will consume both events 4 and 5, combining to get the final result.
    
    

    external by itsWill  252  0  3  0

    Evented Reactor Part for a HTTP Server

    Evented Reactor Part for a HTTP Server: gistfile1.txt
    # BASED ON WORKING WITH TCP/IP-SOCKETS BY JESSEE STORIMER
    require 'socket'
    
    require 'omers/events_emitter'
    require 'omers/stream'
    require 'omers/server'
    
    
    module OMERS
      class Reactor
        include EventsEmitter
    
        attr_accessor :streams, :socket
    
        def initialize
          @streams = []
        end
    
        def listen(host, port)
          @socket = TCPServer.new(host, port)
          server = Server.new(@socket)
    
          register(server)
    
          server.on(:accept) do |client|
            register(client)
          end
    
          server
        end
    
        def register(stream)
          streams << stream
    
          stream.on(:close) do
            streams.delete(stream)
          end
        end
    
        def start
          loop {tick}
        end
    
        def tick
          begin
            readable, writable, _ = IO.select(streams, streams)
    
            readable.each { |stream| stream.handle_read  }
            writable.each { |stream| stream.handle_write }
          rescue Errno::EBADF
            # when the server is close on shutdown select will raise Errno::EBADF
          rescue => ex
            raise ex
          end
        end
    
        def shutdown
          @streams.each do |s|
            s.close
          end
        end
      end
    end
    
    

    external by Ron Williams  128  1  2  0

    Force polling on for the evented file update checker

    Force polling on for the evented file update checker: force_polling.rb
    module ActiveSupport
      class EventedFileUpdateChecker
        private
          def boot!
            Listen.to(*@dtw, force_polling: true,&method(:changed)).start
          end
      end
    end
    
    

    external by gnud  162  0  2  0

    Evented parallel task execution (todo: will add parallel for loop)

    Evented parallel task execution (todo: will add parallel for loop): tasks.js
    var EventEmitter = require('events');
    
    function task1() {
      var taskName = 'task1';
      console.log(taskName, this.tasksResult);
      var result = 1;
      ee.emit('task-done', { 
        'action': taskName,
        'result': result    
      });
    }
    
    function task2() {
      var taskName = 'task2';
      console.log(taskName, this.tasksResult);
      var result = 2;
      ee.emit('task-done', { 
        'action': taskName,
        'result': result    
      });
    }
    
    function task3() {
      var taskName = 'task3';
      console.log(taskName, this.tasksResult);
      var result = 3;
      ee.emit('task-done', { 
        'action': taskName,
        'result': result    
      });
    }
    
    function task4() {
      var taskName = 'task4';
      console.log(taskName, this.tasksResult);
      var result = 4;
      ee.emit('task-done', { 
        'action': taskName,
        'result': result    
      });
    }
    
    tasksList = [task1, task2, task3, task4];
    
    module.exports.doTask1 = function(req, res) {
      ee = new EventEmitter.EventEmitter();
      var tasksResult = {};
    
      ee.on('task-done', function(result) {
        console.log('task-done', result);
        tasksResult[result['action']] = result['result'];
        var totalResults = Object.keys(tasksResult).length;
    
        if (totalResults <= tasksList.length-1) return;
        
        console.log('tasks done', tasksResult);
        finish();
      });
      
      var taskExecuteFn = function(task, t) {
        this.tasksResult = tasksResult;
        task.call(this);
      }
      
      var finish = function() {
        res.end(JSON.stringify(tasksResult));
      }
    
      tasksList.forEach(taskExecuteFn);
    };
    
    

    external by Github  2  0  1  0

    evented JSX rendering without classes

    evented JSX rendering without classes: sample.jsx
    function siteDef(state) {
      return <div>
        function* () {
          var state = "Your Site";
          var resolve;
          
          function render() {
            return <h1 contentEditable={true} onInput={onInput}>{state}</h1>;
          }
          function rerender() {
            resolve(render())
          }
          function onInput(event) {
            state = event.target.innerHTML;
            rerender()
          }
          
          yield render()
          
          while (true) {
            yield new Promise(function(_resolve, reject) {
              resolve = _resolve;
            });
          }
        }
      <div>
    }
    
    

    external by lauromoura  1  0  1  0

    Garbage collecting evented objects.

    Garbage collecting evented objects.: event_gc.cs
    using System;
    using System.Runtime.CompilerServices;
    
    public class Foo
    {
        public int x;
        public Foo(int x) {
            Console.WriteLine("Constructor called for {0}", x);
            this.x = x;
        }
    
        ~Foo() {
            Console.WriteLine("Destructor called for {0}", x);
        }
    
        public event EventHandler Changed;
    
        public static void Main()
        {
            Console.WriteLine("Entering scope");
            {
                Console.WriteLine("Creating 0 for no event and 1 for evented");
                Foo a = new Foo(0);
                Foo b = new Foo(1);
                b.Changed += (object sender, EventArgs args) => { };
                Console.WriteLine("Will exit scope");
            }
            Console.WriteLine("Exited scope. Will collect.");
            System.GC.Collect();
            System.GC.WaitForPendingFinalizers();
            Console.WriteLine("Exiting main. Collected");
        }
    }
    
    
    
    • Public Snippets
    • Channels Snippets