Пример #1
0
    def retraceApi(self, api):
        print '''
static HINSTANCE g_hDll = NULL;

static PROC
__getPublicProcAddress(LPCSTR lpProcName)
{
    if (!g_hDll) {
        char szDll[MAX_PATH] = {0};
        
        if (!GetSystemDirectoryA(szDll, MAX_PATH)) {
            return NULL;
        }
        
        strcat(szDll, "\\\\%s");
        
        g_hDll = LoadLibraryA(szDll);
        if (!g_hDll) {
            return NULL;
        }
    }
        
    return GetProcAddress(g_hDll, lpProcName);
}

''' % api.name

        dispatcher = Dispatcher()
        dispatcher.dispatch_api(api)

        Retracer.retraceApi(self, api)
Пример #2
0
    def dispatchModule(self, module):
        tag = module.name.upper()
        print(r'const char *g_sz%sDllName = NULL;' % (tag, ))
        print(r'HMODULE g_h%sModule = NULL;' % (tag, ))
        print(r'')
        print(r'static PROC')
        print(r'_get%sProcAddress(LPCSTR lpProcName) {' % tag)
        print(r'    if (!g_h%sModule) {' % tag)
        print(r'        if (g_sz%sDllName) {' % tag)
        print(r'            g_h%sModule = LoadLibraryA(g_sz%sDllName);' %
              (tag, tag))
        print(r'            if (!g_h%sModule) {' % tag)
        print(
            r'                os::log("warning: failed to load %%s\n", g_sz%sDllName);'
            % tag)
        print(r'            }')
        print(r'        }')
        print(r'        if (!g_h%sModule) {' % tag)
        print(r'            g_h%sModule = LoadLibraryA("%s.dll");' %
              (tag, module.name))
        print(r'        }')
        print(r'        if (!g_h%sModule) {' % tag)
        print(r'            os::log("error: failed to load %s.dll\n");' %
              module.name)
        print(r'            exit(1);')
        print(r'        }')
        print(r'    }')
        print(r'    return GetProcAddress(g_h%sModule, lpProcName);' % tag)
        print(r'}')
        print(r'')

        Dispatcher.dispatchModule(self, module)
Пример #3
0
    def dispatchModule(self, module):
        tag = module.name.upper()
        print r'const char *g_sz%sDllName = NULL;' % (tag,)
        print r'HMODULE g_h%sModule = NULL;' % (tag,)
        print r''
        print r'static PROC'
        print r'_get%sProcAddress(LPCSTR lpProcName) {' % tag
        print r'    if (!g_h%sModule) {' % tag
        print r'        if (g_sz%sDllName) {' % tag
        print r'            g_h%sModule = LoadLibraryA(g_sz%sDllName);' % (tag, tag)
        print r'            if (!g_h%sModule) {' % tag
        print r'                os::log("warning: failed to load %%s\n", g_sz%sDllName);' % tag 
        print r'            }'
        print r'        }'
        print r'        if (!g_h%sModule) {' % tag
        print r'            g_h%sModule = LoadLibraryA("%s.dll");' % (tag, module.name)
        print r'        }'
        print r'        if (!g_h%sModule) {' % tag
        print r'            os::log("error: failed to load %s.dll\n");' % module.name
        print r'            exit(1);'
        print r'        }'
        print r'    }'
        print r'    return GetProcAddress(g_h%sModule, lpProcName);' % tag
        print r'}'
        print r''

        Dispatcher.dispatchModule(self, module)
Пример #4
0
 def _log_all_events(self, dispatcher: dispatch.Dispatcher) -> None:
     """Bind to all of `dispatcher`'s emitted events to log them."""
     dispatcher.bind(
         **{
             event_name: self._create_event_logger(event_name)
             for event_name in dispatcher.EVENTS
         })
Пример #5
0
    def header(self, api):
        print '''
static HINSTANCE g_hDll = NULL;

static PROC
__getPublicProcAddress(LPCSTR lpProcName)
{
    if (!g_hDll) {
        char szDll[MAX_PATH] = {0};
        
        if (!GetSystemDirectoryA(szDll, MAX_PATH)) {
            return NULL;
        }
        
        strcat(szDll, "\\\\%s");
        
        g_hDll = LoadLibraryA(szDll);
        if (!g_hDll) {
            return NULL;
        }
    }
        
    return GetProcAddress(g_hDll, lpProcName);
}

#define __abort() OS::Abort()
''' % self.dllname

        dispatcher = Dispatcher()
        dispatcher.dispatch_api(api)

        Tracer.header(self, api)
Пример #6
0
    def header(self, api):
        print '''
static HINSTANCE g_hDll = NULL;

static PROC
__getPublicProcAddress(LPCSTR lpProcName)
{
    if (!g_hDll) {
        char szDll[MAX_PATH] = {0};
        
        if (!GetSystemDirectoryA(szDll, MAX_PATH)) {
            return NULL;
        }
        
        strcat(szDll, "\\\\%s");
        
        g_hDll = LoadLibraryA(szDll);
        if (!g_hDll) {
            return NULL;
        }
    }
        
    return GetProcAddress(g_hDll, lpProcName);
}

''' % self.dllname

        dispatcher = Dispatcher()
        dispatcher.dispatch_api(api)

        Tracer.header(self, api)
