signature:
def _effective_path ( self ) : # type : ( ) - > List [ str ]
    """Returns a list of paths to search for config files in reverse order of
 precedence . In other words : the last path element will override the
 settings from the first one ."""

implementation:
# default search path
path = ( [ '/etc/%s/%s' % ( self . group_name , self . app_name ) ] + self . get_xdg_dirs ( ) + [ expanduser ( '~/.%s/%s' % ( self . group_name , self . app_name ) ) , self . get_xdg_home ( ) , join ( getcwd ( ) , '.{}' . format ( self . group_name ) , self . app_name ) ] )
# If a path was passed directly to this instance , override the path .
if self . search_path :
    path = self . search_path . split ( pathsep )
# Next , consider the environment variables . . .
env_path = getenv ( self . env_path_name )
if env_path and env_path . startswith ( '+' ) : # If prefixed with a ' + ' , append the path elements
    additional_paths = env_path [ 1 : ] . split ( pathsep )
    self . _log . info ( 'Search path extended with %r by the environment ' 'variable %s.' , additional_paths , self . env_path_name )
    path . extend ( additional_paths )
elif env_path : # Otherwise , override again . This takes absolute precedence .
    self . _log . info ( "Configuration search path was overridden with " "%r by the environment variable %r." , env_path , self . env_path_name )
    path = env_path . split ( pathsep )
return path


signature:
def check_file ( self , filename ) : # type : ( str ) - > bool
    """Check if ` ` filename ` ` can be read . Will return boolean which is True if
 the file can be read , False otherwise ."""

implementation:
if not exists ( filename ) :
    return False
# Check if the file is version - compatible with this instance .
new_config = ConfigResolverBase ( )
new_config . read ( filename )
if self . version and not new_config . has_option ( 'meta' , 'version' ) : # self . version is set , so we MUST have a version in the file !
    raise NoVersionError ( "The config option 'meta.version' is missing in {}. The " "application expects version {}!" . format ( filename , self . version ) )
elif not self . version and new_config . has_option ( 'meta' , 'version' ) : # Automatically " lock - in " a version number if one is found .
# This prevents loading a chain of config files with incompatible
# version numbers !
    self . version = StrictVersion ( new_config . get ( 'meta' , 'version' ) )
    self . _log . info ( '%r contains a version number, but the config ' 'instance was not created with a version ' 'restriction. Will set version number to "%s" to ' 'prevent accidents!' , filename , self . version )
elif self . version : # This instance expected a certain version . We need to check the
# version in the file and compare .
    file_version = new_config . get ( 'meta' , 'version' )
    major , minor , _ = StrictVersion ( file_version ) . version
    expected_major , expected_minor , _ = self . version . version
    if expected_major != major :
        self . _log . error ( 'Invalid major version number in %r. Expected %r, got %r!' , abspath ( filename ) , str ( self . version ) , file_version )
        return False
    if expected_minor != minor :
        self . _log . warning ( 'Mismatching minor version number in %r. ' 'Expected %r, got %r!' , abspath ( filename ) , str ( self . version ) , file_version )
        return True
return True


signature:
def get ( self , section , option , ** kwargs ) : # type : ignore
# type : ( str , str , Any ) - > Any
    """Overrides : py : meth : ` configparser . ConfigParser . get ` .
 In addition to ` ` section ` ` and ` ` option ` ` , this call takes an optional
 ` ` default ` ` value . This behaviour works in * addition * to the
 : py : class : ` configparser . ConfigParser ` default mechanism . Note that
 a default value from ` ` ConfigParser ` ` takes precedence .
 The reason this additional functionality is added , is because the
 defaults of : py : class : ` configparser . ConfigParser ` are not dependent
 on sections . If you specify a default for the option ` ` test ` ` , then
 this value will be returned for both ` ` section1 . test ` ` and for
 ` ` section2 . test ` ` . Using the default on the ` ` get ` ` call gives you more
 fine - grained control over this .
 Also note , that if a default value was used , it will be logged with
 level ` ` logging . DEBUG ` ` .
 : param section : The config file section .
 : param option : The option name .
 : param kwargs : These keyword args are passed through to
 : py : meth : ` configparser . ConfigParser . get ` ."""

implementation:
if "default" in kwargs :
    default = kwargs . pop ( "default" )
    new_kwargs = { 'fallback' : default }
    new_kwargs . update ( kwargs )
    new_call = build_call_str ( '.get' , ( section , option ) , new_kwargs )
    warn ( 'Using the "default" argument to Config.get() will no ' 'longer work in config_resolver 5.0! Version 5 will return ' 'standard Python ConfigParser instances which use "fallback" ' 'instead of "default". Replace your code with "%s"' % new_call , DeprecationWarning , stacklevel = 2 )
    have_default = True
else :
    have_default = False
try :
    value = super ( Config , self ) . get ( section , option , ** kwargs )
    return value
except ( NoSectionError , NoOptionError ) as exc :
    if have_default :
        self . _log . debug ( "%s: Returning default value %r" , exc , default )
        return default
    else :
        raise


signature:
def load ( self , reload = False , require_load = False ) : # type : ( bool , bool ) - > None
    """Searches for an appropriate config file . If found , loads the file into
 the current instance . This method can also be used to reload a
 configuration . Note that you may want to set ` ` reload ` ` to ` ` True ` ` to
 clear the configuration before loading in that case . Without doing
 that , values will remain available even if they have been removed from
 the config files .
 : param reload : if set to ` ` True ` ` , the existing values are cleared
 before reloading .
 : param require _ load : If set to ` ` True ` ` this will raise a
 : py : exc : ` IOError ` if no config file has been found
 to load ."""

implementation:
if reload : # pragma : no cover
    self . config = None
# only load the config if necessary ( or explicitly requested )
if self . config : # pragma : no cover
    self . _log . debug ( 'Returning cached config instance. Use ' '``reload=True`` to avoid caching!' )
    return
path = self . _effective_path ( )
config_filename = self . _effective_filename ( )
# Next , use the resolved path to find the filenames . Keep track of
# which files we loaded in order to inform the user .
self . _active_path = [ join ( _ , config_filename ) for _ in path ]
for dirname in path :
    conf_name = join ( dirname , config_filename )
    readable = self . check_file ( conf_name )
    if readable :
        action = 'Updating' if self . _loaded_files else 'Loading initial'
        self . _log . info ( '%s config from %s' , action , conf_name )
        self . read ( conf_name )
        if conf_name == expanduser ( "~/.%s/%s/%s" % ( self . group_name , self . app_name , self . filename ) ) :
            self . _log . warning ( "DEPRECATION WARNING: The file " "'%s/.%s/%s/app.ini' was loaded. The XDG " "Basedir standard requires this file to be in " "'%s/.config/%s/%s/app.ini'! This location " "will no longer be parsed in a future version of " "config_resolver! You can already (and should) move " "the file!" , expanduser ( "~" ) , self . group_name , self . app_name , expanduser ( "~" ) , self . group_name , self . app_name )
        self . _loaded_files . append ( conf_name )
if not self . _loaded_files and not require_load :
    self . _log . warning ( "No config file named %s found! Search path was %r" , config_filename , path )
elif not self . _loaded_files and require_load :
    raise IOError ( "No config file named %s found! Search path " "was %r" % ( config_filename , path ) )


signature:
def check_file ( self , filename ) : # type : ( str ) - > bool
    """Overrides : py : meth : ` . Config . check _ file `"""

implementation:
can_read = super ( SecuredConfig , self ) . check_file ( filename )
if not can_read :
    return False
mode = get_stat ( filename ) . st_mode
if ( mode & stat . S_IRGRP ) or ( mode & stat . S_IROTH ) :
    msg = "File %r is not secure enough. Change it's mode to 600"
    self . _log . warning ( msg , filename )
    return False
return True


signature:
def setup_environ ( self ) :
    """https : / / www . python . org / dev / peps / pep - 0333 / # environ - variables"""

implementation:
# Set up base environment
env = self . base_environ = { }
env [ 'SERVER_NAME' ] = self . server_name
env [ 'GATEWAY_INTERFACE' ] = 'CGI/1.1'
env [ 'SERVER_PORT' ] = str ( self . server_port )
env [ 'REMOTE_HOST' ] = ''
env [ 'CONTENT_LENGTH' ] = ''
env [ 'SCRIPT_NAME' ] = ''


signature:
def get_environ ( self ) :
    """https : / / www . python . org / dev / peps / pep - 0333 / # environ - variables"""

implementation:
env = self . base_environ . copy ( )
env [ 'REQUEST_METHOD' ] = self . request_method
if '?' in self . path :
    path , query = self . path . split ( '?' , 1 )
else :
    path , query = self . path , ''
env [ 'PATH_INFO' ] = urllib . parse . unquote ( path )
env [ 'QUERY_STRING' ] = query
env [ 'CONTENT_TYPE' ] = self . headers . get ( 'Content-Type' , '' )
env [ 'CONTENT_LENGTH' ] = self . headers . get ( 'Content-Length' , '0' )
env [ 'SERVER_PROTOCOL' ] = self . request_version
env [ 'REMOTE_ADDR' ] = self . client_address [ 0 ]
env [ 'REMOTE_PORT' ] = self . client_address [ 1 ]
env [ 'wsgi.version' ] = ( 1 , 0 )
env [ 'wsgi.url_scheme' ] = 'http'
env [ 'wsgi.input' ] = io . BytesIO ( self . raw_request )
env [ 'wsgi.errors' ] = sys . stderr
env [ 'wsgi.multithread' ] = False
env [ 'wsgi.multiprocess' ] = True
env [ 'wsgi.run_once' ] = False
for k , v in self . headers . items ( ) :
    k = k . replace ( '-' , '_' ) . upper ( )
    if k in env :
        continue
    env [ 'HTTP_' + k ] = v
return env


signature:
def get ( self , q = None , page = None ) :
    """Get styles ."""

implementation:
# Check cache to exit early if needed
etag = generate_etag ( current_ext . content_version . encode ( 'utf8' ) )
self . check_etag ( etag , weak = True )
# Build response
res = jsonify ( current_ext . styles )
res . set_etag ( etag )
return res


signature:
def create_from_settings ( settings ) :
    """Create a connection with given settings .
 Args :
 settings ( dict ) : A dictionary of settings
 Returns :
 : class : ` Connection ` . The connection"""

implementation: return Connection ( settings [ "url" ] , settings [ "base_url" ] , settings [ "user" ] , settings [ "password" ] , authorizations = settings [ "authorizations" ] , debug = settings [ "debug" ] )


signature:
def delete ( self , url = None , post_data = { } , parse_data = False , key = None , parameters = None ) :
    """Issue a PUT request .
 Kwargs :
 url ( str ) : Destination URL
 post _ data ( dict ) : Dictionary of parameter and values
 parse _ data ( bool ) : If true , parse response data
 key ( string ) : If parse _ data = = True , look for this key when parsing data
 parameters ( dict ) : Additional GET parameters to append to the URL
 Returns :
 dict . Response ( a dict with keys : success , data , info , body )
 Raises :
 AuthenticationError , ConnectionError , urllib2 . HTTPError , ValueError , Exception"""

implementation: return self . _fetch ( "DELETE" , url , post_data = post_data , parse_data = parse_data , key = key , parameters = parameters , full_return = True )


signature:
def post ( self , url = None , post_data = { } , parse_data = False , key = None , parameters = None , listener = None ) :
    """Issue a POST request .
 Kwargs :
 url ( str ) : Destination URL
 post _ data ( dict ) : Dictionary of parameter and values
 parse _ data ( bool ) : If true , parse response data
 key ( string ) : If parse _ data = = True , look for this key when parsing data
 parameters ( dict ) : Additional GET parameters to append to the URL
 listener ( func ) : callback called when uploading a file
 Returns :
 dict . Response ( a dict with keys : success , data , info , body )
 Raises :
 AuthenticationError , ConnectionError , urllib2 . HTTPError , ValueError , Exception"""

implementation: return self . _fetch ( "POST" , url , post_data = post_data , parse_data = parse_data , key = key , parameters = parameters , listener = listener , full_return = True )


