<commit_before># Copyright 2011 <NAME>
#
# This file is part of POX.
#
# POX is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# POX is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with POX.  If not, see <http://www.gnu.org/licenses/>.

"""
Revent is a custom event library for POX. 

The most common use case of revent is to inherit from EventMixin.

For example:

class Foo (EventMixin):
  def __init__(self):
   # This tells revent that we want to listen to events triggered by pox.core
   self.listenTo(pox.core)
  
  
  def _handle_ComponentRegistered(self, event):
    # The name of this method has a special meaning. Any method with a prefix
    # of '_handle_', and a suffix naming an EventType will automatically
    # be registered as an event handler.
    #  
    # This method will now be called whenever pox.core triggers a 
    # ComponentRegistered event.
    
    # All event handlers are passed an event object as a second parameter. 
    component = event.component
    name = event.name
    print "I see you,", name, "!"

  # A second way to register handlers is to explicitly call self.addListener()
  # For example:
  def bar_handler(self, event):
    print "bar!", event
  
  # This has the same effect as defining a method called "_handle_UpEvent"
  self.addListener(UpEvent, bar_handler)
"""
import operator
# weakrefs are used for some event handlers. 
#
# See: http://docs.python.org/library/weakref.html:
# "A weak reference to an object is not enough to keep the object alive: when the
# only remaining references to a referent are weak references, garbage collection
# is free to destroy the referent"
import weakref

showEventExceptions = False

nextEventID = 0
def generateEventID ():
  global nextEventID
  nextEventID += 1
  return nextEventID

def EventReturn (halt = False, remove = False):
  return (halt, remove)

EventHalt = EventReturn(halt=True)

EventRemove = EventReturn(remove=True)

EventHaltAndRemove = EventReturn(remove=True, halt=True)

class Event (object):
  def __init__ (self):
    self.halt = False
    self.source = None

  def _invoke (self, handler, *args, **kw):
    return handler(self, *args, **kw)

class EventMixin (object):
  """
  Mixin to be inherited from if the subclass is interested in handling events
  """
  # What does (_eventMixin_events == True) signify?
  _eventMixin_events = set()

  def _eventMixin_addEvent (self, eventType):
    self._eventMixin_init()
    if self._eventMixin_events == True:
      # Do nothing, all events already accepted!
      # print warning?
      return
    elif self._eventMixin_events == None:
      self._eventMixin_events = set()
    self._eventMixin_events.add(eventType)

  def __init__ (self):
    self._eventMixin_init()

  def _eventMixin_init (self):
    if not hasattr(self, "_eventMixin_events"):
      setattr(self, "_eventMixin_events", True)
    if not hasattr(self, "_eventMixin_handlers"):
      setattr(self, "_eventMixin_handlers", {})

  def raiseEventNoErrors (self, event, *args, **kw):
    """
    Raise an event, but squelch all exception thrown by handler.
    Also see raiseEvent()
    """
    #TODO: this should really keep subsequent events executing and print the
    #      specific handler that failed...
    try:
      return self.raiseEvent(event, *args, **kw)
    except:
      print "Event handler raised exception"
      if showEventExceptions:
        import traceback
        traceback.print_exc()
    return None

  def raiseEvent (self, event, *args, **kw):
    """
    Raises an event.
    If "event" is an event type, it will be initialized with args and kw, but only
    if there are actually listeners.
    Returns the event object, unless it was never created (because there were no
    listeners) in which case returns None.
    """
    self._eventMixin_init()

    classCall = False
    if isinstance(event, Event):
      eventType = event.__class__
      classCall = True
      if event.source is None: event.source = self
    elif issubclass(event, Event):
      # Check for early-out
      if event not in self._eventMixin_handlers:
        return None
      if len(self._eventMixin_handlers[event]) == 0:
        return None

      classCall = True
      eventType = event
      event = eventType(*args, **kw)
      args = ()
      kw = {}
      if event.source is None: event.source = self
    #print "raise",event,eventType<commit_msg>revent.py: fixed a bug, where attribute didn't exist. Traceback here:<commit_after># Copyright 2011 <NAME>
#
# This file is part of POX.
#
# POX is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# POX is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with POX.  If not, see <http://www.gnu.org/licenses/>.