Пример #7
0
    def failFunction(self, function):
        # We fake this when they are not available
        if function.name in ('glGetObjectLabel', 'glGetObjectPtrLabel',
                             'glGetObjectLabelEXT'):
            print r'    if (length != 0) *length = 0;'
            print r'    if (label != 0 && bufSize > 0) *label = 0;'
            return
        if function.name in ('glGetDebugMessageLog',
                             'glGetDebugMessageLogARB'):
            print r'    if (sources != 0) *sources = 0;'
            print r'    if (types != 0) *types = 0;'
            print r'    if (ids != 0) *ids = 0;'
            print r'    if (severities != 0) *severities = 0;'
            print r'    if (lengths != 0) *lengths = 0;'
            print r'    if (messageLog != 0 && bufsize > 0) *messageLog = 0;'
            return
        if function.name in ('glGetDebugMessageLogAMD'):
            print r'    if (categories != 0) *categories = 0;'
            print r'    if (ids != 0) *ids = 0;'
            print r'    if (severities != 0) *severities = 0;'
            print r'    if (lengths != 0) *lengths = 0;'
            print r'    if (message != 0 && bufsize > 0) *message = 0;'
            return

        Dispatcher.failFunction(self, function)
Пример #8
0
    def dispatchApi(self, api):
        tag = api.name.upper()
        print r'const char *g_sz%sDllName = NULL;' % (tag, )
        print r'HMODULE g_h%sModule = NULL;' % (tag, )
        print r''
        print r'static PROC'
        print r'_getPublicProcAddress(LPCSTR lpProcName) {'
        print r'    if (!g_h%sModule) {' % tag
        print r'        if (g_sz%sDllName) {' % tag
        print r'            g_h%sModule = LoadLibraryA(g_sz%sDllName);' % (tag,
                                                                           tag)
        print r'            if (!g_h%sModule) {' % tag
        print r'                os::log("warning: failed to load %%s\n", g_sz%sDllName);' % tag
        print r'            }'
        print r'        }'
        print r'        if (!g_h%sModule) {' % tag
        print r'            g_h%sModule = LoadLibraryA("%s.dll");' % (tag,
                                                                      api.name)
        print r'        }'
        print r'        if (!g_h%sModule) {' % tag
        print r'            os::log("error: failed to load %s.dll\n");' % api.name
        print r'            exit(1);'
        print r'            return NULL;'
        print r'        }'
        print r'    }'
        print r'    return GetProcAddress(g_h%sModule, lpProcName);' % tag
        print r'}'
        print r''

        Dispatcher.dispatchApi(self, api)
Пример #9
0
 def __initDispatchers(self):
     for x in range(self.nDispatchers):
         q = Queue()
         d = Dispatcher(q, x)
         self.clientQueue[x] = q
         self.dispatchers.append(d)
         d.start()
Пример #10
0
    def failFunction(self, function):
        # We fake these when they are not available
        if sys.platform == 'darwin':
            # Fallback to EXT_debug_label on MacOSX
            if function.name == 'glObjectLabel':
                print r'    _glLabelObjectEXT(identifier, name, length < 0 ? 0 : length, length == 0 ? "" : label);'
                return
            if function.name == 'glGetObjectLabel':
                print r'    _glGetObjectLabelEXT(identifier, name, bufSize, length, label);'
                return
        if function.name in (
            # GL_KHR_debug
            'glDebugMessageControl',
            'glDebugMessageInsert',
            'glDebugMessageCallback',
            'glPushDebugGroup',
            'glPopDebugGroup',
            'glObjectLabel',
            'glObjectPtrLabel',
            # GL_ARB_debug_output
            'glDebugMessageControlARB',
            'glDebugMessageInsertARB',
            'glDebugMessageCallbackARB',
            # GL_AMD_debug_output
            'glDebugMessageEnableAMD',
            'glDebugMessageInsertAMD',
            'glDebugMessageCallbackAMD',
            # GL_EXT_debug_label
            'glLabelObjectEXT',
            # GL_EXT_debug_marker
            'glInsertEventMarkerEXT',
            'glPushGroupMarkerEXT',
            'glPopGroupMarkerEXT',
        ):
            return
        if function.name in ('glGetObjectLabel', 'glGetObjectPtrLabel', 'glGetObjectLabelEXT'):
            print r'    if (length != 0) *length = 0;'
            print r'    if (label != 0 && bufSize > 0) *label = 0;'
            return
        if function.name in ('glGetDebugMessageLog', 'glGetDebugMessageLogARB'):
            print r'    if (sources != 0) *sources = 0;'
            print r'    if (types != 0) *types = 0;'
            print r'    if (ids != 0) *ids = 0;'
            print r'    if (severities != 0) *severities = 0;'
            print r'    if (lengths != 0) *lengths = 0;'
            print r'    if (messageLog != 0 && bufsize > 0) *messageLog = 0;'
            print r'    return 0;'
            return
        if function.name in ('glGetDebugMessageLogAMD'):
            print r'    if (categories != 0) *categories = 0;'
            print r'    if (ids != 0) *ids = 0;'
            print r'    if (severities != 0) *severities = 0;'
            print r'    if (lengths != 0) *lengths = 0;'
            print r'    if (message != 0 && bufsize > 0) *message = 0;'
            print r'    return 0;'
            return

        Dispatcher.failFunction(self, function)