signature:
def get ( self , url = None , parse_data = True , key = None , parameters = None ) :
    """Issue a GET request .
 Kwargs :
 url ( str ) : Destination URL
 parse _ data ( bool ) : If true , parse response data
 key ( string ) : If parse _ data = = True , look for this key when parsing data
 parameters ( dict ) : Additional GET parameters to append to the URL
 Returns :
 dict . Response ( a dict with keys : success , data , info , body )
 Raises :
 AuthenticationError , ConnectionError , urllib2 . HTTPError , ValueError , Exception"""

implementation: return self . _fetch ( "GET" , url , post_data = None , parse_data = parse_data , key = key , parameters = parameters )


signature:
def get_headers ( self ) :
    """Get headers .
 Returns :
 tuple : Headers"""

implementation:
headers = { "User-Agent" : "kFlame 1.0" }
password_url = self . _get_password_url ( )
if password_url and password_url in self . _settings [ "authorizations" ] :
    headers [ "Authorization" ] = self . _settings [ "authorizations" ] [ password_url ]
return headers


signature:
def _get_password_url ( self ) :
    """Get URL used for authentication
 Returns :
 string : URL"""

implementation:
password_url = None
if self . _settings [ "user" ] or self . _settings [ "authorization" ] :
    if self . _settings [ "url" ] :
        password_url = self . _settings [ "url" ]
    elif self . _settings [ "base_url" ] :
        password_url = self . _settings [ "base_url" ]
return password_url


signature:
def parse ( self , text , key = None ) :
    """Parses a response .
 Args :
 text ( str ) : Text to parse
 Kwargs :
 key ( str ) : Key to look for , if any
 Returns :
 Parsed value
 Raises :
 ValueError"""

implementation:
try :
    data = json . loads ( text )
except ValueError as e :
    raise ValueError ( "%s: Value: [%s]" % ( e , text ) )
if data and key :
    if key not in data :
        raise ValueError ( "Invalid response (key %s not found): %s" % ( key , data ) )
    data = data [ key ]
return data


signature:
def build_twisted_request ( self , method , url , extra_headers = { } , body_producer = None , full_url = False ) :
    """Build a request for twisted
 Args :
 method ( str ) : Request method ( GET / POST / PUT / DELETE / etc . ) If not specified , it will be POST if post _ data is not None
 url ( str ) : Destination URL ( full , or relative )
 Kwargs :
 extra _ headers ( dict ) : Headers ( override default connection headers , if any )
 body _ producer ( : class : ` twisted . web . iweb . IBodyProducer ` ) : Object producing request body
 full _ url ( bool ) : If False , URL is relative
 Returns :
 tuple . Tuple with two elements : reactor , and request"""

implementation:
uri = url if full_url else self . _url ( url )
raw_headers = self . get_headers ( )
if extra_headers :
    raw_headers . update ( extra_headers )
headers = http_headers . Headers ( )
for header in raw_headers :
    headers . addRawHeader ( header , raw_headers [ header ] )
agent = client . Agent ( reactor )
request = agent . request ( method , uri , headers , body_producer )
return ( reactor , request )


signature:
def _fetch ( self , method , url = None , post_data = None , parse_data = True , key = None , parameters = None , listener = None , full_return = False ) :
    """Issue a request .
 Args :
 method ( str ) : Request method ( GET / POST / PUT / DELETE / etc . ) If not specified , it will be POST if post _ data is not None
 Kwargs :
 url ( str ) : Destination URL
 post _ data ( str ) : A string of what to POST
 parse _ data ( bool ) : If true , parse response data
 key ( string ) : If parse _ data = = True , look for this key when parsing data
 parameters ( dict ) : Additional GET parameters to append to the URL
 listener ( func ) : callback called when uploading a file
 full _ return ( bool ) : If set to True , get a full response ( with success , data , info , body )
 Returns :
 dict . Response . If full _ return = = True , a dict with keys : success , data , info , body , otherwise the parsed data
 Raises :
 AuthenticationError , ConnectionError , urllib2 . HTTPError , ValueError"""

implementation:
headers = self . get_headers ( )
headers [ "Content-Type" ] = "application/json"
handlers = [ ]
debuglevel = int ( self . _settings [ "debug" ] )
handlers . append ( urllib2 . HTTPHandler ( debuglevel = debuglevel ) )
if hasattr ( httplib , "HTTPS" ) :
    handlers . append ( urllib2 . HTTPSHandler ( debuglevel = debuglevel ) )
handlers . append ( urllib2 . HTTPCookieProcessor ( cookielib . CookieJar ( ) ) )
password_url = self . _get_password_url ( )
if password_url and "Authorization" not in headers :
    pwd_manager = urllib2 . HTTPPasswordMgrWithDefaultRealm ( )
    pwd_manager . add_password ( None , password_url , self . _settings [ "user" ] , self . _settings [ "password" ] )
    handlers . append ( HTTPBasicAuthHandler ( pwd_manager ) )
opener = urllib2 . build_opener ( * handlers )
if post_data is not None :
    post_data = json . dumps ( post_data )
uri = self . _url ( url , parameters )
request = RESTRequest ( uri , method = method , headers = headers )
if post_data is not None :
    request . add_data ( post_data )
response = None
try :
    response = opener . open ( request )
    body = response . read ( )
    if password_url and password_url not in self . _settings [ "authorizations" ] and request . has_header ( "Authorization" ) :
        self . _settings [ "authorizations" ] [ password_url ] = request . get_header ( "Authorization" )
except urllib2 . HTTPError as e :
    if e . code == 401 :
        raise AuthenticationError ( "Access denied while trying to access %s" % uri )
    elif e . code == 404 :
        raise ConnectionError ( "URL not found: %s" % uri )
    else :
        raise
except urllib2 . URLError as e :
    raise ConnectionError ( "Error while fetching from %s: %s" % ( uri , e ) )
finally :
    if response :
        response . close ( )
    opener . close ( )
data = None
if parse_data :
    if not key :
        key = string . split ( url , "/" ) [ 0 ]
    data = self . parse ( body , key )
if full_return :
    info = response . info ( ) if response else None
    status = int ( string . split ( info [ "status" ] ) [ 0 ] ) if ( info and "status" in info ) else None
    return { "success" : ( status >= 200 and status < 300 ) , "data" : data , "info" : info , "body" : body }
return data


signature:
def _url ( self , url = None , parameters = None ) :
    """Build destination URL .
 Kwargs :
 url ( str ) : Destination URL
 parameters ( dict ) : Additional GET parameters to append to the URL
 Returns :
 str . URL"""

implementation:
uri = url or self . _settings [ "url" ]
if url and self . _settings [ "base_url" ] :
    uri = "%s/%s" % ( self . _settings [ "base_url" ] , url )
uri += ".json"
if parameters :
    uri += "?%s" % urllib . urlencode ( parameters )
return uri


signature:
def is_text ( self ) :
    """Tells if this message is a text message .
 Returns :
 bool . Success"""

implementation: return self . type in [ self . _TYPE_PASTE , self . _TYPE_TEXT , self . _TYPE_TWEET ]


signature:
def get_rooms ( self , sort = True ) :
    """Get rooms list .
 Kwargs :
 sort ( bool ) : If True , sort rooms by name
 Returns :
 array . List of rooms ( each room is a dict )"""

implementation:
rooms = self . _connection . get ( "rooms" )
if sort :
    rooms . sort ( key = operator . itemgetter ( "name" ) )
return rooms


signature:
def get_room_by_name ( self , name ) :
    """Get a room by name .
 Returns :
 : class : ` Room ` . Room
 Raises :
 RoomNotFoundException"""

implementation:
rooms = self . get_rooms ( )
for room in rooms or [ ] :
    if room [ "name" ] == name :
        return self . get_room ( room [ "id" ] )
raise RoomNotFoundException ( "Room %s not found" % name )


signature:
def get_room ( self , id ) :
    """Get room .
 Returns :
 : class : ` Room ` . Room"""

implementation:
if id not in self . _rooms :
    self . _rooms [ id ] = Room ( self , id )
return self . _rooms [ id ]


signature:
def get_user ( self , id = None ) :
    """Get user .
 Returns :
 : class : ` User ` . User"""

implementation:
if not id :
    id = self . _user . id
if id not in self . _users :
    self . _users [ id ] = self . _user if id == self . _user . id else User ( self , id )
return self . _users [ id ]


signature:
def search ( self , terms ) :
    """Search transcripts .
 Args :
 terms ( str ) : Terms for search
 Returns :
 array . Messages"""

implementation:
messages = self . _connection . get ( "search/%s" % urllib . quote_plus ( terms ) , key = "messages" )
if messages :
    messages = [ Message ( self , message ) for message in messages ]
return messages


signature:
def cookie_dump ( key , value = '' , max_age = None , expires = None , path = '/' , domain = None , secure = False , httponly = False ) :
    """: rtype : ` ` Cookie . SimpleCookie ` `"""

implementation:
cookie = SimpleCookie ( )
cookie [ key ] = value
for attr in ( 'max_age' , 'expires' , 'path' , 'domain' , 'secure' , 'httponly' ) :
    attr_key = attr . replace ( '_' , '-' )
    attr_value = locals ( ) [ attr ]
    if attr_value :
        cookie [ key ] [ attr_key ] = attr_value
return cookie


signature:
def response_status_string ( code ) :
    """e . g . ` ` 200 OK ` `"""

implementation:
mean = HTTP_STATUS_CODES . get ( code , 'unknown' ) . upper ( )
return '{code} {mean}' . format ( code = code , mean = mean )


signature:
def cookies ( self ) :
    """Request cookies
 : rtype : dict"""

implementation:
http_cookie = self . environ . get ( 'HTTP_COOKIE' , '' )
_cookies = { k : v . value for ( k , v ) in SimpleCookie ( http_cookie ) . items ( ) }
return _cookies


signature:
def attach ( self , observer ) :
    """Attach an observer .
 Args :
 observer ( func ) : A function to be called when new messages arrive
 Returns :
 : class : ` Stream ` . Current instance to allow chaining"""

implementation:
if not observer in self . _observers :
    self . _observers . append ( observer )
return self


signature:
def incoming ( self , messages ) :
    """Called when incoming messages arrive .
 Args :
 messages ( tuple ) : Messages ( each message is a dict )"""

implementation:
if self . _observers :
    campfire = self . _room . get_campfire ( )
    for message in messages :
        for observer in self . _observers :
            observer ( Message ( campfire , message ) )


signature:
def run ( self ) :
    """Called by the thread , it runs the process .
 NEVER call this method directly . Instead call start ( ) to start the thread .
 To stop , call stop ( ) , and then join ( )"""

implementation:
if self . _live :
    self . _use_process = True
self . _abort = False
campfire = self . _room . get_campfire ( )
if self . _live :
    process = LiveStreamProcess ( campfire . get_connection ( ) . get_settings ( ) , self . _room . id )
else :
    process = StreamProcess ( campfire . get_connection ( ) . get_settings ( ) , self . _room . id , pause = self . _pause )
if not self . _use_process :
    process . set_callback ( self . incoming )
if self . _use_process :
    queue = Queue ( )
    process . set_queue ( queue )
    process . start ( )
    if not process . is_alive ( ) :
        return
self . _streaming = True
while not self . _abort :
    if self . _use_process :
        if not process . is_alive ( ) :
            self . _abort = True
            break
        try :
            incoming = queue . get_nowait ( )
            if isinstance ( incoming , list ) :
                self . incoming ( incoming )
            elif isinstance ( incoming , Exception ) :
                self . _abort = True
                if self . _error_callback :
                    self . _error_callback ( incoming , self . _room )
        except Empty :
            time . sleep ( self . _pause )
            pass
    else :
        process . fetch ( )
        time . sleep ( self . _pause )
self . _streaming = False
if self . _use_process and self . _abort and not process . is_alive ( ) and self . _error_callback :
    self . _error_callback ( Exception ( "Streaming process was killed" ) , self . _room )
if self . _use_process :
    queue . close ( )
    if process . is_alive ( ) :
        process . stop ( )
        process . terminate ( )
    process . join ( )


