Exemplo n.º 1
0
    def detect_handlers(self):

        if config.VM == 'vmp' or config.VM == 'cv':
            
            dispatcher = self.sorted_blocks('loop_count')[0] # find the hottest block. 

            print '[+] Dispatcher found at %#x.' % dispatcher.addr

            for loop in dispatcher.loops:
                loop_blocks = list(loop.list_nodes(self))
                assert loop_blocks[0] == dispatcher

                h = handler.Handler()
                for b in loop_blocks[1:]:
                    if not h.add_block(b):
                        break  # if add failed, we stop.

                if h.is_valid:
                    self.add_handler(h)

            self.dispatcher = dispatcher            

        elif config.VM == 'vmp3':
            
            jmp_edi_blocks = []
            
            for addr in self.blocks:
                b = self.blocks[addr]
                if b.ends_with_jmp_edi and b.ins_count < 10: # short block
                    jmp_edi_blocks.append(addr)

            for addr in self.blocks:
                if addr in jmp_edi_blocks:
                    continue

                b = self.blocks[addr]

                if b.ends_with_jmp_edi:  # block ends with "jmp edi" patten
                    h = handler.Handler()
                    h.add_block(b)
                    self.add_handler(h)
                else:                    # block jump to `jmp_edi_block`
                    if len(b.nexts) != 1:
                        continue
                    next_addr = b.nexts.keys()[0]
                    if next_addr in jmp_edi_blocks:
                        next_b = self.blocks[next_addr]
                        h = handler.Handler()
                        h.add_block(b)
                        h.add_block(next_b)
                        self.add_handler(h)                       

        else:
            raise NotImplementedError('unsupported VM type %s' % config.VM)

        print '[+] %s %s-handlers found.' % (len(self.handlers), config.VM)
Exemplo n.º 2
0
 def test_api(self):
     test_handler = handler.Handler('http://numbersapi.com/', self.loop, 'GET')
     async def go():
         async with aiohttp.ClientSession(loop=self.loop) as session:
             await test_handler.download_json_coroutine(session, 100, test_handler.url)
     self.loop.run_until_complete(go())
     self.assertTrue(test_handler.output.pop()['found'])
Exemplo n.º 3
0
    def __init__(self,
                 room,
                 nickname="",
                 account=None,
                 password=None,
                 solve_captchas=False):
        self.room_name = room
        self.nickname = nickname
        self.account = account
        self.password = password
        self.client_id = 0
        self.is_client_mod = False
        self.is_client_owner = False
        self._init_time = time.time()

        self.handler = handler.Handler()
        self.is_green_room = False
        self.is_connected = False
        self.active_user = None
        self.users = user.Users()
        # JSON string from tinychat.get_connect_info(), contains room token and ws address
        self.connect_info = {}
        self._ws = None
        self._req = 1
        self.is_published = False
        self.solve_captchas = solve_captchas
        self.ice_servers = None
        if solve_captchas:
            if len(CONFIG.API_KEY) > 0:
                self.captcha = captcha.AntiCaptcha(CONFIG.API_KEY)
            else:
                self.solve_captchas = False
Exemplo n.º 4
0
def run():

    start_query = query.Api()
    results = start_query.query()
    if results:
        handler.Handler().pipeline(results)
    else:
        pass
Exemplo n.º 5
0
 def decorator(procedure):
     """Create a new handler from the decorated function."""
     nonlocal name
     if not name:
         name = procedure.__name__
     new_handler = handler.Handler(self, procedure, name, max_retries)
     if new_handler.name in self.handlers:
         err = "Conflict: handler for task '{}' already exists."
         raise RuntimeError(err.format(new_handler.name))
     self.handlers[new_handler.name] = new_handler
     return new_handler
Exemplo n.º 6
0
    def __init__(self):
        self.cookies = hangups.get_auth_stdin("token.txt", True)
        self.client = hangups.Client(self.cookies)

        with open("reply_data.json", "r") as replies_file:
            self.reply_data = json.load(replies_file)
        self.handler = handler.Handler(self, self.reply_data)
        self.connected = asyncio.Event()

        # to prevent replying to self
        self.recent_meeper_messages = []
        self.sending_lock = asyncio.Lock()