Пример #11
0
def detail():
    if request.method == "POST":
        target, proceed = Dispatcher.create_url(request.form.get("txtbox", ""))
        print(target)
        if proceed:
            schema = Dispatcher(target).create_schema()
        else:
            schema = Dispatcher.defaults()
    else:
        schema = Dispatcher.defaults()
    return render_template("detail.html", schema=schema)
Пример #12
0
class VBot(object):

  def __init__(self):
    logging.info('initializing')
    self.bot = Bot()
    self.dispatcher = Dispatcher()
    logging.info('initialization finished')

  def run(self):
    logging.info('starting bot')
    self.bot.run()

  def answer(self, message, query):
    self.dispatcher.dispatch(message, query)
Пример #13
0
 def InitData(self, serverIP, serverPort, sleepInterval, parent):
     self.serverIP = serverIP
     self.serverPort = serverPort
     self.sleepInterval = sleepInterval
     self.dispatcher = Dispatcher()
     self.parent = parent
     self.isAlive = True
     self.hasBegun = False
Пример #14
0
 def InitData(self,headMode,port,timeInterval,sleepInterval):
     self.database = Database()
     try:
         self.headMode = headMode
         self.port = port
         self.timerInterval = timeInterval
         self.sleepInterval = sleepInterval
         self.dispatcher = Dispatcher()
         self.connectedClients = {}
         print ("Type of clients = ",type(self.connectedClients))
     except BaseException as e:
         print ("Error while server init data")
         print (e)
Пример #15
0
    def dispatchModule(self, module):
        tag = module.name.upper()
        print r'HMODULE g_h%sModule = NULL;' % (tag,)
        print r''
        print r'static PROC'
        print r'_get%sProcAddress(LPCSTR lpProcName) {' % tag
        print r'    if (!g_h%sModule) {' % tag
        print r'        char szDll[MAX_PATH] = {0};'
        print r'        if (!GetSystemDirectoryA(szDll, MAX_PATH)) {'
        print r'            return NULL;'
        print r'        }'
        print r'        strcat(szDll, "\\\\%s.dll");' % module.name
        print r'        g_h%sModule = LoadLibraryA(szDll);' % tag
        print r'        if (!g_h%sModule) {' % tag
        print r'            return NULL;'
        print r'        }'
        print r'    }'
        print r'    return GetProcAddress(g_h%sModule, lpProcName);' % tag
        print r'}'
        print r''

        Dispatcher.dispatchModule(self, module)
Пример #16
0
	def failFunction(self, function):
		# We fake this when they are not available
		if function.name in ('glGetObjectLabel', 'glGetObjectPtrLabel', 'glGetObjectLabelEXT'):
			print r'    if (length != 0) *length = 0;'
			print r'    if (label != 0 && bufSize > 0) *label = 0;'
			return
		if function.name in ('glGetDebugMessageLog', 'glGetDebugMessageLogARB'):
			print r'    if (sources != 0) *sources = 0;'
			print r'    if (types != 0) *types = 0;'
			print r'    if (ids != 0) *ids = 0;'
			print r'    if (severities != 0) *severities = 0;'
			print r'    if (lengths != 0) *lengths = 0;'
			print r'    if (messageLog != 0 && bufsize > 0) *messageLog = 0;'
			return
		if function.name in ('glGetDebugMessageLogAMD'):
			print r'    if (categories != 0) *categories = 0;'
			print r'    if (ids != 0) *ids = 0;'
			print r'    if (severities != 0) *severities = 0;'
			print r'    if (lengths != 0) *lengths = 0;'
			print r'    if (message != 0 && bufsize > 0) *message = 0;'
			return

		Dispatcher.failFunction(self, function)
Пример #17
0
def index():
    """ parse request.args for bucket and link
    if either is present, retrieve data accordingly
    if either is present, set active attribute to True
    return schema """
    # initialize empty lists so we dont raise errors
    buckets = []
    links = []
    # get list of buckets
    buckets = database2
    # parse args
    bucket, link = parse_view_args(request.args)
    if bucket:  # retrieve child links, set bucket to active
        for each in buckets:
            if each["id"] == bucket:
                each["active"] = True
                links = each["children"]
            else:
                each["active"] = False
    else:
        for each in buckets:
            each["active"] = False
    if link:  # create preview schema, set link to active
        for each in links:
            if each["id"] == link:
                each["active"] = True
                schema = Dispatcher(each["url"]).create_schema()
            else:
                each["active"] = False
    else:
        for each in links:
            each["active"] = False
        schema = Dispatcher.defaults()
    return render_template("index.html",
                           buckets=buckets,
                           links=links,
                           schema=schema)