signature:
def run ( self ) :
    """Called by the process , it runs it .
 NEVER call this method directly . Instead call start ( ) to start the separate process .
 If you don ' t want to use a second process , then call fetch ( ) directly on this istance .
 To stop , call terminate ( )"""

implementation:
if not self . _queue :
    raise Exception ( "No queue available to send messages" )
while True :
    self . fetch ( )
    time . sleep ( self . _pause )


signature:
def fetch ( self ) :
    """Fetch new messages ."""

implementation:
try :
    if not self . _last_message_id :
        messages = self . _connection . get ( "room/%s/recent" % self . _room_id , key = "messages" , parameters = { "limit" : 1 } )
        self . _last_message_id = messages [ - 1 ] [ "id" ]
    messages = self . _connection . get ( "room/%s/recent" % self . _room_id , key = "messages" , parameters = { "since_message_id" : self . _last_message_id } )
except :
    messages = [ ]
if messages :
    self . _last_message_id = messages [ - 1 ] [ "id" ]
self . received ( messages )


signature:
def received ( self , messages ) :
    """Called when new messages arrive .
 Args :
 messages ( tuple ) : Messages"""

implementation:
if messages :
    if self . _queue :
        self . _queue . put_nowait ( messages )
    if self . _callback :
        self . _callback ( messages )


implementation:
if not self . _queue :
    raise Exception ( "No queue available to send messages" )
factory = LiveStreamFactory ( self )
self . _reactor . connectSSL ( "streaming.campfirenow.com" , 443 , factory , ssl . ClientContextFactory ( ) )
self . _reactor . run ( )


signature:
def stop ( self ) :
    """Stop streaming"""

implementation:
if self . _protocol :
    self . _protocol . factory . continueTrying = 0
    self . _protocol . transport . loseConnection ( )
if self . _reactor and self . _reactor . running :
    self . _reactor . stop ( )


signature:
def connectionMade ( self ) :
    """Called when a connection is made , and used to send out headers"""

implementation:
headers = [ "GET %s HTTP/1.1" % ( "/room/%s/live.json" % self . factory . get_stream ( ) . get_room_id ( ) ) ]
connection_headers = self . factory . get_stream ( ) . get_connection ( ) . get_headers ( )
for header in connection_headers :
    headers . append ( "%s: %s" % ( header , connection_headers [ header ] ) )
headers . append ( "Host: streaming.campfirenow.com" )
self . transport . write ( "\r\n" . join ( headers ) + "\r\n\r\n" )
self . factory . get_stream ( ) . set_protocol ( self )


signature:
def lineReceived ( self , line ) :
    """Callback issued by twisted when new line arrives .
 Args :
 line ( str ) : Incoming line"""

implementation:
while self . _in_header :
    if line :
        self . _headers . append ( line )
    else :
        http , status , message = self . _headers [ 0 ] . split ( " " , 2 )
        status = int ( status )
        if status == 200 :
            self . factory . get_stream ( ) . connected ( )
        else :
            self . factory . continueTrying = 0
            self . transport . loseConnection ( )
            self . factory . get_stream ( ) . disconnected ( RuntimeError ( status , message ) )
            return
        self . _in_header = False
    break
else :
    try :
        self . _len_expected = int ( line , 16 )
        self . setRawMode ( )
    except :
        pass


signature:
def rawDataReceived ( self , data ) :
    """Process data .
 Args :
 data ( str ) : Incoming data"""

implementation:
if self . _len_expected is not None :
    data , extra = data [ : self . _len_expected ] , data [ self . _len_expected : ]
    self . _len_expected -= len ( data )
else :
    extra = ""
self . _buffer += data
if self . _len_expected == 0 :
    data = self . _buffer . strip ( )
    if data :
        lines = data . split ( "\r" )
        for line in lines :
            try :
                message = self . factory . get_stream ( ) . get_connection ( ) . parse ( line )
                if message :
                    self . factory . get_stream ( ) . received ( [ message ] )
            except ValueError :
                pass
    self . _buffer = ""
    self . _len_expected = None
    self . setLineMode ( extra )


signature:
def get_func ( self , path ) :
    """: return : ( func , methods )"""

implementation:
for url_match , func_pair in self . _urls_regex_map . items ( ) :
    m = url_match . match ( path )
    if m is not None :
        return func_pair . func , func_pair . methods , m . groupdict ( )
return None , None , None


signature:
def _replace_type_to_regex ( cls , match ) :
    """/ < int : id > - > r ' ( ? P < id > \ d + ) '"""

implementation:
groupdict = match . groupdict ( )
_type = groupdict . get ( 'type' )
type_regex = cls . TYPE_REGEX_MAP . get ( _type , '[^/]+' )
name = groupdict . get ( 'name' )
return r'(?P<{name}>{type_regex})' . format ( name = name , type_regex = type_regex )


signature:
def styles ( self ) :
    """Get a dictionary of CSL styles ."""

implementation:
styles = get_all_styles ( )
whitelist = self . app . config . get ( 'CSL_STYLES_WHITELIST' )
if whitelist :
    return { k : v for k , v in styles . items ( ) if k in whitelist }
return styles


signature:
def init_app ( self , app ) :
    """Flask application initialization ."""

implementation:
state = _InvenioCSLRESTState ( app )
app . extensions [ 'invenio-csl-rest' ] = state
return state


signature:
def startProducing ( self , consumer ) :
    """Start producing .
 Args :
 consumer : Consumer"""

implementation:
self . _consumer = consumer
self . _current_deferred = defer . Deferred ( )
self . _sent = 0
self . _paused = False
if not hasattr ( self , "_chunk_headers" ) :
    self . _build_chunk_headers ( )
if self . _data :
    block = ""
    for field in self . _data :
        block += self . _chunk_headers [ field ]
        block += self . _data [ field ]
        block += "\r\n"
    self . _send_to_consumer ( block )
if self . _files :
    self . _files_iterator = self . _files . iterkeys ( )
    self . _files_sent = 0
    self . _files_length = len ( self . _files )
    self . _current_file_path = None
    self . _current_file_handle = None
    self . _current_file_length = None
    self . _current_file_sent = 0
    result = self . _produce ( )
    if result :
        return result
else :
    return defer . succeed ( None )
return self . _current_deferred


signature:
def resumeProducing ( self ) :
    """Resume producing"""

implementation:
self . _paused = False
result = self . _produce ( )
if result :
    return result


signature:
def stopProducing ( self ) :
    """Stop producing"""

implementation:
self . _finish ( True )
if self . _deferred and self . _sent < self . length :
    self . _deferred . errback ( Exception ( "Consumer asked to stop production of request body (%d sent out of %d)" % ( self . _sent , self . length ) ) )


signature:
def _finish ( self , forced = False ) :
    """Cleanup code after asked to stop producing .
 Kwargs :
 forced ( bool ) : If True , we were forced to stop"""

implementation:
if hasattr ( self , "_current_file_handle" ) and self . _current_file_handle :
    self . _current_file_handle . close ( )
if self . _current_deferred :
    self . _current_deferred . callback ( self . _sent )
    self . _current_deferred = None
if not forced and self . _deferred :
    self . _deferred . callback ( self . _sent )


signature:
def _send_to_consumer ( self , block ) :
    """Send a block of bytes to the consumer .
 Args :
 block ( str ) : Block of bytes"""

implementation:
self . _consumer . write ( block )
self . _sent += len ( block )
if self . _callback :
    self . _callback ( self . _sent , self . length )


signature:
def _length ( self ) :
    """Returns total length for this request .
 Returns :
 int . Length"""

implementation:
self . _build_chunk_headers ( )
length = 0
if self . _data :
    for field in self . _data :
        length += len ( self . _chunk_headers [ field ] )
        length += len ( self . _data [ field ] )
        length += 2
if self . _files :
    for field in self . _files :
        length += len ( self . _chunk_headers [ field ] )
        length += self . _file_size ( field )
        length += 2
length += len ( self . boundary )
length += 6
return length


signature:
def _build_chunk_headers ( self ) :
    """Build headers for each field ."""

implementation:
if hasattr ( self , "_chunk_headers" ) and self . _chunk_headers :
    return
self . _chunk_headers = { }
for field in self . _files :
    self . _chunk_headers [ field ] = self . _headers ( field , True )
for field in self . _data :
    self . _chunk_headers [ field ] = self . _headers ( field )


signature:
def _headers ( self , name , is_file = False ) :
    """Returns the header of the encoding of this parameter .
 Args :
 name ( str ) : Field name
 Kwargs :
 is _ file ( bool ) : If true , this is a file field
 Returns :
 array . Headers"""

implementation:
value = self . _files [ name ] if is_file else self . _data [ name ]
_boundary = self . boundary . encode ( "utf-8" ) if isinstance ( self . boundary , unicode ) else urllib . quote_plus ( self . boundary )
headers = [ "--%s" % _boundary ]
if is_file :
    disposition = 'form-data; name="%s"; filename="%s"' % ( name , os . path . basename ( value ) )
else :
    disposition = 'form-data; name="%s"' % name
headers . append ( "Content-Disposition: %s" % disposition )
if is_file :
    file_type = self . _file_type ( name )
else :
    file_type = "text/plain; charset=utf-8"
headers . append ( "Content-Type: %s" % file_type )
if is_file :
    headers . append ( "Content-Length: %i" % self . _file_size ( name ) )
else :
    headers . append ( "Content-Length: %i" % len ( value ) )
headers . append ( "" )
headers . append ( "" )
return "\r\n" . join ( headers )


signature:
def _boundary ( self ) :
    """Returns a random string to use as the boundary for a message .
 Returns :
 string . Boundary"""

implementation:
boundary = None
try :
    import uuid
    boundary = uuid . uuid4 ( ) . hex
except ImportError :
    import random , sha
    bits = random . getrandbits ( 160 )
    boundary = sha . new ( str ( bits ) ) . hexdigest ( )
return boundary


signature:
def _file_type ( self , field ) :
    """Returns file type for given file field .
 Args :
 field ( str ) : File field
 Returns :
 string . File type"""

implementation:
type = mimetypes . guess_type ( self . _files [ field ] ) [ 0 ]
return type . encode ( "utf-8" ) if isinstance ( type , unicode ) else str ( type )


signature:
def _file_size ( self , field ) :
    """Returns the file size for given file field .
 Args :
 field ( str ) : File field
 Returns :
 int . File size"""

implementation:
size = 0
try :
    handle = open ( self . _files [ field ] , "r" )
    size = os . fstat ( handle . fileno ( ) ) . st_size
    handle . close ( )
except :
    size = 0
self . _file_lengths [ field ] = size
return self . _file_lengths [ field ]


signature:
def _filename ( draw , result_type = None ) :
    """Generate a path value of type result _ type .
 result _ type can either be bytes or text _ type"""

implementation:
# Various ASCII chars have a special meaning for the operating system ,
# so make them more common
ascii_char = characters ( min_codepoint = 0x01 , max_codepoint = 0x7f )
if os . name == 'nt' : # pragma : no cover
# Windows paths can contain all surrogates and even surrogate pairs
# if two paths are concatenated . This makes it more likely for them to
# be generated .
    surrogate = characters ( min_codepoint = 0xD800 , max_codepoint = 0xDFFF )
    uni_char = characters ( min_codepoint = 0x1 )
    text_strategy = text ( alphabet = one_of ( uni_char , surrogate , ascii_char ) )
    def text_to_bytes ( path ) :
        fs_enc = sys . getfilesystemencoding ( )
        try :
            return path . encode ( fs_enc , 'surrogatepass' )
        except UnicodeEncodeError :
            return path . encode ( fs_enc , 'replace' )
    bytes_strategy = text_strategy . map ( text_to_bytes )