Exemplo n.º 7
0
    def run(self):
        event_handler = handler.Handler()
        self.observer.schedule(event_handler,
                               self.watch_directory,
                               recursive=True)

        self.observer.start()
        try:
            while True:
                time.sleep(5)
        except:
            self.observer.stop()
            print("\nERROR: Stopping watcher.\n")

        self.observer.join()
Exemplo n.º 8
0
	def __init__(self):
		super(Mapper, self).__init__()

		self.handler = handler.Handler()
		self._clear()
		f = Figlet()
		intro_text = """============================================\n"""
		intro_text += """Welcome to the Loadsheet Builder. \n"""
		intro_text += """Use this tool to build and review loadsheets. \n"""
		intro_text += """For help with functions, type 'help' or view README. \n"""
		intro_text += """OnboardingTool Copyright (C) 2020 DB Engineering"""
		intro_text += """To view license information, type 'license'\n"""
		intro_text += """============================================"""
		self.intro = f.renderText('LoadBoy2000')+intro_text

		self.prompt = '>>> '
Exemplo n.º 9
0
      def parse_js_obj(self,message_data):
          print message_data
          self.decoded = json.loads(message_data)
          print 'DECODED:', self.decoded
          print self.decoded[0]['data']

          # write in a file to cache data
          fob = open('dwrite' ,'w')                   
          for item in self.decoded:
              fob.write("%s\n" % item)
              # A call to an handler class to pass the received message to the appropriate class object to run
              #handle = handler.Handler(item[0])
          fob.close() 

          # A call to an handler class to pass the received message to the appropriate class object to run
          handle = handler.Handler(self.decoded )


          """
Exemplo n.º 10
0
    def detect_handlers(self):

        dispatcher = self.sorted_blocks('loop_count')[
            0]  # find the hottest block.

        print '[+] Dispatcher found at %#x.' % dispatcher.addr

        for loop in dispatcher.loops:
            loop_blocks = list(loop.list_nodes(self))
            assert loop_blocks[0] == dispatcher

            h = handler.Handler()
            for b in loop_blocks[1:]:
                if not h.add_block(b):
                    break  # if add failed, we stop.

            if h.is_valid:
                self.add_handler(h)

        self.dispatcher = dispatcher

        print '[+] %s handlers found.' % len(self.handlers)
Exemplo n.º 11
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("-w", "--weather", action="store_true", help="weather display function")
    args = parser.parse_args()

    arg_list = []
    if args.weather:
        arg_list.append("weather")
    handler_object = handler.Handler(arg_list)

    try:
        for event in longpoll.listen():
            # new message income
            if event.type == VkEventType.MESSAGE_NEW:
                # if this has mark for me(for bot)
                if event.to_me:
                    # message from user
                    request = event.text
                    print(request)
                    handler_object.handle(event.user_id, request)
    except KeyboardInterrupt:
        print("Goodbye...")
        sys.exit()
Exemplo n.º 12
0
def data():
    output = handler.Handler('/home/likewise-open/LOCAL/joao.garcia/Workplace/'
                             '1.INPE/Data/Radar/BR_PP/2014/06/')
    return output
Exemplo n.º 13
0
import random, handler, display

# win_0 = Combat Calculator

obj = handler.Handler()
display.display_win("win_0")
Exemplo n.º 14
0
 def __init__(self):
     super().__init__()
     self.db = db.DB()
     self.handler = handler.Handler()
     self.initUI()
Exemplo n.º 15
0
import os
import handler
import sys
from flask import Flask, request
import pandas as pd
from sessionHandler import SessionHandler
import redis
import fbApi


app = Flask(__name__)

DATA_LOC = 'Data/'
PRODUCTS = pd.read_csv(DATA_LOC + 'Lengow.csv').fillna('')
SHOPS = pd.read_csv(DATA_LOC + 'Shops2.csv').fillna('')
hdl = handler.Handler(opt_list=handler.ALL_OPT, shops=SHOPS, products=PRODUCTS)

# Test setting
TEST_MODE = True if len(sys.argv) > 1 and sys.argv[1] == 'test' else False

if TEST_MODE:
    FB_URL = "http://localhost:9999/"
    ACCESS_TOKEN = ""
    REDIS_HOST = 'localhost'
    REDIS_PORT = 6379
    r = redis.StrictRedis(host=REDIS_HOST, port=REDIS_PORT, db=0)
else:
    FB_URL = "https://graph.facebook.com/v2.6/me/"
    ACCESS_TOKEN = os.environ["PAGE_ACCESS_TOKEN"]
    REDIS_URL = os.getenv('REDISTOGO_URL', 'redis://localhost:6379')
    r = redis.from_url(REDIS_URL)
Exemplo n.º 16
0
import config
import telebot
import datetime
import keyboards as kb
import handler
import sql

bot = telebot.TeleBot(config.TOKEN)

hd = handler.Handler(bot)

print("Start")

print(bot.get_me())


@bot.message_handler(commands=['start'])
def handle_command(message):  #Проверяем команды от пользователя
    hd.start_handler(message)


@bot.message_handler(content_types=['text'])
def handle_message(message):
    hd.handle_text(message)


bot.polling(none_stop=True, interval=0)
Exemplo n.º 17
0
import handler


if __name__ == "__main__":
    hand = handler.Handler()
    hand.print_info()
    while True:
        command = str(input())
        try:
            hand.get_command(command)
        except (ValueError, handler.InputException):
            print('Try one more time')
        except handler.AdderException:
            print('Already added')
            print('Try tomorrow')
        except handler.ForecastException:
            print('Firstly add current weather')
        except handler.APIException:
            print('Problems with servers, try later')
        except handler.DecodingException:
            print('Problems with decoding data, try later')
Exemplo n.º 18
0
            output_text += '    portd = %' + ''.join(d) + '\n'
            output_text += '    portc = %' + ''.join(c) + '\n'
            output_text += '    pause 1\n'
          
            output_text += '\n'
            
            output.insert(tkinter.END, output_text)
            output_text = ''
        output.insert(tkinter.END, '    next x\n')

#create cube
cube = Cube([],[],400,500,15, 150, 4)
cube.generate()
cube.rotate(220,1)
cube.rotate(190,2)
cube.draw_points()
cube.draw_edges()

h = handler.Handler(root,cube,screen)

generate_button = tkinter.Button(root, text='generate', command = cube.create_frame)
generate_button.grid(row = 2, column = 1)

lock_button = tkinter.Button(root, text='lock', command = h.lock)
lock_button.grid(row = 4, column = 1)

screen.bind('<B1-Motion>',h.motion_handler)
screen.bind('<Button-1>',h.click_handler)

root.mainloop()
Exemplo n.º 19
0
the top topics. Each has their own call to the handler class to retrieve
the data.

"""