Пример #18
0
def main():
    """
    Parse configuration and start flask app.

    WARNING: only a single profile file is supported at this time
    """
    parser = argparse.ArgumentParser()
    parser.add_argument('--port', type=int, default=9001,
                        help="port to listen on (default=9001)")
    parser.add_argument('profiles', nargs='+',
                        help="full path to OpenC2 profile")

    args = parser.parse_args()
    
    global PROFILE
    PROFILE = Dispatcher(*args.profiles)

    app.run(port=args.port)
Пример #19
0
from discord import Client
import os

from dispatch import Dispatcher

TOKEN = os.getenv('TEST_BOT_TOKEN')

class CustomClient(Client):
	async def on_ready(self):
		print(f'{self.user.name} now connected.')

	async def on_message(self, message):
		if message.author == self.user:
			return
		
		await dispatcher.dispatch(message)
		
	async def on_raw_reaction_add(self, payload):
		guild = self.get_guild(payload.guild_id)
		user = guild.get_member(payload.user_id)
		if user == self.user:
			return

		channel = self.get_channel(payload.channel_id)
		msg = await channel.fetch_message(payload.message_id)

client = CustomClient()
dispatcher = Dispatcher(client)

client.run(TOKEN)
Пример #20
0
from dispatch import Dispatcher, Message


def print_message(message):
    print(message)
    print(message.langauge)
    if message.reqex:
        print message.reqex.groups()

numbers = [18182124554] 

def check_message(message):
    if message.number in numbers:
        return True
    
def fall_through(message):
    print(message)
    assert 0 

dispatcher = Dispatcher()
dispatcher.catchAll(fall_through)
dispatcher.addMatcher(check_message,print_message) 
dispatcher.addMatcher(r'^(bal).(\w+)',print_message)
dispatcher.addMatcher(r'^(solde).(\w+)',print_message,langauge="fr")
dispatcher.addMatcher(r'^(add).(\w+).(\d+)',print_message)


if __name__ == '__main__':
    dispatcher.matchMessage(Message(text="bal.asd123",number=18182124551))
Пример #21
0
 def wrap(f):
     Dispatcher.route(url, f)
Пример #22
0
def setup_dispatch(app):
    dispatcher = Dispatcher()
    app['dispatcher'] = dispatcher
    app.on_startup.append(start_dispatcher)
Пример #23
0
    print('}')


if __name__ == '__main__':
    # glClientSideBufferData is a fake api to update client-side memory
    glesapi.delFunctionByName("glClientSideBufferData")
    glesapi.delFunctionByName("glClientSideBufferSubData")
    glesapi.delFunctionByName("glCreateClientSideBuffer")
    glesapi.delFunctionByName("glDeleteClientSideBuffer")
    glesapi.delFunctionByName("glCopyClientSideBuffer")
    glesapi.delFunctionByName("glPatchClientSideBuffer")
    # glGenGraphicBuffer_ARM, glGraphicBufferData_ARM and glDeleteGraphicBuffer are fake APIs to use GraphicBuffer on Android or to use DMA buffer on Linux
    glesapi.delFunctionByName("glGenGraphicBuffer_ARM")
    glesapi.delFunctionByName("glGraphicBufferData_ARM")
    glesapi.delFunctionByName("glDeleteGraphicBuffer_ARM")
    dispatcher = Dispatcher()

    #############################################################
    sys.stdout = open('eglproc_auto.hpp', 'w')
    print('// Generated by', sys.argv[0])
    print('#ifndef _DISPATCH_EGLPROC_HPP_')
    print('#define _DISPATCH_EGLPROC_HPP_')
    print()
    print('#include "eglimports.hpp"')
    print('#include "common/os.hpp"')
    print()
    print('#ifndef GLES_CALLCONVENTION')
    print('#define GLES_CALLCONVENTION')
    print('#endif')
    print()
    print('void * _getProcAddress(const char *procName);')