else :
    latin_char = characters ( min_codepoint = 0x01 , max_codepoint = 0xff )
    bytes_strategy = text ( alphabet = one_of ( latin_char , ascii_char ) ) . map ( lambda t : t . encode ( 'latin-1' ) )
    unix_path_text = bytes_strategy . map ( lambda b : b . decode ( sys . getfilesystemencoding ( ) , 'surrogateescape' if PY3 else 'ignore' ) )
    # Two surrogates generated through surrogateescape can generate
    # a valid utf - 8 sequence when encoded and result in a different
    # code point when decoded again . Can happen when two paths get
    # concatenated . Shuffling makes it possible to generate such a case .
    text_strategy = permutations ( draw ( unix_path_text ) ) . map ( u"" . join )
if result_type is None :
    return draw ( one_of ( bytes_strategy , text_strategy ) )
elif result_type is bytes :
    return draw ( bytes_strategy )
else :
    return draw ( text_strategy )


signature:
def _str_to_path ( s , result_type ) :
    """Given an ASCII str , returns a path of the given type ."""

implementation:
assert isinstance ( s , str )
if isinstance ( s , bytes ) and result_type is text_type :
    return s . decode ( 'ascii' )
elif isinstance ( s , text_type ) and result_type is bytes :
    return s . encode ( 'ascii' )
return s


signature:
def _path_root ( draw , result_type ) :
    """Generates a root component for a path ."""

implementation:
# Based on https : / / en . wikipedia . org / wiki / Path _ ( computing )
def tp ( s = '' ) :
    return _str_to_path ( s , result_type )
if os . name != 'nt' :
    return tp ( os . sep )
sep = sampled_from ( [ os . sep , os . altsep or os . sep ] ) . map ( tp )
name = _filename ( result_type )
char = characters ( min_codepoint = ord ( "A" ) , max_codepoint = ord ( "z" ) ) . map ( lambda c : tp ( str ( c ) ) )
relative = sep
# [ drive _ letter ] : \
drive = builds ( lambda * x : tp ( ) . join ( x ) , char , just ( tp ( ':' ) ) , sep )
# \ \ ? \ [ drive _ spec ] : \
extended = builds ( lambda * x : tp ( ) . join ( x ) , sep , sep , just ( tp ( '?' ) ) , sep , drive )
network = one_of ( [ # \ \ [ server ] \ [ sharename ] \
builds ( lambda * x : tp ( ) . join ( x ) , sep , sep , name , sep , name , sep ) , # \ \ ? \ [ server ] \ [ sharename ] \
builds ( lambda * x : tp ( ) . join ( x ) , sep , sep , just ( tp ( '?' ) ) , sep , name , sep , name , sep ) , # \ \ ? \ UNC \ [ server ] \ [ sharename ] \
builds ( lambda * x : tp ( ) . join ( x ) , sep , sep , just ( tp ( '?' ) ) , sep , just ( tp ( 'UNC' ) ) , sep , name , sep , name , sep ) , # \ \ . \ [ physical _ device ] \
builds ( lambda * x : tp ( ) . join ( x ) , sep , sep , just ( tp ( '.' ) ) , sep , name , sep ) , ] )
final = one_of ( relative , drive , extended , network )
return draw ( final )


signature:
def fspaths ( draw , allow_pathlike = None ) :
    """A strategy which generates filesystem path values .
 The generated values include everything which the builtin
 : func : ` python : open ` function accepts i . e . which won ' t lead to
 : exc : ` ValueError ` or : exc : ` TypeError ` being raised .
 Note that the range of the returned values depends on the operating
 system , the Python version , and the filesystem encoding as returned by
 : func : ` sys . getfilesystemencoding ` .
 : param allow _ pathlike :
 If : obj : ` python : None ` makes the strategy include objects implementing
 the : class : ` python : os . PathLike ` interface when Python > = 3.6 is used .
 If : obj : ` python : False ` no pathlike objects will be generated . If
 : obj : ` python : True ` pathlike will be generated ( Python > = 3.6 required )
 : type allow _ pathlike : : obj : ` python : bool ` or : obj : ` python : None `
 . . versionadded : : 3.15"""

implementation:
has_pathlike = hasattr ( os , 'PathLike' )
if allow_pathlike is None :
    allow_pathlike = has_pathlike
if allow_pathlike and not has_pathlike :
    raise InvalidArgument ( 'allow_pathlike: os.PathLike not supported, use None instead ' 'to enable it only when available' )
result_type = draw ( sampled_from ( [ bytes , text_type ] ) )
def tp ( s = '' ) :
    return _str_to_path ( s , result_type )
special_component = sampled_from ( [ tp ( os . curdir ) , tp ( os . pardir ) ] )
normal_component = _filename ( result_type )
path_component = one_of ( normal_component , special_component )
extension = normal_component . map ( lambda f : tp ( os . extsep ) + f )
root = _path_root ( result_type )
def optional ( st ) :
    return one_of ( st , just ( result_type ( ) ) )
sep = sampled_from ( [ os . sep , os . altsep or os . sep ] ) . map ( tp )
path_part = builds ( lambda s , l : s . join ( l ) , sep , lists ( path_component ) )
main_strategy = builds ( lambda * x : tp ( ) . join ( x ) , optional ( root ) , path_part , optional ( extension ) )
if allow_pathlike and hasattr ( os , 'fspath' ) :
    pathlike_strategy = main_strategy . map ( lambda p : _PathLike ( p ) )
    main_strategy = one_of ( main_strategy , pathlike_strategy )
return draw ( main_strategy )


signature:
def _exec ( self , globals_dict = None ) :
    """exec compiled code"""

implementation:
globals_dict = globals_dict or { }
globals_dict . setdefault ( '__builtins__' , { } )
exec ( self . _code , globals_dict )
return globals_dict


signature:
def handle_extends ( self , text ) :
    """replace all blocks in extends with current blocks"""

implementation:
match = self . re_extends . match ( text )
if match :
    extra_text = self . re_extends . sub ( '' , text , count = 1 )
    blocks = self . get_blocks ( extra_text )
    path = os . path . join ( self . base_dir , match . group ( 'path' ) )
    with open ( path , encoding = 'utf-8' ) as fp :
        return self . replace_blocks_in_extends ( fp . read ( ) , blocks )
else :
    return None


signature:
def flush_buffer ( self ) :
    """flush all buffered string into code"""

implementation:
self . code_builder . add_line ( '{0}.extend([{1}])' , self . result_var , ',' . join ( self . buffered ) )
self . buffered = [ ]


signature:
def strip_token ( self , text , start , end ) :
    """{ { a } } - > a"""

implementation:
text = text . replace ( start , '' , 1 )
text = text . replace ( end , '' , 1 )
return text


signature:
def run ( self ) :
    """Called by the thread , it runs the process .
 NEVER call this method directly . Instead call start ( ) to start the thread .
 Before finishing the thread using this thread , call join ( )"""

implementation:
queue = Queue ( )
process = UploadProcess ( self . _connection_settings , self . _room , queue , self . _files )
if self . _data :
    process . add_data ( self . _data )
process . start ( )
if not process . is_alive ( ) :
    return
self . _uploading = True
done = False
while not self . _abort and not done :
    if not process . is_alive ( ) :
        self . _abort = True
        break
    messages = None
    try :
        data = queue . get ( )
        if not data :
            done = True
            if self . _finished_callback :
                self . _finished_callback ( )
        elif isinstance ( data , tuple ) :
            sent , total = data
            if self . _progress_callback :
                self . _progress_callback ( sent , total )
        else :
            self . _abort = True
            if self . _error_callback :
                self . _error_callback ( data , self . _room )
    except Empty :
        time . sleep ( 0.5 )
self . _uploading = False
if self . _abort and not process . is_alive ( ) and self . _error_callback :
    self . _error_callback ( Exception ( "Upload process was killed" ) , self . _room )
queue . close ( )
if process . is_alive ( ) :
    queue . close ( )
    process . terminate ( )
process . join ( )


signature:
def add_data ( self , data ) :
    """Add POST data .
 Args :
 data ( dict ) : key = > value dictionary"""

implementation:
if not self . _data :
    self . _data = { }
self . _data . update ( data )


signature:
def run ( self ) :
    """Called by the process , it runs it .
 NEVER call this method directly . Instead call start ( ) to start the separate process .
 If you don ' t want to use a second process , then call fetch ( ) directly on this istance .
 To stop , call terminate ( )"""

implementation:
producer_deferred = defer . Deferred ( )
producer_deferred . addCallback ( self . _request_finished )
producer_deferred . addErrback ( self . _request_error )
receiver_deferred = defer . Deferred ( )
receiver_deferred . addCallback ( self . _response_finished )
receiver_deferred . addErrback ( self . _response_error )
self . _producer = producer . MultiPartProducer ( self . _files , self . _data , callback = self . _request_progress , deferred = producer_deferred )
self . _receiver = receiver . StringReceiver ( receiver_deferred )
headers = { 'Content-Type' : "multipart/form-data; boundary=%s" % self . _producer . boundary }
self . _reactor , request = self . _connection . build_twisted_request ( "POST" , "room/%s/uploads" % self . _room . id , extra_headers = headers , body_producer = self . _producer )
request . addCallback ( self . _response )
request . addErrback ( self . _shutdown )
self . _reactor . run ( )


signature:
def log_error ( self , text : str ) -> None :
    '''Given some error text it will log the text if self . log _ errors is True
 : param text : Error text to log'''

implementation:
if self . log_errors :
    with self . _log_fp . open ( 'a+' ) as log_file :
        log_file . write ( f'{text}\n' )


signature:
def parse_conll ( self , texts : List [ str ] , retry_count : int = 0 ) -> List [ str ] :
    '''Processes the texts using TweeboParse and returns them in CoNLL format .
 : param texts : The List of Strings to be processed by TweeboParse .
 : param retry _ count : The number of times it has retried for . Default
 0 does not require setting , main purpose is for
 recursion .
 : return : A list of CoNLL formated strings .
 : raises ServerError : Caused when the server is not running .
 : raises : py : class : ` requests . exceptions . HTTPError ` : Caused when the
 input texts is not formated correctly e . g . When you give it a
 String not a list of Strings .
 : raises : py : class : ` json . JSONDecodeError ` : Caused if after self . retries
 attempts to parse the data it cannot decode the data .
 : Example :'''

implementation:
post_data = { 'texts' : texts , 'output_type' : 'conll' }
try :
    response = requests . post ( f'http://{self.hostname}:{self.port}' , json = post_data , headers = { 'Connection' : 'close' } )
    response . raise_for_status ( )
except ( requests . exceptions . ConnectionError , requests . exceptions . Timeout ) as server_error :
    raise ServerError ( server_error , self . hostname , self . port )
except requests . exceptions . HTTPError as http_error :
    raise http_error
else :
    try :
        return response . json ( )
    except json . JSONDecodeError as json_exception :
        if retry_count == self . retries :
            self . log_error ( response . text )
            raise Exception ( 'Json Decoding error cannot parse this ' f':\n{response.text}' )
        return self . parse_conll ( texts , retry_count + 1 )


signature:
def set_data ( self , data = { } , datetime_fields = [ ] ) :
    """Set entity data
 Args :
 data ( dict ) : Entity data
 datetime _ fields ( array ) : Fields that should be parsed as datetimes"""

implementation:
if datetime_fields :
    for field in datetime_fields :
        if field in data :
            data [ field ] = self . _parse_datetime ( data [ field ] )
super ( CampfireEntity , self ) . set_data ( data )


signature:
def _parse_datetime ( self , value ) :
    """Parses a datetime string from " YYYY / MM / DD HH : MM : SS + HHMM " format
 Args :
 value ( str ) : String
 Returns :
 datetime . Datetime"""

implementation:
offset = 0
pattern = r"\s+([+-]{1}\d+)\Z"
matches = re . search ( pattern , value )
if matches :
    value = re . sub ( pattern , '' , value )
    offset = datetime . timedelta ( hours = int ( matches . group ( 1 ) ) / 100 )
return datetime . datetime . strptime ( value , "%Y/%m/%d %H:%M:%S" ) - offset


signature:
def validate_xml_text ( text ) :
    """validates XML text"""

implementation:
bad_chars = __INVALID_XML_CHARS & set ( text )
if bad_chars :
    for offset , c in enumerate ( text ) :
        if c in bad_chars :
            raise RuntimeError ( 'invalid XML character: ' + repr ( c ) + ' at offset ' + str ( offset ) )