import dash
from dash.dependencies import Input, Output, State
import dash_core_components as dcc
import dash_html_components as html

import pandas as pd
import numpy as np
import handler

app = dash.Dash()
my_handler = handler.Handler()


# Reusable
def make_dash_table(data_frame):
    ''' Return a dash definition of an HTML table for a Pandas dataframe '''
    table = []
    for _, row in data_frame.iterrows():
        html_row = []
        for i in range(len(row)):
            html_row.append(html.Td([row[i]]))
        table.append(html.Tr(html_row))
    return table


# Main layout
Exemplo n.º 20
0
def main(entry, depth):
    print("Entry: {w}, depth: {d}".format(w=entry, d=depth))
    hdlr = handler.Handler(config)
    hdlr.crawl(entry ,int(depth))
Exemplo n.º 21
0
import multiprocessing
import Library.interfaz
import Library.config
import handler
import server

try:
    config = Library.config.read()
except:
    import sys
    print("FAILED TO OPEN CONFIG FILE, EXITING")
    sys.exit()
man = multiprocessing.Manager()
adios = man.Value(bool, False)
interfaz = Library.interfaz.Interfaz(lang=config["lang"])
hand = handler.Handler(interfaz, adios)
hand.pantalla("INIT", prompt=False)
input("")
key_bits = int(config["key_length"])
hand.pantalla("GENERATING_KEY", args=(key_bits, ), prompt=False)
server = server.Server(adios,
                       hand,
                       Library.Encriptacion.genera(key_bits),
                       ip=config["host"],
                       port=int(config["port"]))
g = multiprocessing.Process(target=server.listen)
p = multiprocessing.Process(target=server.server_handler)
p2 = multiprocessing.Process(target=hand.listen, args=(server, ))
p.start()
g.start()
hand.listen(server)
Exemplo n.º 22
0
def run_handler():
    global handler
    handler = handler.Handler(debug_mode=True)
    handler.start()