Пример #24
0
class Client(NetStream, GObject):
    def __init__(self, headMode=8, serverIP="127.0.0.1", serverPort=4829, sleepInterval=0.1, parent=None):
        NetStream.__init__(self, headMode)
        GObject.__init__(self)
        print("client init: %s %s" % (serverIP, serverPort))
        self.InitData(serverIP, serverPort, sleepInterval, parent)
        self.setup()

        # define a signal and its handler, then each time this
        # siganl isa emitted, handler function will be called
        # self.parent.parent.connect(self, QtCore.SIGNAL('serverCrashedAlert()', self.parent.parent.serverCrashedAlert))
        __gsignals__ = {"serverCrashedAlert": (GObject.SIGNAL_RUN_FIRST, None, (int,))}

        def do_serverCrashedAlert(self, arg):
            print("class method for `serverCrashedAlert` called with argument", arg)
            print("server is crashed")

    def InitData(self, serverIP, serverPort, sleepInterval, parent):
        self.serverIP = serverIP
        self.serverPort = serverPort
        self.sleepInterval = sleepInterval
        self.dispatcher = Dispatcher()
        self.parent = parent
        self.isAlive = True
        self.hasBegun = False

    def killClient(self):
        self.isAlive = False

    def setup(self):
        self.setupDispatcher()
        self.setupClient()

    def setupDispatcher(self):
        self.dispatcher.setParent(self)
        services = {
            1001: LoginService(self.dispatcher),
            # 1002 : HallService(self.dispatcher),
            # 1003 : RoomService(self.dispatcher)
        }
        self.dispatcher.registers(services)

    def setupClient(self):
        print(self.serverPort + "\n" + self.serverIP)
        self.connect(self.serverIP, self.serverPort)
        self.nodelay(0)
        self.nodelay(1)

    def sendToServer(self, serviceID, commandID, data):
        message = {}
        message["create_time"] = time.time()
        message["service_id"] = serviceID
        message["command_id"] = commandID
        message["data"] = data
        try:
            messageString = json.dumps(message)
        except (TypeError, e):
            print("error while dumping json")
            print(e)
            print(message)
        print("sending message: %s" % (message))
        self.send(messageString)

    def run(self, lock):  # WARN:lock is not used
        try:
            while self.isAlive:
                time.sleep(self.sleepInterval)
                self.process()
                if self.state == net.NET_STATE_ESTABLISHED:
                    self.hasBegun = True
                if sel.hasBegun == True:
                    print("current state: ", self.state)
                    if self.state == NET_STATE_STOP:
                        # emit the signal, only to self in GTK+
                        # self.emit(QtCore.SIGNAL('serverCrashedAlert()'))
                        self.emit("serverCrashedAlert", 100000000)
                        self.isAlive = False
                    messageString = self.recv()
                    if messageString == "":
                        continue
                    else:
                        print("message: ", messageString)
                    try:
                        message = json.loads(messageString)
                    except (ValueError, e):
                        message = messageString
                    self.dispatcher.dispatch(message, self)
        except (BaseException, e):
            print(time.ctime(), ": error in running client")
            print(e)
Пример #25
0
"""
"""
from pyramid_beaker import session_factory_from_settings
from pyramid.authentication import AuthTktAuthenticationPolicy
from pyramid.authorization import ACLAuthorizationPolicy
from pyramid.exceptions import Forbidden
from pyramid.exceptions import NotFound
import pyramid_handlers
from dispatch import Dispatcher
from gateway.messaging import findMeter

dispatcher = Dispatcher()
dispatcher.addMatcher(findMeter,
                      'gateway.messaging.parse_meter_message')

dispatcher.addMatcher(r'^\(job=gateway-ping', 'gateway.messaging.gateway_ping')

# Allow consumers to check their balance
dispatcher.addMatcher(r'^(bal).(\w+)',
                      'gateway.consumer.get_balance', language='en')
dispatcher.addMatcher(r'^(solde).(\w+)',
                      'gateway.consumer.get_balance', language='fr')
dispatcher.addMatcher(r'^(2).(\w+)',
                    'gateway.consumer.get_balance', language='fr')

# Allow consumers to add credit to their account
dispatcher.addMatcher(r'^(add).(\w+).(\d+)',
                      'gateway.consumer.add_credit', language='en')
dispatcher.addMatcher(r'^(recharge).(\w+).(\d+)',
                      'gateway.consumer.add_credit', language='fr')
