Exemplo n.º 1
0
    def __init__(self, ctx, **kwargs):
        super().__init__(ctx, **kwargs);
        self.id = kwargs.get("id") # networkx node id
        self.label = kwargs.get("label", "NoLabelSet"); # name in topology
        self.x = kwargs.get("x"); # coordinates in topology
        self.y = kwargs.get("y"); # coordinates in topology

        # create a port object for each port of the switch; these are used 
        # to store and access port related statistics
        cnt = 0
        self.ports = {}

        for n in ctx.topo.graph.neighbors(self.id):
            port = Port(cnt)
            cnt += 1 
            port.target = n
            port.link_in = ctx.topo.graph.edges[n, self.id]['_link']
            port.link_out = ctx.topo.graph.edges[self.id, n]['_link']
            self.ports[(n, self.id)] = port

        # create a flow table object for this switch
        self.flowtable = FlowTable(self)

        # logic of the switch is implemented inside the engine; This is
        # similar to connecting a switch to a controller
        self.engine = kwargs.get("engine", Engine(self.ctx, **kwargs)) # routing engine

        self.cnt_backdelegations = 0
        self.cnt_adddelegations = 0
Exemplo n.º 2
0
 def do_crawler(self, para):
     print "do_crawler"
     #create crawler engin
     crawler_engine = Engine()
     #start engine
     crawler_engine.start()
     #stop engin
     crawler_engine.stop()
Exemplo n.º 3
0
def main() -> None:
    engine = Engine()
    engine.load_session_from_json('../config/project.json')
    interface = ConsoleInterface(engine)
    # This starts the interface, which uses this thread until the exit command has been given
    # The sequencer runs in it's own thread, that has already been started, so this is actually desired
    interface.start_interface()
    # after the ui has stopped, it's time to shut down the engine (which stops the sequencer thread)
    engine.shut_down()
Exemplo n.º 4
0
    def init(self, spider_type, task_name):
        self.__spider_type = spider_type
        self.__task_name = task_name
        self.__container = Container()
        self.set('app', self)
        self.set('browser', Browser())
        self.set('facade', Facade())
        Facade().init(self)

        self.set('component', ComponentManager())
        self.set('for', ForManager())
        self.set('global', GlobalManager())
        self.set('hook', HookManager())
        self.set('config', Config())

        self.set('engine', Engine())
        Engine().init(spider_type)
        return self