signature:
def validate_xml_name ( name ) :
    """validates XML name"""

implementation:
if len ( name ) == 0 :
    raise RuntimeError ( 'empty XML name' )
if __INVALID_NAME_CHARS & set ( name ) :
    raise RuntimeError ( 'XML name contains invalid character' )
if name [ 0 ] in __INVALID_NAME_START_CHARS :
    raise RuntimeError ( 'XML name starts with invalid character' )


signature:
def update ( self ) :
    """Calculate what the desired change in velocity is .
 delta _ velocity = acceleration * delta _ time
 Time will be dealt with by the sprite ."""

implementation:
delta_velocity = Vector . null ( )
target_position = self . target . get_position ( )
sprite_position = self . sprite . get_position ( )
desired_direction = target_position - sprite_position
if 0.0 == self . los or desired_direction . magnitude <= self . los :
    try :
        desired_normal = desired_direction . normal
    except NullVectorError :
        desired_normal = Vector . null ( )
    desired_velocity = desired_normal * self . sprite . get_max_speed ( )
    delta_velocity = desired_velocity - self . sprite . get_velocity ( )
self . last_delta_velocity = delta_velocity
return delta_velocity , self . power


signature:
def on_enter_stage ( self ) :
    """Prepare the actors , the world , and the messaging system to begin
 playing the game .
 This method is guaranteed to be called exactly once upon entering the
 game stage ."""

implementation:
with self . world . _unlock_temporarily ( ) :
    self . forum . connect_everyone ( self . world , self . actors )
# 1 . Setup the forum .
self . forum . on_start_game ( )
# 2 . Setup the world .
with self . world . _unlock_temporarily ( ) :
    self . world . on_start_game ( )
# 3 . Setup the actors . Because this is done after the forum and the
# world have been setup , this signals to the actors that they can
# send messages and query the game world as usual .
num_players = len ( self . actors ) - 1
for actor in self . actors :
    actor . on_setup_gui ( self . gui )
for actor in self . actors :
    actor . on_start_game ( num_players )


signature:
def on_update_stage ( self , dt ) :
    """Sequentially update the actors , the world , and the messaging system .
 The theater terminates once all of the actors indicate that they are done ."""

implementation:
for actor in self . actors :
    actor . on_update_game ( dt )
self . forum . on_update_game ( )
with self . world . _unlock_temporarily ( ) :
    self . world . on_update_game ( dt )
if self . world . has_game_ended ( ) :
    self . exit_stage ( )


signature:
def on_exit_stage ( self ) :
    """Give the actors , the world , and the messaging system a chance to react
 to the end of the game ."""

implementation:
# 1 . Let the forum react to the end of the game . Local forums don ' t
# react to this , but remote forums take the opportunity to stop
# trying to extract tokens from messages .
self . forum . on_finish_game ( )
# 2 . Let the actors react to the end of the game .
for actor in self . actors :
    actor . on_finish_game ( )
# 3 . Let the world react to the end of the game .
with self . world . _unlock_temporarily ( ) :
    self . world . on_finish_game ( )


signature:
def tokens_referenced ( self ) :
    """Return a list of all the tokens that are referenced ( i . e . contained in )
 this message . Tokens that haven ' t been assigned an id yet are searched
 recursively for tokens . So this method may return fewer results after
 the message is sent . This information is used by the game engine to
 catch mistakes like forgetting to add a token to the world or keeping a
 stale reference to a token after its been removed ."""

implementation:
tokens = set ( )
# Use the pickle machinery to find all the tokens contained at any
# level of this message . When an object is being pickled , the Pickler
# calls its persistent _ id ( ) method for each object it encounters . We
# hijack this method to add every Token we encounter to a list .
# This definitely feels like a hacky abuse of the pickle machinery , but
# that notwithstanding this should be quite robust and quite fast .
def persistent_id ( obj ) :
    from . tokens import Token
    if isinstance ( obj , Token ) :
        tokens . add ( obj )
        # Recursively descend into tokens that haven ' t been assigned an
        # id yet , but not into tokens that have .
        return obj . id
from pickle import Pickler
from io import BytesIO
# Use BytesIO to basically ignore the serialized data stream , since we
# only care about visiting all the objects that would be pickled .
pickler = Pickler ( BytesIO ( ) )
pickler . persistent_id = persistent_id
pickler . dump ( self )
return tokens


signature:
def wrap_handler ( self , handler , context_switcher ) :
    """Enable / Disable handler ."""

implementation:
context_switcher . add_context_in ( lambda : LOGGER . addHandler ( self . handler ) )
context_switcher . add_context_out ( lambda : LOGGER . removeHandler ( self . handler ) )


signature:
def render_vars ( self ) :
    """Template variables ."""

implementation: return { 'records' : [ { 'message' : record . getMessage ( ) , 'time' : dt . datetime . fromtimestamp ( record . created ) . strftime ( '%H:%M:%S' ) , } for record in self . handler . records ] }


signature:
def init_async ( self , loop = None ) :
    """Use when application is starting ."""

implementation:
self . _loop = loop or asyncio . get_event_loop ( )
self . _async_lock = asyncio . Lock ( loop = loop )
# FIX : SQLITE in memory database
if not self . database == ':memory:' :
    self . _state = ConnectionLocal ( )


signature:
async def async_connect ( self ) :
    """Catch a connection asyncrounosly ."""

implementation:
if self . _async_lock is None :
    raise Exception ( 'Error, database not properly initialized before async connection' )
async with self . _async_lock :
    self . connect ( True )
return self . _state . conn


signature:
def init_async ( self , loop ) :
    """Initialize self ."""

implementation:
super ( PooledAIODatabase , self ) . init_async ( loop )
self . _waiters = collections . deque ( )


signature:
async def async_connect ( self ) :
    """Asyncronously wait for a connection from the pool ."""

implementation:
if self . _waiters is None :
    raise Exception ( 'Error, database not properly initialized before async connection' )
if self . _waiters or self . max_connections and ( len ( self . _in_use ) >= self . max_connections ) :
    waiter = asyncio . Future ( loop = self . _loop )
    self . _waiters . append ( waiter )
    try :
        logger . debug ( 'Wait for connection.' )
        await waiter
    finally :
        self . _waiters . remove ( waiter )
self . connect ( )
return self . _state . conn


signature:
def _close ( self , conn ) :
    """Release waiters ."""

implementation:
super ( PooledAIODatabase , self ) . _close ( conn )
for waiter in self . _waiters :
    if not waiter . done ( ) :
        logger . debug ( 'Release a waiter' )
        waiter . set_result ( True )
        break


signature:
def receive_id_from_server ( self ) :
    """Listen for an id from the server .
 At the beginning of a game , each client receives an IdFactory from the
 server . This factory are used to give id numbers that are guaranteed
 to be unique to tokens that created locally . This method checks to see if such
 a factory has been received . If it hasn ' t , this method does not block
 and immediately returns False . If it has , this method returns True
 after saving the factory internally . At this point it is safe to enter
 the GameStage ."""

implementation:
for message in self . pipe . receive ( ) :
    if isinstance ( message , IdFactory ) :
        self . actor_id_factory = message
        return True
return False


signature:
def execute_sync ( self , message ) :
    """Respond when the server indicates that the client is out of sync .
 The server can request a sync when this client sends a message that
 fails the check ( ) on the server . If the reason for the failure isn ' t
 very serious , then the server can decide to send it as usual in the
 interest of a smooth gameplay experience . When this happens , the
 server sends out an extra response providing the clients with the
 information they need to resync themselves ."""

implementation:
info ( "synchronizing message: {message}" )
# Synchronize the world .
with self . world . _unlock_temporarily ( ) :
    message . _sync ( self . world )
    self . world . _react_to_sync_response ( message )
# Synchronize the tokens .
for actor in self . actors :
    actor . _react_to_sync_response ( message )


signature:
def execute_undo ( self , message ) :
    """Manage the response when the server rejects a message .
 An undo is when required this client sends a message that the server
 refuses to pass on to the other clients playing the game . When this
 happens , the client must undo the changes that the message made to the
 world before being sent or crash . Note that unlike sync requests , undo
 requests are only reported to the client that sent the offending
 message ."""

implementation:
info ( "undoing message: {message}" )
# Roll back changes that the original message made to the world .
with self . world . _unlock_temporarily ( ) :
    message . _undo ( self . world )
    self . world . _react_to_undo_response ( message )
# Give the actors a chance to react to the error . For example , a
# GUI actor might inform the user that there are connectivity
# issues and that their last action was countermanded .
for actor in self . actors :
    actor . _react_to_undo_response ( message )


signature:
def _relay_message ( self , message ) :
    """Relay messages from the forum on the server to the client represented
 by this actor ."""

implementation:
info ( "relaying message: {message}" )
if not message . was_sent_by ( self . _id_factory ) :
    self . pipe . send ( message )
    self . pipe . deliver ( )


signature:
def generate ( request ) :
    """Create a new DataItem ."""

implementation:
models . DataItem . create ( content = '' . join ( random . choice ( string . ascii_uppercase + string . digits ) for _ in range ( 20 ) ) )
return muffin . HTTPFound ( '/' )


signature:
def require_active_token ( object ) :
    """Raise an ApiUsageError if the given object is not a token that is currently
 participating in the game . To be participating in the game , the given
 token must have an id number and be associated with the world ."""

implementation:
require_token ( object )
token = object
if not token . has_id :
    raise ApiUsageError ( """\
                token {token} should have an id, but doesn't.

                This error usually means that a token was added to the world
                without being assigned an id number.  To correct this, make
                sure that you're using a message (i.e. CreateToken) to create
                all of your tokens.""" )
if not token . has_world :
    raise ApiUsageError ( """\
                token {token} (id={token.id}) not in world.

                You can get this error if you try to remove the same token from
                the world twice.  This might happen is you don't get rid of
                every reference to a token after it's removed the first time,
                then later on you try to remove the stale reference.""" )


signature:
def add_safety_checks ( meta , members ) :
    """Iterate through each member of the class being created and add a
 safety check to every method that isn ' t marked as read - only ."""

implementation:
for member_name , member_value in members . items ( ) :
    members [ member_name ] = meta . add_safety_check ( member_name , member_value )


signature:
def watch_method ( self , method_name , callback ) :
    """Register the given callback to be called whenever the method with the
 given name is called . You can easily take advantage of this feature in
 token extensions by using the @ watch _ token decorator ."""

implementation:
# Make sure a token method with the given name exists , and complain if
# nothing is found .
try :
    method = getattr ( self , method_name )
except AttributeError :
    raise ApiUsageError ( """\
                    {self.__class__.__name__} has no such method
                    {method_name}() to watch.

                    This error usually means that you used the @watch_token
                    decorator on a method of a token extension class that
                    didn't match the name of any method in the corresponding
                    token class.  Check for typos.""" )
# Wrap the method in a WatchedMethod object , if that hasn ' t already
# been done . This object manages a list of callback method and takes
# responsibility for calling them after the method itself has been
# called .
if not isinstance ( method , Token . WatchedMethod ) :
    setattr ( self , method_name , Token . WatchedMethod ( method ) )
    method = getattr ( self , method_name )
# Add the given callback to the watched method .
method . add_watcher ( callback )


signature:
def _remove_from_world ( self ) :
    """Clear all the internal data the token needed while it was part of
 the world .
 Note that this method doesn ' t actually remove the token from the
 world . That ' s what World . _ remove _ token ( ) does . This method is just
 responsible for setting the internal state of the token being removed ."""

implementation:
self . on_remove_from_world ( )
self . _extensions = { }
self . _disable_forum_observation ( )
self . _world = None
self . _id = None


signature:
def _unlock_temporarily ( self ) :
    """Allow tokens to modify the world for the duration of a with - block .
 It ' s important that tokens only modify the world at appropriate times ,
 otherwise the changes they make may not be communicated across the
 network to other clients . To help catch and prevent these kinds of
 errors , the game engine keeps the world locked most of the time and
 only briefly unlocks it ( using this method ) when tokens are allowed to
 make changes . When the world is locked , token methods that aren ' t
 marked as being read - only can ' t be called . When the world is unlocked ,
 any token method can be called . These checks can be disabled by
 running python with optimization enabled .
 You should never call this method manually from within your own game .
 This method is intended to be used by the game engine , which was
 carefully designed to allow the world to be modified only when safe .
 Calling this method yourself disables an important safety check ."""