Exemplo n.º 23
0
 def __init__(self, host, port, controllers_prefix, logger_name=None):
     self.logger = Logger.get_logger(logger_name)
     self.controllers_prefix = controllers_prefix
     self.handler = handler.Handler(controllers_prefix)
     self.host = str(host)
     self.port = int(port)
Exemplo n.º 24
0
#
# Copyright 2017 Alsanium, SAS. or its affiliates. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

import sys
import dl

sys.setdlopenflags(sys.getdlopenflags() | dl.RTLD_NOW | dl.RTLD_GLOBAL)

import shim

shim.open(__name__)

import handler

sys.modules[__name__] = handler.Handler()
Exemplo n.º 25
0
    log('[MAIN] Connecting to database')
    database_connection = database.Database()

    log('[MAIN] Starting WebApp Server')
    webapp_server = threaded_server.ThreadedServer(ip_addr, 51030,
                                                   database_connection,
                                                   webapp_socket.WebAppSocket)
    webapp_server.start()

    log('[MAIN] Starting Wearable Server')
    wearable_server = threaded_server.ThreadedServer(
        ip_addr, 24192, database_connection, wearable_socket.WearableSocket)
    wearable_server.start()

    log('[MAIN] Setting up handlers')
    server_handler = handler.Handler(webapp_server, wearable_server,
                                     database_connection)

    while True:
        try:
            if not webapp_server.queue.empty():
                server_handler.webapp()

            if not wearable_server.queue.empty():
                server_handler.wearable()

            time.sleep(1)
        except KeyboardInterrupt:
            sys.exit(0)
        except:
            log(traceback.format_exc())
Exemplo n.º 26
0
 def setUp(self):
     self.handler = handler.Handler()
     self.query_article = 'SpaceX Launches Rocket'
     self.path = 'news_analyzer/libraries'
Exemplo n.º 27
0
import time
import problem, store, phone, handler, paras

store = store.Store("./store")
phone = phone.Phone()
entryHandler = handler.Handler("entry", "pics/entrySign.jpg", phone)
endHandler = handler.Handler("end", "pics/endSign.jpg", phone)
retryHandler = handler.Handler("retry", "pics/retrySign.jpg", phone)
exitHandler = handler.Handler("exit", "pics/exitSign.jpg", phone)
backHandler = handler.Handler("back", "pics/backSign.jpg", phone)
wrongHandler = handler.Handler("wrong", "pics/wrongSign.jpg", phone)
problemHandler = problem.ProblemHandler("pics/problemSign.jpg", phone, store)

inputFile = "inputs/a.png"

if __name__ == '__main__':
    while True:
        phone.screencast(inputFile, paras.SCALE)
        if entryHandler.check(inputFile):
            entryHandler.handle()
        elif endHandler.check(inputFile):
            endHandler.handle()
        elif exitHandler.check(inputFile):
            exitHandler.handle()
        elif retryHandler.check(inputFile):
            retryHandler.handle()
        elif problemHandler.check(inputFile):
            problemHandler.handle()
        elif wrongHandler.check(inputFile):
            break
            backHandler.check(inputFile)