dispatcher.addMatcher(r'^(9).(\w+).(\w+)',
Пример #26
0
 def __init__(self):
   logging.info('initializing')
   self.bot = Bot()
   self.dispatcher = Dispatcher()
   logging.info('initialization finished')
Пример #27
0
    def failFunction(self, function):
        # Fallback to EXT_debug_label on MacOSX, some enums need to be translated.
        if function.name in ('glObjectLabel', 'glObjectLabelKHR'):
            print r'#ifdef __APPLE__'
            print r'    if (translateDebugLabelIdentifier(identifier)) {'
            print r'        _glLabelObjectEXT(identifier, name, length < 0 ? 0 : length, length == 0 ? "" : label);'
            print r'        return;'
            print r'    }'
            print r'#endif'
        if function.name in ('glGetObjectLabel', 'glGetObjectLabelKHR'):
            print r'#ifdef __APPLE__'
            print r'    if (translateDebugLabelIdentifier(identifier)) {'
            print r'        _glGetObjectLabelEXT(identifier, name, bufSize, length, label);'
            print r'        return;'
            print r'    }'
            print r'#endif'

        # We fake these when they are not available
        if function.name in (
            # GL_KHR_debug
            'glDebugMessageControl',
            'glDebugMessageInsert',
            'glDebugMessageCallback',
            'glPushDebugGroup',
            'glPopDebugGroup',
            'glObjectLabel',
            'glObjectPtrLabel',
            # GL_KHR_debug (OpenGL ES)
            'glDebugMessageControlKHR',
            'glDebugMessageInsertKHR',
            'glDebugMessageCallbackKHR',
            'glPushDebugGroupKHR',
            'glPopDebugGroupKHR',
            'glObjectLabelKHR',
            'glObjectPtrLabelKHR',
            # GL_ARB_debug_output
            'glDebugMessageControlARB',
            'glDebugMessageInsertARB',
            'glDebugMessageCallbackARB',
            # GL_AMD_debug_output
            'glDebugMessageEnableAMD',
            'glDebugMessageInsertAMD',
            'glDebugMessageCallbackAMD',
            # GL_EXT_debug_label
            'glLabelObjectEXT',
            # GL_EXT_debug_marker
            'glInsertEventMarkerEXT',
            'glPushGroupMarkerEXT',
            'glPopGroupMarkerEXT',
        ):
            return
        if function.name.startswith('glGetObjectLabel'):
            print r'    if (length != 0) *length = 0;'
            print r'    if (label != 0 && bufSize > 0) *label = 0;'
            return
        if function.name == 'glGetDebugMessageLogAMD':
            print r'    if (categories != 0) *categories = 0;'
            print r'    if (ids != 0) *ids = 0;'
            print r'    if (severities != 0) *severities = 0;'
            print r'    if (lengths != 0) *lengths = 0;'
            print r'    if (message != 0 && bufsize > 0) *message = 0;'
            print r'    return 0;'
            return
        if function.name.startswith('glGetDebugMessageLog'):
            print r'    if (sources != 0) *sources = 0;'
            print r'    if (types != 0) *types = 0;'
            print r'    if (ids != 0) *ids = 0;'
            print r'    if (severities != 0) *severities = 0;'
            print r'    if (lengths != 0) *lengths = 0;'
            print r'    if (messageLog != 0 && bufsize > 0) *messageLog = 0;'
            print r'    return 0;'
            return

        Dispatcher.failFunction(self, function)
Пример #28
0
    def dispatchModule(self, module):
        print(r'Module g_mod%s("%s");' % (module.name.upper(), module.name))

        Dispatcher.dispatchModule(self, module)
Пример #29
0
def main():

    """
    Parse configuration and start flask app.
    -
    -    WARNING: Multiple profiles are currently subtly broken in dispatch.py; 
         spreading the logic for different actions across multiple .py files should work correctly,
         but spreading the logic for the same action across multiple files will not; 
         only the target/actuator types from the last profile will be run.
    """
    global PROFILE

    parser = argparse.ArgumentParser()
    parser.add_argument('--port', type=int, default=None, help="port to listen on (default=9001)")    

    group = parser.add_mutually_exclusive_group(required=True)
    group.add_argument('--conf', default=None)
    group.add_argument('--profiles', nargs='+', default=None)


    args = parser.parse_args()

    if args.profiles:

        # If a profile is specified by switches

        # Make dispatcher with loaded modules     
        PROFILE = Dispatcher(args.profiles)

        # Run the app    
        if args.port:

		app.run(port=int(args.port),host="127.0.0.1")

	else:

		app.run(port=9001,host="127.0.0.1")	

    else:

        # If a config file is specified
        if os.path.isfile(args.conf):

            app.config["yuuki"] = parse_config(args.conf)

        else:

            raise(Exception("Config file not found")) 

        # Load profiles
        profile_list = []

        for profile in app.config["yuuki"]["profiles"]:
           
            print " * Loading profile %s" % profile

            profile_list.append(app.config["yuuki"]["profiles"][profile])
        
        # Make dispatcher with loaded modules    
        PROFILE = Dispatcher(profile_list)

	if args.port:

        	# Run the app:   
       		app.run(port=int(args.port),host=app.config["yuuki"]["server"]["host"])
	else:

		# Run the app:
                app.run(port=int(app.config["yuuki"]["server"]["port"]),host=app.config["yuuki"]["server"]["host"])
Пример #30
0
    def dispatchModule(self, module):
        print r'Module g_mod%s("%s");' % (module.name.upper(), module.name)

        Dispatcher.dispatchModule(self, module)
Пример #31
0
    col = []
    for x in range(0, config.world_size[0]):
        col.append( Grass(x, y, vp) )
    vp.map_layer.append(col)

for y in range(0, config.world_size[1]):
    col = []
    for x in range(0, config.world_size[0]):
        col.append( None )
    vp.item_layer.append(col)

# generate item layer
generate_items_layer(vp)

#generate units
dispatcher = Dispatcher(vp)
vp.hud.dispatcher = dispatcher
#dispatcher.tasks.append( Task( GenericTarget( 20, 20) ) )
#dispatcher.tasks.append( Task( GenericTarget( 0, 20) ) )
#dispatcher.tasks.append( Task( GenericTarget( 20, 0) ) )
#dispatcher.tasks.append( Task( GenericTarget( 15, 7) ) )
#dispatcher.tasks.append( Task( GenericTarget( 50, 50) ) )
Unit.load_images()
num_units = 5

unit_count = 0
for y in range(0, config.world_size[1]):
    for x in range(0, config.world_size[0]):
        if vp.item_layer[y][x] == None:
            unit = Unit(x, y, vp, dispatcher)
            vp.unit_layer.append( unit )
Пример #32
0
    def failFunction(self, function):
        # Fallback to EXT_debug_label on MacOSX, some enums need to be translated.
        if function.name in ('glObjectLabel', 'glObjectLabelKHR'):
            print r'#ifdef __APPLE__'
            print r'    if (translateDebugLabelIdentifier(identifier)) {'
            print r'        _glLabelObjectEXT(identifier, name, length < 0 ? 0 : length, length == 0 ? "" : label);'
            print r'        return;'
            print r'    }'
            print r'#endif'
        if function.name in ('glGetObjectLabel', 'glGetObjectLabelKHR'):
            print r'#ifdef __APPLE__'
            print r'    if (translateDebugLabelIdentifier(identifier)) {'
            print r'        _glGetObjectLabelEXT(identifier, name, bufSize, length, label);'
            print r'        return;'
            print r'    }'
            print r'#endif'

        # We fake these when they are not available
        if function.name in (
                # GL_KHR_debug
                'glDebugMessageControl',
                'glDebugMessageInsert',
                'glDebugMessageCallback',
                'glPushDebugGroup',
                'glPopDebugGroup',
                'glObjectLabel',
                'glObjectPtrLabel',
                # GL_KHR_debug (OpenGL ES)
                'glDebugMessageControlKHR',
                'glDebugMessageInsertKHR',
                'glDebugMessageCallbackKHR',
                'glPushDebugGroupKHR',
                'glPopDebugGroupKHR',
                'glObjectLabelKHR',
                'glObjectPtrLabelKHR',
                # GL_ARB_debug_output
                'glDebugMessageControlARB',
                'glDebugMessageInsertARB',
                'glDebugMessageCallbackARB',
                # GL_AMD_debug_output
                'glDebugMessageEnableAMD',
                'glDebugMessageInsertAMD',
                'glDebugMessageCallbackAMD',
                # GL_EXT_debug_label
                'glLabelObjectEXT',
                # GL_EXT_debug_marker
                'glInsertEventMarkerEXT',
                'glPushGroupMarkerEXT',
                'glPopGroupMarkerEXT',
        ):
            return
        if function.name.startswith('glGetObjectLabel'):
            print r'    if (length != 0) *length = 0;'
            print r'    if (label != 0 && bufSize > 0) *label = 0;'
            return
        if function.name == 'glGetDebugMessageLogAMD':
            print r'    if (categories != 0) *categories = 0;'
            print r'    if (ids != 0) *ids = 0;'
            print r'    if (severities != 0) *severities = 0;'
            print r'    if (lengths != 0) *lengths = 0;'
            print r'    if (message != 0 && bufsize > 0) *message = 0;'
            print r'    return 0;'
            return
        if function.name.startswith('glGetDebugMessageLog'):
            print r'    if (sources != 0) *sources = 0;'
            print r'    if (types != 0) *types = 0;'
            print r'    if (ids != 0) *ids = 0;'
            print r'    if (severities != 0) *severities = 0;'
            print r'    if (lengths != 0) *lengths = 0;'
            print r'    if (messageLog != 0 && bufsize > 0) *messageLog = 0;'
            print r'    return 0;'
            return

        Dispatcher.failFunction(self, function)
Пример #33
0
class Main(NetHost):    #GObject?

    def __init__(self, headMode = 8, port = 4829, timeInterval = 10000, sleepInterval = 0.5):
        NetHost.__init__(self, headMode)
        self.InitData(headMode,port,timeInterval,sleepInterval)
        self.setup()

    def InitData(self,headMode,port,timeInterval,sleepInterval):
        self.database = Database()
        try:
            self.headMode = headMode
            self.port = port
            self.timerInterval = timeInterval
            self.sleepInterval = sleepInterval
            self.dispatcher = Dispatcher()
            self.connectedClients = {}
            print ("Type of clients = ",type(self.connectedClients))
        except BaseException as e:
            print ("Error while server init data")
            print (e)

    def __del__(self):
        print ("Server Lost!")

    def setup(self):
        self.setupDatabase()
        self.setupDispatcher()
        self.setupServer()
        print (self.connectedClients)

    def setupServer(self):
        try:
            self.startup(self.port)
            print ('[',time.ctime(),']','Server startup at port:',self.port)
            self.settimer(self.timerInterval)
        except BaseException as e:
            print ("Error while setup server")
            print (e)

    def setupDispatcher(self):
        self.dispatcher.setParent(self)
        services = {}
        #services[LoginService.serviceID] = LoginService(self.dispatcher)
        #services[HallService.serviceID]  = HallService(self.dispatcher)
        #services[RoomService.serviceID] = RoomService(self.dispatcher)
        self.dispatcher.registers(services)
        print ("Setup Dispatcher")
        print (services)

    def setupDatabase(self):
        self.database.connect()
        try:
            self.database.setup()
        except BaseException as e:
            print ("Error while setup db")
            print (e)

    def hasNicknameInConnectedClients(self,nickname):
        for connectID in self.connectedClients:
            if self.connectedClients[connectID].nickname == nickname:
                print ("Has Nickname connected!!")
                print (connectID," ",nickname)
                return True
        return False

    @staticmethod
    def logTime():
        print ("[",time.ctime(),"]")

    @staticmethod
    def log(string):
        try:
            Main.logTime()
            print (string)
        except BaseException as e:
            print ("Error while finding log",e)

    def connectionEventHandler(self,connectID,messageString = ''):
        print ("clientsType is ",type(self.connectedClients))
        try:
            self.log(str(connectID) + " comes")
            self.connectedClients[connectID] = Player.Player(connectID,self)
            #self.sendToClient(connectID,1001,1001,"F**k you in connection handler")
        except BaseException as e:
            self.log("Error in Connection Event")
            print (type(self.connectedClients))
            print (e)

    def disconnectionEventHandler(self,connectID,messageString = ''):
        try:
            self.log(str(connectID) + ' leaves')
            del self.connectedClients[connectID]
            self.dispatcher.services[1002].leaveHall(connectID)
            self.dispatcher.services[1003].removePlayerFromAllRooms(connectID)
        except BaseException as e:
            self.log("Error in disconnect")
            print (e)

    def timerEventHandler(self,connectID,messageString = ''):
        #self.log(str(connectID) + ":timer triggered!")
        #print "Clients type = " ,type(self.connectedClients)
        pass

    def messageEventHandler(self,connectID,message = ''):
        try:
            self.log(str(connectID) + " sends a message!")
            self.dispatcher.dispatch(message,self.connectedClients[connectID])
            #self.sendToClient(connectID,1001,1001,"F**k you in messageEventHandler")
        except BaseException as e:
            self.log("Error in message Event Handler")
            print (message)
            print (e)

    def sendToClient(self,connectID,serviceID,commandID,data):
        message = {}
        message['create_time'] = time.time()
        message['service_id'] = serviceID
        message['command_id'] = commandID
        message['data'] = data

        messageString = json.dumps(message)
        self.send(connectID,messageString)
        print ("Send message To ",connectID,":",messageString)

    def run(self):
    #try:
        while True:
            try:
                try:
                    time.sleep(self.sleepInterval)
                except BaseException as e:
                    print ("Error while Server Sleep")
                    print (e)
                try:
                    try:
                        self.process()
                    except BaseException as e:
                        print ("Error while Server Processing!")
                        print (e)
                    try:
                        eventType , connectID , lparam ,messageString = self.read()
                    except BaseException as e:
                        print ("Error while Server Reading()")
                    try:
                        if eventType < 0:
                            #print "Wrong Event:",eventType
                            continue
                    except BaseException as e:
                        print ("Errow while Finding Wrong Event")
                    try:
                        if eventType == net.NET_NEW:
                            self.connectionEventHandler(connectID,messageString)
                        if eventType == net.NET_LEAVE:
                            self.disconnectionEventHandler(connectID,messageString)
                        if eventType == net.NET_TIMER:
                            self.timerEventHandler(connectID,messageString)
                        if eventType == net.NET_DATA:
                            #self.sendToClient(connectID,1001,1001,"F**k you in NETDATA")
                            message = None
                            try:
                                message = json.loads(messageString)
                                self.messageEventHandler(connectID,message)
                            except BaseException as e:
                                self.logTime()
                                print (e)
                    except BaseException as e:
                        self.log("Error while handling Event")
                        print (e)
                except BaseException as e:
                    print ("Error while server working in loop")
                    print (e)
            except KeyboardInterrupt:
                print ("to quit the server")
                break
            except BaseException as e:
                print ("Error while server loop")
                print (e)
Пример #34
0
        type='string',
        dest='nametype',
        default='vid',
        help='how to name the video file. vid and title. default is vid. ')
    parser.add_option('-f',
                      action='store_true',
                      dest='force',
                      default=False,
                      help='overwrite the existing file.default is False.')
    parser.add_option(
        '-m',
        action='store_true',
        dest='makejson',
        default=False,
        help='if create json file that describe the video. default is False.')
    parser.add_option('-e',
                      '--ext',
                      action='store',
                      type='string',
                      dest='ext',
                      default='mp4',
                      help='output video extended name. default is mp4.')
    options, args = parser.parse_args()
    url = options.__dict__.get('url')
    c = Condition(**options.__dict__)
    if url is None or len(url) == 0:
        print('error: video url is None! exit...')
        sys.exit(0)

    Dispatcher(c)