implementation:
if not self . _is_locked :
    yield
else :
    try :
        self . _is_locked = False
        yield
    finally :
        self . _is_locked = True


signature:
def scan ( xml ) :
    """Converts XML tree to event generator"""

implementation:
if xml . tag is et . Comment :
    yield { 'type' : COMMENT , 'text' : xml . text }
    return
if xml . tag is et . PI :
    if xml . text :
        yield { 'type' : PI , 'target' : xml . target , 'text' : xml . text }
    else :
        yield { 'type' : PI , 'target' : xml . target }
    return
obj = _elt2obj ( xml )
obj [ 'type' ] = ENTER
yield obj
assert type ( xml . tag ) is str , xml
if xml . text :
    yield { 'type' : TEXT , 'text' : xml . text }
for c in xml :
    for x in scan ( c ) :
        yield x
    if c . tail :
        yield { 'type' : TEXT , 'text' : c . tail }
yield { 'type' : EXIT }


signature:
def unscan ( events , nsmap = None ) :
    """Converts events stream into lXML tree"""

implementation:
root = None
last_closed_elt = None
stack = [ ]
for obj in events :
    if obj [ 'type' ] == ENTER :
        elt = _obj2elt ( obj , nsmap = nsmap )
        if stack :
            stack [ - 1 ] . append ( elt )
        elif root is not None :
            raise RuntimeError ( 'Event stream tried to create second XML tree' )
        else :
            root = elt
        stack . append ( elt )
        last_closed_elt = None
    elif obj [ 'type' ] == EXIT :
        last_closed_elt = stack . pop ( )
    elif obj [ 'type' ] == COMMENT :
        elt = et . Comment ( obj [ 'text' ] )
        stack [ - 1 ] . append ( elt )
    elif obj [ 'type' ] == PI :
        elt = et . PI ( obj [ 'target' ] )
        if obj . get ( 'text' ) :
            elt . text = obj [ 'text' ]
        stack [ - 1 ] . append ( elt )
    elif obj [ 'type' ] == TEXT :
        text = obj [ 'text' ]
        if text :
            if last_closed_elt is None :
                stack [ - 1 ] . text = ( stack [ - 1 ] . text or '' ) + text
            else :
                last_closed_elt . tail = ( last_closed_elt . tail or '' ) + text
    else :
        assert False , obj
if root is None :
    raise RuntimeError ( 'Empty XML event stream' )
return root


signature:
def parse ( filename ) :
    """Parses file content into events stream"""

implementation:
for event , elt in et . iterparse ( filename , events = ( 'start' , 'end' , 'comment' , 'pi' ) , huge_tree = True ) :
    if event == 'start' :
        obj = _elt2obj ( elt )
        obj [ 'type' ] = ENTER
        yield obj
        if elt . text :
            yield { 'type' : TEXT , 'text' : elt . text }
    elif event == 'end' :
        yield { 'type' : EXIT }
        if elt . tail :
            yield { 'type' : TEXT , 'text' : elt . tail }
        elt . clear ( )
    elif event == 'comment' :
        yield { 'type' : COMMENT , 'text' : elt . text }
    elif event == 'pi' :
        yield { 'type' : PI , 'text' : elt . text }
    else :
        assert False , ( event , elt )


signature:
def subtree ( events ) :
    """selects sub - tree events"""

implementation:
stack = 0
for obj in events :
    if obj [ 'type' ] == ENTER :
        stack += 1
    elif obj [ 'type' ] == EXIT :
        if stack == 0 :
            break
        stack -= 1
    yield obj


signature:
def merge_text ( events ) :
    """merges each run of successive text events into one text event"""

implementation:
text = [ ]
for obj in events :
    if obj [ 'type' ] == TEXT :
        text . append ( obj [ 'text' ] )
    else :
        if text :
            yield { 'type' : TEXT , 'text' : '' . join ( text ) }
            text . clear ( )
        yield obj
if text :
    yield { 'type' : TEXT , 'text' : '' . join ( text ) }


signature:
def with_peer ( events ) :
    """locates ENTER peer for each EXIT object . Convenient when selectively
 filtering out XML markup"""

implementation:
stack = [ ]
for obj in events :
    if obj [ 'type' ] == ENTER :
        stack . append ( obj )
        yield obj , None
    elif obj [ 'type' ] == EXIT :
        yield obj , stack . pop ( )
    else :
        yield obj , None


signature:
def easter ( year ) :
    """This method was ported from the work done by GM Arts ,
 on top of the algorithm by Claus Tondering , which was
 based in part on the algorithm of Ouding ( 1940 ) , as
 quoted in " Explanatory Supplement to the Astronomical
 Almanac " , P . Kenneth Seidelmann , editor .
 More about the algorithm may be found at :
 http : / / users . chariot . net . au / ~ gmarts / eastalg . htm
 and
 http : / / www . tondering . dk / claus / calendar . html"""