Exemplo n.º 28
0
    def __init__(self, title="Map Simulator"):

        self.master  = Tk()
        self.master.title(title)
        self.handler = handler.Handler(self)
        self.map     = self.handler.map
        self.algo    = self.handler.algo

        t = Toplevel(self.master)
        t.title("Control Panel")
        t.geometry('180x360+1050+28')

        # left side map panel
        self.map_pane = ttk.Frame(self.master, borderwidth=0, relief="solid")
        self.map_pane.grid(column=0, row=0, sticky=(N, S, E, W))
        # right side control panel
        self.control_pane = ttk.Frame(t, padding=(12, 10))
        self.control_pane.grid(column=1, row=0, sticky=(N, S, E, W))

        # robot size
        self.robot_size     = config.robot_detail['size']
        # stores instances of widgets on the map
        self.map_widget     = [[None]*self.map.width]*self.map.height

        # photo instances
        self.robot_n = []
        self.robot_s = []
        self.robot_e = []
        self.robot_w = []
        for i in range(9):
            self.robot_n += [PhotoImage(file=config.icon_path['north'][i]).subsample(config.icon_path['size'])]
            self.robot_s += [PhotoImage(file=config.icon_path['south'][i]).subsample(config.icon_path['size'])]
            self.robot_w += [PhotoImage(file=config.icon_path['west'][i]).subsample(config.icon_path['size'])]
            self.robot_e += [PhotoImage(file=config.icon_path['east'][i]).subsample(config.icon_path['size'])]
        self.map_free1               = PhotoImage(file=config.icon_path['free'])
        self.map_free_explored1      = PhotoImage(file=config.icon_path['explored_free'])
        self.map_obstacle1           = PhotoImage(file=config.icon_path['obstacle'])
        self.map_obstacle_explored1  = PhotoImage(file=config.icon_path['explored_obstacle'])
        self.map_start1              = PhotoImage(file=config.icon_path['start'])
        self.map_end1                = PhotoImage(file=config.icon_path['end'])

        self.map_free               = self.map_free1.subsample(config.icon_path['size'])
        self.map_free_explored      = self.map_free_explored1.subsample(config.icon_path['size'])
        self.map_obstacle           = self.map_obstacle1.subsample(config.icon_path['size'])
        self.map_obstacle_explored  = self.map_obstacle_explored1.subsample(config.icon_path['size'])
        self.map_start              = self.map_start1.subsample(config.icon_path['size'])
        self.map_end                = self.map_end1.subsample(config.icon_path['size'])

        # map initialization.
        self.currentMap      = deepcopy(self.map.get_map())
        self.robot_location  = self.map.get_robot_location()
        self.robot_direction = self.map.get_robot_direction()
        self.update_map(init=True)

        control_pane_window = ttk.Panedwindow(self.control_pane, orient=VERTICAL)
        control_pane_window.grid(column=0, row=0, sticky=(N, S, E, W))
        parameter_pane = ttk.Labelframe(control_pane_window, text='Parameters')
        action_pane = ttk.Labelframe(control_pane_window, text='Action')
        control_pane_window.add(parameter_pane, weight=4)
        control_pane_window.add(action_pane, weight=1)

        explore_button = ttk.Button(action_pane, text='Explore', width=16, command=self.algo.explore)
        explore_button.grid(column=0, row=0, sticky=(W, E))
        fastest_path_button = ttk.Button(action_pane, text='Fastest Path', command=self.algo.run)
        fastest_path_button.grid(column=0, row=1, sticky=(W, E))
        move_button = ttk.Button(action_pane, text='Move', command=self.move)
        move_button.grid(column=0, row=2, sticky=(W, E))
        left_button = ttk.Button(action_pane, text='Left', command=self.left)
        left_button.grid(column=0, row=3, sticky=(W, E))
        right_button = ttk.Button(action_pane, text='Right', command=self.right)
        right_button.grid(column=0, row=4, sticky=(W, E))

        step_per_second = StringVar()
        step_per_second_label = ttk.Label(parameter_pane, text="Step Per Second:")
        step_per_second_label.grid(column=0, row=0, sticky=W)
        step_per_second_entry = ttk.Entry(parameter_pane, textvariable=step_per_second)
        step_per_second_entry.grid(column=0, row=1, pady=(0, 10))

        coverage_figure = StringVar()
        coverage_figure_label = ttk.Label(parameter_pane, text="Coverage Figure(%):")
        coverage_figure_label.grid(column=0, row=2, sticky=W)
        coverage_figure_entry = ttk.Entry(parameter_pane, textvariable=coverage_figure)
        coverage_figure_entry.grid(column=0, row=3, pady=(0, 10))

        time_limit = StringVar()
        time_limit_label = ttk.Label(parameter_pane, text="Time Limit(s):")
        time_limit_label.grid(column=0, row=4, sticky=W)
        time_limit_entry = ttk.Entry(parameter_pane, textvariable=time_limit)
        time_limit_entry.grid(column=0, row=5, pady=(0, 10))

        # self.root.columnconfigure(0, weight=1)
        # self.root.rowconfigure(0, weight=1)
        self.control_pane.columnconfigure(0, weight=1)
        self.control_pane.rowconfigure(0, weight=1)

        # for i in range(10):
        #     map_pane.rowconfigure(i, weight=1)
        # for j in range(15):
        #     map_pane.columnconfigure(j, weight=1)

        self.master.bind("<Left>", lambda e: self.left())
        self.master.bind("<Right>", lambda e: self.right())
        self.master.bind("<Up>", lambda e: self.move())
        self.master.bind("<Down>", lambda e: self.back())

        self.master.mainloop()