"""
Revent is a custom event library for POX. 

The most common use case of revent is to inherit from EventMixin.

For example:

class Foo (EventMixin):
  def __init__(self):
   # This tells revent that we want to listen to events triggered by pox.core
   self.listenTo(pox.core)
  
  
  def _handle_ComponentRegistered(self, event):
    # The name of this method has a special meaning. Any method with a prefix
    # of '_handle_', and a suffix naming an EventType will automatically
    # be registered as an event handler.
    #  
    # This method will now be called whenever pox.core triggers a 
    # ComponentRegistered event.
    
    # All event handlers are passed an event object as a second parameter. 
    component = event.component
    name = event.name
    print "I see you,", name, "!"

  # A second way to register handlers is to explicitly call self.addListener()
  # For example:
  def bar_handler(self, event):
    print "bar!", event
  
  # This has the same effect as defining a method called "_handle_UpEvent"
  self.addListener(UpEvent, bar_handler)
"""
import operator
# weakrefs are used for some event handlers. 
#
# See: http://docs.python.org/library/weakref.html:
# "A weak reference to an object is not enough to keep the object alive: when the
# only remaining references to a referent are weak references, garbage collection
# is free to destroy the referent"
import weakref

showEventExceptions = False

nextEventID = 0
def generateEventID ():
  global nextEventID
  nextEventID += 1
  return nextEventID

def EventReturn (halt = False, remove = False):
  return (halt, remove)

EventHalt = EventReturn(halt=True)

EventRemove = EventReturn(remove=True)

EventHaltAndRemove = EventReturn(remove=True, halt=True)

class Event (object):
  def __init__ (self):
    self.halt = False
    self.source = None

  def _invoke (self, handler, *args, **kw):
    return handler(self, *args, **kw)

class EventMixin (object):
  """
  Mixin to be inherited from if the subclass is interested in handling events
  """
  # What does (_eventMixin_events == True) signify?
  _eventMixin_events = set()

  def _eventMixin_addEvent (self, eventType):
    self._eventMixin_init()
    if self._eventMixin_events == True:
      # Do nothing, all events already accepted!
      # print warning?
      return
    elif self._eventMixin_events == None:
      self._eventMixin_events = set()
    self._eventMixin_events.add(eventType)

  def __init__ (self):
    self._eventMixin_init()

  def _eventMixin_init (self):
    if not hasattr(self, "_eventMixin_events"):
      setattr(self, "_eventMixin_events", True)
    if not hasattr(self, "_eventMixin_handlers"):
      setattr(self, "_eventMixin_handlers", {})

  def raiseEventNoErrors (self, event, *args, **kw):
    """
    Raise an event, but squelch all exception thrown by handler.
    Also see raiseEvent()
    """
    #TODO: this should really keep subsequent events executing and print the
    #      specific handler that failed...
    try:
      return self.raiseEvent(event, *args, **kw)
    except:
      print "Event handler raised exception"
      if showEventExceptions:
        import traceback
        traceback.print_exc()
    return None

  def raiseEvent (self, event, *args, **kw):
    """
    Raises an event.
    If "event" is an event type, it will be initialized with args and kw, but only
    if there are actually listeners.
    Returns the event object, unless it was never created (because there were no
    listeners) in which case returns None.
    """
    self._eventMixin_init()

    classCall = False
    if isinstance(event, Event):
      eventType = event.__class__
      classCall = True
      if event.source is None: event.source = self
    elif issubclass(event, Event):
      # Check for early-out
      if event not in self._eventMixin_handlers:
        return None
      if len(self._eventMixin_handlers[event]) == 0:
        return None

      classCall = True
      eventType = event
      event = eventType(*args, **kw)
      args = ()
      kw = {}
      if not hasattr(event, 'source') or event.source is None: event.source = self
    #print "raise",event,eventType
{'fraction_non_alphanumeric': 0.08253024400246053, 'fraction_numerical': 0.0016403526758253025, 'mean_word_length': 3.316371681415929, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 7, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5736971', 'n_tokens_mistral': 2844, 'n_tokens_neox': 2788, 'n_words': 1126}