Exemplo n.º 5
0
    def __init__(self, size=24, selection_size=6, game_number=5, folder="generations", \
        ideal_generation=1000, idle_limit=100, league:LEAGUE=LEAGUE.WOOD3, restart_generation=20,
        visualize=False, batch_size=os.cpu_count(), save_every=10, print_game = False):

        assert size > selection_size
        assert not (
            size % batch_size
        ), f'Population Size ({size}) must be divisible by Batch Size ({batch_size})'
        assert not (
            (size // batch_size) %
            2), f'Batch Data must be an even number ({(size // batch_size)})'

        self.batch_size = batch_size
        self.generation = 0
        self.simulated = 0
        self.restart_limit = restart_generation
        self.size = size
        self.selection_size = selection_size
        self.folder = folder
        self.ideal_generation = ideal_generation
        self.visualize = visualize
        self.save_every = save_every
        self.print_game = print_game

        if not os.path.exists(f'./ai/{folder}'):
            os.mkdir(f'./ai/{folder}')

        if visualize:
            from core.gui import GUIEngine
            self.batch_size = 1
            self.num_game = 1
            self.engines = [
                GUIEngine(league=league,
                          silence=False,
                          idle_limit=idle_limit,
                          sleep=0.1)
            ]

        else:
            print(
                f'Initializing Population with size({size}) selection({selection_size}) batch({batch_size}) league({league.name})'
            )
            self.engines = [
                Engine(league=league, silence=True, idle_limit=idle_limit)
                for _ in range(batch_size)
            ]

        [(engine.add_player(AIBot, randomize=True),\
            engine.add_player(AIBot, randomize=True)) for engine in self.engines]
        self.num_game = game_number
        self.generation_data = [None] * self.size
        self.results = [None] * self.size
        self.current_index = 0
def main():
    import argparse
    parser = argparse.ArgumentParser()
    parser.add_argument('traintsv')
    parser.add_argument('generalintentscsv')
    parser.add_argument('testtsv')
    args = parser.parse_args()
    data = read_tsv(args.testtsv)

    # initialize engine
    engine = Engine(args.traintsv, args.generalintentscsv)

    correct_entities = 0.
    correct_intents = 0.
    correct_response = 0.

    from fuzzywuzzy import fuzz

    # Begin evaluation
    for i, line in enumerate(data):
        print "Query ", i
        query = line[0]
        response = line[1]
        intent = line[2]
        entities = underscore_entities(line[3].split(','))
        result = engine.process_message(i, query)
        pprint(line)
        pprint(result)
        if len(result['entities']) >= 1 and set(entities).issubset(
                result['entities']):
            correct_entities += 1
        else:
            print "Entities mismatch"
            print set(entities)
            print result['entities']

        if intent == result['intent']:
            correct_intents += 1
        else:
            print "Intent mismatch"

        if result['response'] is not None and \
           fuzz.partial_ratio(response, result['response']) > 50:
            correct_response += 1
        else:
            print "Response mismatch"

    print "Entity score {} Intent score {} Response score {}".format(
        correct_entities / len(data), correct_intents / len(data),
        correct_response / len(data))

    sys.stdout.flush()
Exemplo n.º 7
0
def main():
    config_dict = create_config("tnn")
    tnn = Engine(config_dict)
    model_dict = tnn.prepare_models()
    device_dict = tnn.prepare_devices()
    tnn.set_config("model_dict", model_dict)
    tnn.set_config("device_dict", device_dict)

    tnn.prepare_models_for_devices()
    tnn.prepare_benchmark_assets_for_devices()
    bench_dict = tnn.run_bench()
    bench_str_list = tnn.generate_benchmark_summary(bench_dict)
    tnn.write_list_to_file(bench_str_list)
Exemplo n.º 8
0
def bench(name):
    if name is None:
        return
    config_dict = create_config(name)
    engine = Engine(config_dict)

    model_dict = engine.prepare_models()
    device_dict = engine.prepare_devices()
    engine.set_config("model_dict", model_dict)
    engine.set_config("device_dict", device_dict)

    engine.prepare_models_for_devices()
    engine.prepare_benchmark_assets_for_devices()

    bench_dict = engine.run_bench()

    bench_str_list = engine.generate_benchmark_summary(bench_dict)
    engine.write_list_to_file(bench_str_list)
def main():
    usage = "usage: %prog [options]"
    parser = OptionParser(usage=usage)
    parser.add_option("-u", "--url", dest="url", help="target URL")

    (options, args) = parser.parse_args()
    #options.url=targetUrl
    if options.url is None:
        parser.print_help()
        exit()

    t = Target(options.url)
    s = Engine(t)
    s.addOption("crawl", True)
    s.addOption("forms", True)
    s.addOption("threads", 1)
    if s.start():
        exit()
Exemplo n.º 10
0
class Game:
	"""
		Description: Provides a game entity that represents the entirety of the game. Game is composed of engine
				     to render graphics and to maintain frame rate and a state which handles game logic.

	"""

	engine = Engine()
	state = State()

	def __init__(self):
		pass

	def run(self) -> None:
		"""
		Runs game. Calls run_event from state to signal that next event should be executed.
		keep_running returns false when "X" in top right corner of game window is clicked
		"""
		while self.engine.should_run():
			self.engine.clear_screen()
			self.state.run_event(self.engine.get_dt())
			self.engine.update_screen(self.state.get_objects_to_render(), self.state.get_sprites())
Exemplo n.º 11
0
 def __init__(self):
     self.database = Database()
     self.engine = Engine()
     self.service = self.engine.service
Exemplo n.º 12
0
from core.engine import Engine

Engine("Login")
Engine("Home")
Exemplo n.º 13
0
from flask import Flask
from core.engine import Engine
import os

## Create app
app = Flask(__name__)

## Create engine
engine = Engine()

## Look up which is the current path
APP_ROOT = os.path.dirname(os.path.abspath(__file__))

## Specify the upload directory target
app.config['UPLOAD_FOLDER'] = os.path.join(APP_ROOT, 'dynamic')

## Get the views
from webapp import views
Exemplo n.º 14
0
args = arg_parser.parse_known_args()[0]

# add manually trade mode
args.backtest = True
# args.live = True
# args.paper = True

# usage
# print(arg_parser.format_help())

# print current options
print(args)

# check whether trade mode is provided, otherwise exit
if not args.backtest and not args.live and not args.paper:
    print(
        "Missing trade mode argument (backtest, paper or live). See --help for more details."
    )
    exit(0)
else:
    # initialize and run Engine
    engine = Engine(trade_mode_input='backtest', plot_input=True)
    engine.run()  # problems with exit

# data downloaded: pandas dataframe
data = engine.history
print(data.columns)
print(data.shape)
print(data.describe())
# dates = data.date
Exemplo n.º 15
0
# add manually trade mode
args.backtest = True
# args.live = True
# args.paper = True

# usage
# print(arg_parser.format_help())

# print current options
print(args)

# check whether trade mode is provided, otherwise exit
if not args.backtest and not args.live and not args.paper:
    print(
        "Missing trade mode argument (backtest, paper or live). See --help for more details."
    )
    exit(0)
else:
    # initialize and run Engine
    engine = Engine(trade_mode_input='backtest',
                    plot_input=True,
                    strategy='bumblebee')
    engine.run()  # problems with exit

# data downloaded: pandas dataframe
data = engine.history
print(data.columns)
print(data.shape)
print(data.describe())
# dates = data.date
Exemplo n.º 16
0
def main():

    print(args)
    engine = Engine()
    engine.run()
Exemplo n.º 17
0
# project_dir/main.py
# from core.engine import Engine    # 导入引擎
#
# from .spiders.baidu import BaiduSpider
# from .spiders.douban import DoubanSpider
# from .pipelines import BaiduPipeline, DoubanPipeline
# # 此处新增
# from .spider_middlewares import TestDownloaderMiddleware1, TestDownloaderMiddleware2
# from .downloader_middlewares import TestSpiderMiddleware1, TestSpiderMiddleware2
# if __name__ == '__main__':
#     baidu_spider = BaiduSpider()    # 实例化爬虫对象
#     douban_spider = DoubanSpider()    # 实例化爬虫对象
#     spiders = {BaiduSpider.name: baidu_spider, DoubanSpider.name: douban_spider}
#     pipelines = [BaiduPipeline(), DoubanPipeline()]  # 管道们
#     spider_mids = [TestSpiderMiddleware1(), TestSpiderMiddleware2()]  # 多个爬虫中间件
#     downloader_mids = [TestDownloaderMiddleware1(), TestDownloaderMiddleware2()]  # 多个下载中间件
#     # engine = Engine(spiders)    # 传入爬虫对象
#     engine = Engine(spiders, pipelines=pipelines,
#                     spider_mids=spider_mids, downloader_mids=downloader_mids)    # 传入爬虫对象
#     engine.start()    # 启动引擎

# project_dir/main.py
from core.engine import Engine  # 导入引擎

if __name__ == '__main__':
    engine = Engine()  # 创建引擎对象
    engine.start()  # 启动引擎
Exemplo n.º 18
0
#!/usr/bin/env python3
import argparse

from core.console import Console
from core.engine import Engine
from core.interpreter import Interpreter
from ports.art_net import ArtNetPort

if __name__ == '__main__':
    ap = argparse.ArgumentParser(
        description="Theatrical lighting control engine/language interpreter.")
    ap.add_argument(
        'file',
        nargs='?',
        help=
        'A file of lxscript code to run before entering the interactive environment'
    )
    ap.add_argument('--address',
                    help='IP address to send ArtNet data to',
                    default='<broadcast>')
    args = ap.parse_args()

    engine = Engine([ArtNetPort(1, address=args.address)])

    if args.file:
        with open(args.file, 'r') as file:
            Interpreter(engine).run(file.read())

    Console(engine).cmdloop()
Exemplo n.º 19
0
# -*- coding: utf-8 -*-

import os
import sys
import json
from core import watson as w, solr
import psycopg2
import csv
import urlparse
from core.engine import Engine
from autocorrect import spell

watson = w.ConversationAPI(w.graduate_affairs_2_config())
demo_watson = w.ConversationAPI(w.rohan_admissions_config())
engine = Engine('training/question-answers-2016-11-27.tsv',
                'training/general-intents.csv')

import requests
import flask
from flask import Flask, request
from flask import render_template
from flask_bootstrap import Bootstrap


def create_app():
    app = Flask(__name__)
    Bootstrap(app)

    return app

Exemplo n.º 20
0
Create a Scene that store objects, the scene must include the optimised data structure.
Create a camera.
Create a light source.
Add objects to the Scene.
Generate data structure for the Scene with optimize().

Create an engine object with that contains methods for ray tracings.
Give the scene to the engine that outputs a picture.

Show the picture.

"""

if __name__ == "__main__":

    engine = Engine(500, 500)

    camera = Camera([0, 0, 0], [1, 0, 0], [0, -1, 0], fov=1)
    #camera = ThinLensCamera([0,0,0], [1,0,0], [0,-1,0], radius=0.0, focal_distance=6, fov=1)

    #light = Light([10,0,10])
    #light = LightProb("hdrmap/grace_probe.pfm")
    light = LightProb("hdrmap/stpeters_probe.pfm")

    scene = Scene(light)

    #scene.addobject(Sphere([0,0,0], 1000, anti=True))

    #scene.addobject(Triangle(([-1000, -1000, 200], [1000,-1000, 200], [1000,1000, 200]), color=[255,0,0]))
    #scene.addobject(Triangle(([-1000, -1000, 200], [1000,1000, 200], [-1000, 1000, 200])))
Exemplo n.º 21
0
def run():
    from core.engine import Engine
    game_config = Config()
    GameEngine = Engine(game_config)
    GameEngine.run()
Exemplo n.º 22
0
 def __init__(self):
     self.db = Database()
     self.db.create_schema()
     self.query = self.db.session.query(Email)
     self.engine = Engine()
     self.service = self.engine.service
Exemplo n.º 23
0
 def __init__(self):
     os.chdir('./global_vars')
     from core.engine import Engine
     os.chdir('..')
     self.engine = Engine()
Exemplo n.º 24
0
def main(args):

    engine = Engine(args, 'config.ini')
    engine.run()
Exemplo n.º 25
0
def main():
    engine = Engine()
    engine.run()
Exemplo n.º 26
0
def main():
    banner()
    usage = "usage: %prog [options]"

    parser = OptionParser(usage=usage)
    parser.add_option("-u", "--url", dest="url", help="target URL")
    parser.add_option("--post",
                      dest="post",
                      default=False,
                      action="store_true",
                      help="try a post request to target url")
    parser.add_option("--data", dest="post_data", help="posta data to use")
    parser.add_option("--threads",
                      dest="threads",
                      default=1,
                      help="number of threads")
    parser.add_option("--http-proxy",
                      dest="http_proxy",
                      help="scan behind given proxy (format: 127.0.0.1:80)")
    parser.add_option("--tor",
                      dest="tor",
                      default=False,
                      action="store_true",
                      help="scan behind default Tor")
    parser.add_option("--crawl",
                      dest="crawl",
                      default=False,
                      action="store_true",
                      help="crawl target url for other links to test")
    parser.add_option("--forms",
                      dest="forms",
                      default=False,
                      action="store_true",
                      help="crawl target url looking for forms to test")
    parser.add_option("--user-agent",
                      dest="user_agent",
                      help="provide an user agent")
    parser.add_option("--random-agent",
                      dest="random_agent",
                      default=False,
                      action="store_true",
                      help="perform scan with random user agents")
    parser.add_option("--cookie",
                      dest="cookie",
                      help="use a cookie to perform scans")
    parser.add_option("--dom",
                      dest="dom",
                      default=False,
                      action="store_true",
                      help="basic heuristic to detect dom xss")

    (options, args) = parser.parse_args()
    if options.url is None:
        parser.print_help()
        exit()

    # Build a first target
    print "[+] TARGET: %s" % options.url

    if options.post is True:
        print " |- METHOD: POST"
        if options.post_data is not None:
            print " |- POST data: %s" % options.post_data
            t = Target(options.url, method='POST', data=options.post_data)
        else:
            error('No POST data specified: use --data', ' |- ')
            exit()
    else:
        print " |- METHOD: GET"
        t = Target(options.url)

    # Build a scanner
    s = Engine(t)

    # Lets parse options for some proxy setting
    if options.http_proxy is not None and options.tor is True:
        error('No --tor and --http-proxy together!', ' |- ')
        exit()
    elif options.tor is False and options.http_proxy is not None:
        s.addOption("http-proxy", options.http_proxy)
        print " |- PROXY: %s" % options.http_proxy
    elif options.tor is True:
        s.addOption("http-proxy", "127.0.0.1:8118")
        print " |- PROXY: 127.0.0.1:8118"

    # User Agent option provided?
    if options.user_agent is not None and options.random_agent is True:
        error('No --user-agent and --random-agent together!', ' |- ')
    elif options.random_agent is False and options.user_agent is not None:
        s.addOption("ua", options.user_agent)
        print " |- USER-AGENT: %s" % options.user_agent
    elif options.random_agent is True:
        s.addOption("ua", "RANDOM")
        print " |- USER-AGENT: RANDOM"

    # Cookies?
    if options.cookie is not None:
        s.addOption("cookie", options.cookie)
        print " |- COOKIE: %s" % options.cookie

    # Do you want to crawl?
    if options.crawl is True:
        s.addOption("crawl", True)

    # Do you want to crawl forms?
    if options.forms is True:
        s.addOption("forms", True)

    # Dom scan?
    if options.dom is True:
        s.addOption("dom", True)

    # How many threads?
    s.addOption("threads", int(options.threads))

    # Start the scanning
    if s.start():
        exit()
Exemplo n.º 27
0
# Entry point for the application

import os
import json
from pathlib import Path

from core.engine import Engine

if __name__ == '__main__':
    cfg_path = Path(f'{os.getcwd()}/config/config.json')
    with open(cfg_path) as config_file:
        config = json.load(config_file)

    Engine().init(config)
    Engine().run()
Exemplo n.º 28
0
def main():
    manager, port, downloaders = parseCommandLineArgs()
    engine = Engine(downloaders, manager, port)
    engine.start()
    raw_input("press any key to stop....\n")
    engine.stop()