implementation:
# g - Golden year - 1
# c - Century
# h - ( 23 - Epact ) mod 30
# i - Number of days from March 21 to Paschal Full Moon
# j - Weekday for PFM ( 0 = Sunday , etc )
# p - Number of days from March 21 to Sunday on or before PFM
# ( - 6 to 28 methods 1 & 3 , to 56 for method 2)
# e - Extra days to add for method 2 ( converting Julian
# date to Gregorian date )
y = year
g = y % 19
e = 0
c = y // 100
h = ( c - c // 4 - ( 8 * c + 13 ) // 25 + 19 * g + 15 ) % 30
i = h - ( h // 28 ) * ( 1 - ( h // 28 ) * ( 29 // ( h + 1 ) ) * ( ( 21 - g ) // 11 ) )
j = ( y + y // 4 + i + 2 - c + c // 4 ) % 7
# p can be from - 6 to 56 corresponding to dates 22 March to 23 May
# ( later dates apply to method 2 , although 23 May never actually occurs )
p = i - j + e
d = 1 + ( p + 27 + ( p + 6 ) // 40 ) % 31
m = 3 + ( p + 26 ) // 30
return BusinessDate . from_ymd ( int ( y ) , int ( m ) , int ( d ) )


signature:
def from_date ( datetime_date ) :
    """construct BusinessDate instance from datetime . date instance ,
 raise ValueError exception if not possible
 : param datetime . date datetime _ date : calendar day
 : return bool :"""

implementation: return BusinessDate . from_ymd ( datetime_date . year , datetime_date . month , datetime_date . day )


signature:
def from_string ( date_str ) :
    """construction from the following string patterns
 ' % Y - % m - % d '
 ' % d . % m . % Y '
 ' % m / % d / % Y '
 ' % Y % m % d '
 : param str date _ str :
 : return BusinessDate :"""

implementation:
if date_str . count ( '-' ) :
    str_format = '%Y-%m-%d'
elif date_str . count ( '.' ) :
    str_format = '%d.%m.%Y'
elif date_str . count ( '/' ) :
    str_format = '%m/%d/%Y'
elif len ( date_str ) == 8 :
    str_format = '%Y%m%d'
elif len ( date_str ) == 4 :
    year = ord ( date_str [ 0 ] ) * 256 + ord ( date_str [ 1 ] )
    month = ord ( date_str [ 2 ] )
    day = ord ( date_str [ 3 ] )
    return BusinessDate . from_ymd ( year , month , day )
else :
    msg = "the date string " + date_str + " has not the right format"
    raise ValueError ( msg )
d = datetime . strptime ( date_str , str_format )
return BusinessDate . from_ymd ( d . year , d . month , d . day )


signature:
def to_date ( self ) :
    """construct datetime . date instance represented calendar date of BusinessDate instance
 : return datetime . date :"""

implementation:
y , m , d = self . to_ymd ( )
return date ( y , m , d )


signature:
def is_businessdate ( in_date ) :
    """checks whether the provided date is a date
 : param BusinessDate , int or float in _ date :
 : return bool :"""

implementation:
# Note : if the data range has been created from pace _ xl , then all the dates are bank dates
# and here it remains to check the validity .
# ! ! ! However , if the data has been read from json string via json . load ( ) function
# it does not recognize that this numbers are bankdates , just considers them as integers
# therefore , additional check is useful here , first to convert the date if it is integer to BusinessDate ,
# then check the validity .
# ( as the parameter to this method should always be a BusinessDate )
if not isinstance ( in_date , BaseDate ) :
    try : # to be removed
        in_date = BusinessDate ( in_date )
    except :
        return False
y , m , d , = in_date . to_ymd ( )
return is_valid_ymd ( y , m , d )


signature:
def is_business_day ( self , holiday_obj = None ) :
    """: param list holiday _ obj : datetime . date list defining business holidays
 : return : bool
 method to check if a date falls neither on weekend nor is holiday"""

implementation:
y , m , d = BusinessDate . to_ymd ( self )
if weekday ( y , m , d ) > FRIDAY :
    return False
holiday_list = holiday_obj if holiday_obj is not None else DEFAULT_HOLIDAYS
if self in holiday_list :
    return False
elif date ( y , m , d ) in holiday_list :
    return False
return True


signature:
def add_period ( self , p , holiday_obj = None ) :
    """addition of a period object
 : param BusinessDate d :
 : param p :
 : type p : BusinessPeriod or str
 : param list holiday _ obj :
 : return bankdate :"""

implementation:
if isinstance ( p , ( list , tuple ) ) :
    return [ BusinessDate . add_period ( self , pd ) for pd in p ]
elif isinstance ( p , str ) :
    period = BusinessPeriod ( p )
else :
    period = p
res = self
res = BusinessDate . add_months ( res , period . months )
res = BusinessDate . add_years ( res , period . years )
res = BusinessDate . add_days ( res , period . days )
if period . businessdays :
    if holiday_obj :
        res = BusinessDate . add_business_days ( res , period . businessdays , holiday_obj )
    else :
        res = BusinessDate . add_business_days ( res , period . businessdays , period . holiday )
return res


signature:
def add_months ( self , month_int ) :
    """addition of a number of months
 : param BusinessDate d :
 : param int month _ int :
 : return bankdate :"""

implementation:
month_int += self . month
while month_int > 12 :
    self = BusinessDate . add_years ( self , 1 )
    month_int -= 12
while month_int < 1 :
    self = BusinessDate . add_years ( self , - 1 )
    month_int += 12
l = monthrange ( self . year , month_int ) [ 1 ]
return BusinessDate . from_ymd ( self . year , month_int , min ( l , self . day ) )


signature:
def add_business_days ( self , days_int , holiday_obj = None ) :
    """private method for the addition of business days , used in the addition of a BusinessPeriod only
 : param BusinessDate d :
 : param int days _ int :
 : param list holiday _ obj :
 : return : BusinessDate"""

implementation:
res = self
if days_int >= 0 :
    count = 0
    while count < days_int :
        res = BusinessDate . add_days ( res , 1 )
        if BusinessDate . is_business_day ( res , holiday_obj ) :
            count += 1
else :
    count = 0
    while count > days_int :
        res = BusinessDate . add_days ( res , - 1 )
        if BusinessDate . is_business_day ( res , holiday_obj ) :
            count -= 1
return res


signature:
def diff ( self , end_date ) :
    """difference expressed as a tuple of years , months , days
 ( see also the python lib dateutils . relativedelta )
 : param BusinessDate start _ date :
 : param BusinessDate end _ date :
 : return ( int , int , int ) :"""

implementation:
if end_date < self :
    y , m , d = BusinessDate . diff ( end_date , self )
    return - y , - m , - d
y = end_date . year - self . year
m = end_date . month - self . month
while m < 0 :
    y -= 1
    m += 12
while m > 12 :
    y += 1
    m -= 12
s = BusinessDate . add_years ( BusinessDate . add_months ( self , m ) , y )
d = BusinessDate . diff_in_days ( s , end_date )
if d < 0 :
    m -= 1
    if m < 0 :
        y -= 1
        m += 12
    s = BusinessDate . add_years ( BusinessDate . add_months ( self , m ) , y )
d = BusinessDate . diff_in_days ( s , end_date )
return - int ( y ) , - int ( m ) , - int ( d )


signature:
def get_30_360 ( self , end ) :
    """implements 30/360 Day Count Convention ( 4.16 ( f ) 2006 ISDA Definitions )"""

implementation:
start_day = min ( self . day , 30 )
end_day = 30 if ( start_day == 30 and end . day == 31 ) else end . day
return ( 360 * ( end . year - self . year ) + 30 * ( end . month - self . month ) + ( end_day - start_day ) ) / 360.0


signature:
def get_act_act ( self , end ) :
    """implements Act / Act day count convention ( 4.16 ( b ) 2006 ISDA Definitions )"""

implementation:
# split end - self in year portions
# if the period does not lie within a year split the days in the period as following :
# restdays of start year / years in between / days in the end year
# REMARK : following the affore mentioned ISDA Definition the first day of the period is included whereas the
# last day will be excluded
# What remains to check now is only whether the start and end year are leap or non - leap years . The quotients
# can be easily calculated and for the years in between they are always one ( 365/365 = 1 ; 366/366 = 1)
if end . year - self . year == 0 :
    if BusinessDate . is_leap_year ( self . year ) :
        return BusinessDate . diff_in_days ( self , end ) / 366.0
        # leap year : 366 days
    else : # return BusinessDate . diff _ in _ days ( self , end ) / 366.0
        return BusinessDate . diff_in_days ( self , end ) / 365.0
        # non - leap year : 365 days
else :
    rest_year1 = BusinessDate . diff_in_days ( self , BusinessDate ( date ( self . year , 12 , 31 ) ) ) + 1
    # since the first day counts
    rest_year2 = abs ( BusinessDate . diff_in_days ( end , BusinessDate ( date ( end . year , 1 , 1 ) ) ) )
    # here the last day is automatically not counted
    years_in_between = end . year - self . year - 1
    return years_in_between + rest_year1 / ( 366.0 if is_leap_year ( self . year ) else 365.0 ) + rest_year2 / ( 366.0 if is_leap_year ( end . year ) else 365.0 )


signature:
def get_30E_360 ( self , end ) :
    """implements the 30E / 360 Day Count Convention ( 4.16 ( g ) 2006 ISDA Definitons )"""

implementation:
y1 , m1 , d1 = self . to_ymd ( )
# adjust to date immediately following the the last day
y2 , m2 , d2 = end . add_days ( 0 ) . to_ymd ( )
d1 = min ( d1 , 30 )
d2 = min ( d2 , 30 )
return ( 360 * ( y2 - y1 ) + 30 * ( m2 - m1 ) + ( d2 - d1 ) ) / 360.0


signature:
def get_30E_360_ISDA ( self , end ) :
    """implements the 30E / 360 ( ISDA ) Day Count Convention ( 4.16 ( h ) 2006 ISDA Definitions )
 : param end :
 : return :"""

implementation:
y1 , m1 , d1 = self . to_ymd ( )
# ajdust to date immediately following the last day
y2 , m2 , d2 = end . add_days ( 0 ) . to_ymd ( )
if ( m1 == 2 and d1 >= 28 ) or d1 == 31 :
    d1 = 30
if ( m2 == 2 and d2 >= 28 ) or d2 == 31 :
    d2 = 30
return ( 360 * ( y2 - y1 ) + 30 * ( m2 - m1 ) + ( d2 - d1 ) ) / 360.0


signature:
def adjust_previous ( self , holidays_obj = None ) :
    """adjusts to Business Day Convention " Preceding " ( 4.12 ( a ) ( iii ) 2006 ISDA Definitions ) ."""

implementation:
while not BusinessDate . is_business_day ( self , holidays_obj ) :
    self = BusinessDate . add_days ( self , - 1 )
return self


signature:
def adjust_follow ( self , holidays_obj = None ) :
    """adjusts to Business Day Convention " Following " ( 4.12 ( a ) ( i ) 2006 ISDA Definitions ) ."""

implementation:
while not BusinessDate . is_business_day ( self , holidays_obj ) :
    self = BusinessDate . add_days ( self , 1 )
return self


signature:
def adjust_mod_follow ( self , holidays_obj = None ) :
    """adjusts to Business Day Convention " Modified [ Following ] " ( 4.12 ( a ) ( ii ) 2006 ISDA Definitions ) ."""

implementation:
month = self . month
new = BusinessDate . adjust_follow ( self , holidays_obj )
if month != new . month :
    new = BusinessDate . adjust_previous ( self , holidays_obj )
self = new
return self


signature:
def adjust_mod_previous ( self , holidays_obj = None ) :
    """ajusts to Business Day Convention " Modified Preceding " ( not in 2006 ISDA Definitons ) ."""

implementation:
month = self . month
new = BusinessDate . adjust_previous ( self , holidays_obj )
if month != new . month :
    new = BusinessDate . adjust_follow ( self , holidays_obj )
self = new
return self


signature:
def is_businessperiod ( cls , in_period ) :
    """: param in _ period : object to be checked
 : type in _ period : object , str , timedelta
 : return : True if cast works
 : rtype : Boolean
 checks is argument con becasted to BusinessPeriod"""

implementation:
try : # to be removed
    if str ( in_period ) . upper ( ) == '0D' :
        return True
    else :
        p = BusinessPeriod ( str ( in_period ) )
        return not ( p . days == 0 and p . months == 0 and p . years == 0 and p . businessdays == 0 )
except :
    return False


signature:
def quoted ( parser = any_token ) :
    """Parses as much as possible until it encounters a matching closing quote .
 By default matches any _ token , but can be provided with a more specific parser if required .
 Returns a string"""

implementation:
quote_char = quote ( )
value , _ = many_until ( parser , partial ( one_of , quote_char ) )
return build_string ( value )


signature:
def days_in_month ( year , month ) :
    """returns number of days for the given year and month
 : param int year : calendar year
 : param int month : calendar month
 : return int :"""

implementation:
eom = _days_per_month [ month - 1 ]
if is_leap_year ( year ) and month == 2 :
    eom += 1
return eom


signature:
def is_valid_ymd ( year , month , day ) :
    """return True if ( year , month , day ) can be represented in Excel - notation
 ( number of days since 30.12.1899 ) for calendar days , otherwise False
 : param int year : calendar year
 : param int month : calendar month
 : param int day : calendar day
 : return bool :"""

implementation: return 1 <= month <= 12 and 1 <= day <= days_in_month ( year , month ) and year >= 1899


signature:
def from_excel_to_ymd ( excel_int ) :
    """converts date in Microsoft Excel representation style and returns ` ( year , month , day ) ` tuple
 : param int excel _ int : date as int ( days since 1899-12-31)
 : return tuple ( int , int , int ) :"""

implementation:
int_date = int ( floor ( excel_int ) )
int_date -= 1 if excel_int > 60 else 0
# jan dingerkus : There are two errors in excels own date < > int conversion .
# The first is that there exists the 00.01.1900 and the second that there never happend to be a 29.2.1900 since it
# was no leap year . So there is the int 60 < > 29.2.1900 which has to be jumped over .
year = ( int_date - 1 ) // 365
rest_days = int_date - 365 * year - ( year + 3 ) // 4 + ( year + 99 ) // 100 - ( year + 299 ) // 400
year += 1900
while rest_days <= 0 :
    year -= 1
    rest_days += days_in_year ( year )
month = 1
if is_leap_year ( year ) and rest_days == 60 :
    month = 2
    day = 29
else :
    if is_leap_year ( year ) and rest_days > 60 :
        rest_days -= 1
    while rest_days > _cum_month_days [ month ] :
        month += 1
    day = rest_days - _cum_month_days [ month - 1 ]
return year , month , day


signature:
def from_ymd_to_excel ( year , month , day ) :
    """converts date as ` ( year , month , day ) ` tuple into Microsoft Excel representation style
 : param tuple ( int , int , int ) : int tuple ` year , month , day `
 : return int :"""

implementation:
if not is_valid_ymd ( year , month , day ) :
    raise ValueError ( "Invalid date {0}.{1}.{2}" . format ( year , month , day ) )
days = _cum_month_days [ month - 1 ] + day
days += 1 if ( is_leap_year ( year ) and month > 2 ) else 0
years_distance = year - 1900
days += years_distance * 365 + ( years_distance + 3 ) // 4 - ( years_distance + 99 ) // 100 + ( years_distance + 299 ) // 400
# count days since 30.12.1899 ( excluding 30.12.1899 ) ( workaround for excel bug )
days += 1 if ( year , month , day ) > ( 1900 , 2 , 28 ) else 0
return days


signature:
def add_years ( d , years_int ) :
    """adds number of years to a date
 : param BaseDateFloat d : date to add years to
 : param int years _ int : number of years to add
 : return BaseDate : resulting date"""

implementation:
y , m , d = BaseDate . to_ymd ( d )
if not is_leap_year ( years_int ) and m == 2 :
    d = min ( 28 , d )
return BaseDateFloat . from_ymd ( y + years_int , m , d )


signature:
def add_days ( d , days_int ) :
    """addition of a number of days
 : param BaseDateDatetimeDate d :
 : param int days _ int :
 : return BaseDatetimeDate :"""

implementation:
n = date ( d . year , d . month , d . day ) + timedelta ( days_int )
return BaseDateDatetimeDate ( n . year , n . month , n . day )


signature:
def add_years ( d , years_int ) :
    """addition of a number of years
 : param BaseDateDatetimeDate d :
 : param int years _ int :
 : return BaseDatetimeDate :"""

implementation:
y , m , d = BaseDateDatetimeDate . to_ymd ( d )
y += years_int
if not is_leap_year ( y ) and m == 2 :
    d = min ( 28 , d )
return BaseDateDatetimeDate . from_ymd ( y , m , d )


signature:
def diff_in_days ( start , end ) :
    """calculate difference between given dates in days
 : param BaseDateDatetimeDate start : state date
 : param BaseDateDatetimeDate end : end date
 : return float : difference between end date and start date in days"""

implementation:
diff = date ( end . year , end . month , end . day ) - date ( start . year , start . month , start . day )
return float ( diff . days )


signature:
def add_days ( date_obj , days_int ) :
    """addition of a number of days
 : param BaseDateTuple d :
 : param int days _ int :
 : return BaseDatetimeDate :"""

implementation:
n = from_ymd_to_excel ( * date_obj . date ) + days_int
return BaseDateTuple ( * from_excel_to_ymd ( n ) )


signature:
def add_years ( date_obj , years_int ) :
    """addition of a number of years
 : param BaseDateTuple d :
 : param int years _ int :
 : return BaseDatetimeDate :"""

implementation:
y , m , d = BaseDateTuple . to_ymd ( date_obj )
y += years_int
if not is_leap_year ( y ) and m == 2 :
    d = min ( 28 , d )
return BaseDateTuple . from_ymd ( y , m , d )


signature:
def diff_in_days ( start , end ) :
    """calculate difference between given dates in days
 : param BaseDateTuple start : state date
 : param BaseDateTuple end : end date
 : return float : difference between end date and start date in days"""

implementation:
diff = from_ymd_to_excel ( * end . date ) - from_ymd_to_excel ( * start . date )
return float ( diff )


signature:
def startup ( self , app ) :
    """Register connection ' s middleware and prepare self database ."""

implementation:
self . database . init_async ( app . loop )
if not self . cfg . connection_manual :
    app . middlewares . insert ( 0 , self . _middleware )


signature:
def cleanup ( self , app ) :
    """Close all connections ."""

implementation:
if hasattr ( self . database . obj , 'close_all' ) :
    self . database . close_all ( )


signature:
def register ( self , model ) :
    """Register a model in self ."""

implementation:
self . models [ model . _meta . table_name ] = model
model . _meta . database = self . database
return model


signature:
async def manage ( self ) :
    """Manage a database connection ."""

implementation:
cm = _ContextManager ( self . database )
if isinstance ( self . database . obj , AIODatabase ) :
    cm . connection = await self . database . async_connect ( )
else :
    cm . connection = self . database . connect ( )
return cm


signature:
def migrate ( migrator , database , ** kwargs ) :
    """Write your migrations here .
 > Model = migrator . orm [ ' name ' ]
 > migrator . sql ( sql )
 > migrator . create _ table ( Model )
 > migrator . drop _ table ( Model , cascade = True )
 > migrator . add _ columns ( Model , * * fields )
 > migrator . change _ columns ( Model , * * fields )
 > migrator . drop _ columns ( Model , * field _ names , cascade = True )
 > migrator . rename _ column ( Model , old _ field _ name , new _ field _ name )
 > migrator . rename _ table ( Model , new _ table _ name )
 > migrator . add _ index ( Model , * col _ names , unique = False )
 > migrator . drop _ index ( Model , index _ name )
 > migrator . add _ not _ null ( Model , field _ name )
 > migrator . drop _ not _ null ( Model , field _ name )
 > migrator . add _ default ( Model , field _ name , default )"""

implementation:
@ migrator . create_table
class DataItem ( pw . Model ) :
    created = pw . DateTimeField ( default = dt . datetime . utcnow )
    content = pw . CharField ( )


signature:
def chain ( * args ) :
    """Runs a series of parsers in sequence passing the result of each parser to the next .
 The result of the last parser is returned ."""

implementation:
def chain_block ( * args , ** kwargs ) :
    v = args [ 0 ] ( * args , ** kwargs )
    for p in args [ 1 : ] :
        v = p ( v )
    return v
return chain_block


signature:
def one_of ( these ) :
    """Returns the current token if is found in the collection provided .
 Fails otherwise ."""

implementation:
ch = peek ( )
try :
    if ( ch is EndOfFile ) or ( ch not in these ) :
        fail ( list ( these ) )
except TypeError :
    if ch != these :
        fail ( [ these ] )
next ( )
return ch


signature:
def not_one_of ( these ) :
    """Returns the current token if it is not found in the collection provided .
 The negative of one _ of ."""

implementation:
ch = peek ( )
desc = "not_one_of" + repr ( these )
try :
    if ( ch is EndOfFile ) or ( ch in these ) :
        fail ( [ desc ] )
except TypeError :
    if ch != these :
        fail ( [ desc ] )
next ( )
return ch


signature:
def satisfies ( guard ) :
    """Returns the current token if it satisfies the guard function provided .
 Fails otherwise .
 This is the a generalisation of one _ of ."""

implementation:
i = peek ( )
if ( i is EndOfFile ) or ( not guard ( i ) ) :
    fail ( [ "<satisfies predicate " + _fun_to_str ( guard ) + ">" ] )
next ( )
return i


signature:
def not_followed_by ( parser ) :
    """Succeeds if the given parser cannot consume input"""

implementation:
@ tri
def not_followed_by_block ( ) :
    failed = object ( )
    result = optional ( tri ( parser ) , failed )
    if result != failed :
        fail ( [ "not " + _fun_to_str ( parser ) ] )
choice ( not_followed_by_block )


signature:
def many ( parser ) :
    """Applies the parser to input zero or more times .
 Returns a list of parser results ."""

implementation:
results = [ ]
terminate = object ( )
while local_ps . value :
    result = optional ( parser , terminate )
    if result == terminate :
        break
    results . append ( result )
return results


signature:
def many_until ( these , term ) :
    """Consumes as many of these as it can until it term is encountered .
 Returns a tuple of the list of these results and the term result"""

implementation:
results = [ ]
while True :
    stop , result = choice ( _tag ( True , term ) , _tag ( False , these ) )
    if stop :
        return results , result
    else :
        results . append ( result )


signature:
def many_until1 ( these , term ) :
    """Like many _ until but must consume at least one of these ."""

implementation:
first = [ these ( ) ]
these_results , term_result = many_until ( these , term )
return ( first + these_results , term_result )


signature:
def sep1 ( parser , separator ) :
    """Like sep but must consume at least one of parser ."""

implementation:
first = [ parser ( ) ]
def inner ( ) :
    separator ( )
    return parser ( )
return first + many ( tri ( inner ) )


signature:
def string ( string ) :
    """Iterates over string , matching input to the items provided .
 The most obvious usage of this is to accept an entire string of characters ,
 However this is function is more general than that . It takes an iterable
 and for each item , it tries one _ of for that set . For example ,
 string ( [ ' aA ' , ' bB ' , ' cC ' ] )
 will accept ' abc ' in either case .
 note , If you wish to match caseless strings as in the example , use
 picoparse . text . caseless _ string ."""

implementation:
found = [ ]
for c in string :
    found . append ( one_of ( c ) )
return found


signature:
def seq ( * sequence ) :
    """Runs a series of parsers in sequence optionally storing results in a returned dictionary .
 For example :
 seq ( whitespace , ( ' phone ' , digits ) , whitespace , ( ' name ' , remaining ) )"""

implementation:
results = { }
for p in sequence :
    if callable ( p ) :
        p ( )
        continue
    k , v = p
    results [ k ] = v ( )
return results


signature:
def _fill ( self , size ) :
    """fills the internal buffer from the source iterator"""

implementation:
try :
    for i in range ( size ) :
        self . buffer . append ( self . source . next ( ) )
except StopIteration :
    self . buffer . append ( ( EndOfFile , EndOfFile ) )
self . len = len ( self . buffer )


signature:
def next ( self ) :
    """Advances to and returns the next token or returns EndOfFile"""

implementation:
self . index += 1
t = self . peek ( )
if not self . depth :
    self . _cut ( )
return t


signature:
def current ( self ) :
    """Returns the current ( token , position ) or ( EndOfFile , EndOfFile )"""

implementation:
if self . index >= self . len :
    self . _fill ( ( self . index - self . len ) + 1 )
return self . index < self . len and self . buffer [ self . index ] or ( EndOfFile , EndOfFile )


signature:
def main ( world_cls , referee_cls , gui_cls , gui_actor_cls , ai_actor_cls , theater_cls = PygletTheater , default_host = DEFAULT_HOST , default_port = DEFAULT_PORT , argv = None ) :
    """Run a game being developed with the kxg game engine .
 Usage :
 { exe _ name } sandbox [ < num _ ais > ] [ - v . . . ]
 { exe _ name } client [ - - host HOST ] [ - - port PORT ] [ - v . . . ]
 { exe _ name } server < num _ guis > [ < num _ ais > ] [ - - host HOST ] [ - - port PORT ] [ - v . . . ]
 { exe _ name } debug < num _ guis > [ < num _ ais > ] [ - - host HOST ] [ - - port PORT ] [ - v . . . ]
 { exe _ name } - - help
 Commands :
 sandbox
 Play a single - player game with the specified number of AIs . None of
 the multiplayer machinery will be used .
 client
 Launch a client that will try to connect to a server on the given host
 and port . Once it connects and the game starts , the client will allow
 you to play the game against any other connected clients .
 server
 Launch a server that will manage a game between the given number of
 human and AI players . The human players must connect using this
 command ' s client mode .
 debug
 Debug a multiplayer game locally . This command launches a server and
 the given number of clients all in different processes , and configures
 the logging system such that the output from each process can be easily
 distinguished .
 Arguments :
 < num _ guis >
 The number of human players that will be playing the game . Only needed
 by commands that will launch some sort of multiplayer server .
 < num _ ais >
 The number of AI players that will be playing the game . Only needed by
 commands that will launch single - player games or multiplayer servers .
 Options :
 - x - - host HOST [ default : { default _ host } ]
 The address of the machine running the server . Must be accessible from
 the machines running the clients .
 - p - - port PORT [ default : { default _ port } ]
 The port that the server should listen on . Don ' t specify a value less
 than 1024 unless the server is running with root permissions .
 - v - - verbose
 Have the game engine log more information about what it ' s doing . You
 can specify this option several times to get more and more information .
 This command is provided so that you can start writing your game with the least
 possible amount of boilerplate code . However , the clients and servers provided
 by this command are not capable of running a production game . Once you have
 written your game and want to give it a polished set of menus and options ,
 you ' ll have to write new Stage subclasses encapsulating that logic and you ' ll
 have to call those stages yourself by interacting more directly with the
 Theater class . The online documentation has more information on this process ."""

implementation:
import sys , os , docopt , nonstdlib
exe_name = os . path . basename ( sys . argv [ 0 ] )
usage = main . __doc__ . format ( ** locals ( ) ) . strip ( )
args = docopt . docopt ( usage , argv or sys . argv [ 1 : ] )
num_guis = int ( args [ '<num_guis>' ] or 1 )
num_ais = int ( args [ '<num_ais>' ] or 0 )
host , port = args [ '--host' ] , int ( args [ '--port' ] )
logging . basicConfig ( format = '%(levelname)s: %(name)s: %(message)s' , level = nonstdlib . verbosity ( args [ '--verbose' ] ) , )
# Use the given game objects and command line arguments to play a game !
if args [ 'debug' ] :
    print ( """\
****************************** KNOWN BUG WARNING ******************************
In debug mode, every message produced by the logging system gets printed twice.
I know vaguely why this is happening, but as of yet I've not been able to fix
it.  In the mean time, don't let this confuse you!
*******************************************************************************""" )
    game = MultiplayerDebugger ( world_cls , referee_cls , gui_cls , gui_actor_cls , num_guis , ai_actor_cls , num_ais , theater_cls , host , port )
else :
    game = theater_cls ( )
    ai_actors = [ ai_actor_cls ( ) for i in range ( num_ais ) ]
    if args [ 'sandbox' ] :
        game . gui = gui_cls ( )
        game . initial_stage = UniplayerGameStage ( world_cls ( ) , referee_cls ( ) , gui_actor_cls ( ) , ai_actors )
        game . initial_stage . successor = PostgameSplashStage ( )
    if args [ 'client' ] :
        game . gui = gui_cls ( )
        game . initial_stage = ClientConnectionStage ( world_cls ( ) , gui_actor_cls ( ) , host , port )
    if args [ 'server' ] :
        game . initial_stage = ServerConnectionStage ( world_cls ( ) , referee_cls ( ) , num_guis , ai_actors , host , port )
game . play ( )


signature:
def _run_supervisor ( self ) :
    """Poll the queues that the worker can use to communicate with the
 supervisor , until all the workers are done and all the queues are
 empty . Handle messages as they appear ."""

implementation:
import time
still_supervising = lambda : ( multiprocessing . active_children ( ) or not self . log_queue . empty ( ) or not self . exception_queue . empty ( ) )
try :
    while still_supervising ( ) : # When a log message is received , make a logger with the same
    # name in this process and use it to re - log the message . It
    # will get handled in this process .
        try :
            record = self . log_queue . get_nowait ( )
            logger = logging . getLogger ( record . name )
            logger . handle ( record )
        except queue . Empty :
            pass
        # When an exception is received , immediately re - raise it .
        try :
            exception = self . exception_queue . get_nowait ( )
        except queue . Empty :
            pass
        else :
            raise exception
        # Sleep for a little bit , and make sure that the workers haven ' t
        # outlived their time limit .
        time . sleep ( 1 / self . frame_rate )
        self . elapsed_time += 1 / self . frame_rate
        if self . time_limit and self . elapsed_time > self . time_limit :
            raise RuntimeError ( "timeout" )
# Make sure the workers don ' t outlive the supervisor , no matter how the
# polling loop ended ( e . g . normal execution or an exception ) .
finally :
    for process in multiprocessing . active_children ( ) :
        process . terminate ( )


signature:
def field_type ( self ) :
    """Return database field type ."""

implementation:
if not self . model :
    return 'JSON'
database = self . model . _meta . database
if isinstance ( database , Proxy ) :
    database = database . obj
if Json and isinstance ( database , PostgresqlDatabase ) :
    return 'JSON'
return 'TEXT'


signature:
def python_value ( self , value ) :
    """Parse value from database ."""

implementation:
if self . field_type == 'TEXT' and isinstance ( value , str ) :
    return self . loads ( value )
return value