Beispiel #1
0
    def recieve_msg(self, msg):
        if msg == "win":
            pass
        elif msg == "":
            pass
        else:
            try:
                msg = msg[1:]
                print(msg[1:])
                sub_object = json.loads(msg[1:])
                print(sub_object)
                if "reward" in msg:
                    object = Factory.challenge()
                    object.deep = sub_object["deep"]
                    object.treeType = sub_object["treeType"]
                    object.order = sub_object["order"]
                    self.challenge = object
                    print("a3")

                else:
                    object = Factory.token()
                    object.int_value = sub_object["int_value"]
                    object.tree_type = sub_object["tree_type"]
                    self.tokens.append(object)
                    print("a4")
            except json.JSONDecodeError:
                print("error")
                pass
            finally:
                pass
Beispiel #2
0
class RadioVars:
    static = Factory.IntVar()
    speed = Factory.IntVar()

    def __init__(self):
        self.speed.set(10)
        self.static.set(0)
Beispiel #3
0
 def __init__(self, **kwargs):
     super(KeymapMenu.Tetris, self).__init__("KeymapMenu.Tetris", header_font=MENU_HEADER_FONT, option_font=MENU_OPTION_FONT, xcenter=True, **kwargs)
     self.header = "Tetris-map"
     self.menu = Factory.textBoxes(
             [("Player 1", lambda: self.call(self.Player1, caption="Loltris - Tetris player 1 keymap")),
              ("Player 2", lambda: self.call(self.Player2, caption="Loltris - Tetris player 2 keymap")),
             ],
             self,
             font=MENU_OPTION_FONT,
             colors={"background":self.colorscheme["background"], "font":self.colorscheme["option"]},
             fill=MENU_3DBORDER_BACKGROUND,
             xcenter=True,
             )
     self.menu.extend(Factory.variableTextBoxes(
             [( action.replace("_", " ").capitalize() + ": {key}",
                ## Nested lambdas are used here to cirumvent an issue with python closures. (http://code.activestate.com/recipes/502271/)
                ## Basically if you don't nest the lambdas, you will end up with every single functions having the last action in
                ## the list of dictionary keys.
                {"key": (lambda action_: lambda _: Utils.keyToString(Shared.keymap["game"][action_]))(action) },
                lambda: modifyKeymap(self, Shared.keymap["game"], action))
                for action in Shared.keymap["game"]
                if isinstance(Shared.keymap["game"][action], int) ## Skip the player1 and player2 sub-dictionaries
                ],
             self,
             font=MENU_OPTION_FONT,
             colors={"background":self.colorscheme["background"], "font":self.colorscheme["option"]},
             fill=MENU_3DBORDER_BACKGROUND,
             xcenter=True,
             ))
     self.setupObjects()
Beispiel #4
0
def test_bunch_recursive():
    b = Factory.Bunch(pants="jeans")
    b.sub = Factory.Bunch(shirt="buttons")
    b2 = b.harden()
    assert b is not b2
    assert b == b2
    assert b.sub is not b2.sub
    assert b.sub == b2.sub
Beispiel #5
0
 def __init__(self):
     self.planimetry = Factory.create_planimetry()
     self.column = Factory.create_column()
     self.gorgeous_column = GorgeousColumn(5, 18)
     self.top_triangle = Triangle(42, 10)
     self.lateral_roof = Triangle(52, 201)
     self.main_roof = Roof(72, 65.16, 16)
     self.arch = Arch(4, 15, 1.5)
Beispiel #6
0
    def addSprite(self,
                  myDict,
                  myGroup,
                  specificGroup,
                  sprite=None,
                  factoryFlag=0):
        x = 0
        y = 0
        if not factoryFlag:
            x = sprite.x
            y = sprite.y
        else:
            x = self.box.x
            y = self.box.y
        checkIfOccupied = myDict.get((x, y))

        # print(checkIfOccupied)
        if not checkIfOccupied:
            if factoryFlag:
                checkIfLeftNeighborOccupied = myDict.get((x - 1, y))
                checkIfRightNeighborOccupied = myDict.get((x + 1, y))
                checkIfTopNeighborOccupied = myDict.get((x, y - 1))
                checkIfBottomNeighborOccupied = myDict.get((x, y + 1))
                if not checkIfLeftNeighborOccupied:
                    print(10)
                    sprite = Factory(self, self.box.x, self.box.y,
                                     self.box.x - 1, self.box.y,
                                     self.emotion.value)
                    self.spriteDict[(self.box.x - 1, self.box.y)] = sprite
                elif not checkIfRightNeighborOccupied:
                    x += 1
                    sprite = Factory(self, self.box.x, self.box.y,
                                     self.box.x + 1, self.box.y,
                                     self.emotion.value)
                    self.spriteDict[(self.box.x, self.box.y)] = sprite
                elif not checkIfTopNeighborOccupied:
                    sprite = Factory(self, self.box.x, self.box.y, self.box.x,
                                     self.box.y - 1, self.emotion.value)
                    self.spriteDict[(self.box.x, self.box.y - 1)] = sprite
                elif not checkIfBottomNeighborOccupied:
                    y += 1
                    sprite = Factory(self, self.box.x, self.box.y, self.box.x,
                                     self.box.y + 1, self.emotion.value)
                    self.spriteDict[(self.box.x, self.box.y)] = sprite
                else:
                    return
            self.allSprites.add(sprite)
            myGroup.add(sprite)
            specificGroup.add(sprite)
            myDict[(x, y)] = sprite
            if sprite.type == SPRITETYPE.SEA:
                return
            self.constructionList.append(sprite)
Beispiel #7
0
def CopyAndUnzipLatestDevSandbox():
    fullSourcePath = Factory.CombinePath(Config.RevitDevSandboxDestination,
                                         Config.RevitDevSandboxFolderName)
    Factory.DeleteFolderAndContents(fullSourcePath)
    Factory.CreateDirectory(fullSourcePath)
    zipfile = Factory.GetLatestZipFileWithMaskInDir(
        Config.RevitDevSandboxMask, Config.RevitDevSandboxSource)
    fullzippath = Factory.CombinePath(Config.RevitDevSandboxSource, zipfile)
    Factory.CopyFileToDir(fullzippath, Config.RevitDevSandboxDestination)
    Factory.Unzip(fullzippath, fullSourcePath)
    journalsFolder = Factory.CombinePath(fullSourcePath, "Journals")
    Factory.CreateDirectory(journalsFolder)
def getProfiler():
    try:
        name = package_home(".", 'SysProf', platform.system().lower(), 'profiler.Profiler')
        istance = Factory.class_forname(name)
    except FactoryException as e:
        raise LocalProfilerException(e)
    return istance
Beispiel #9
0
def getRisorsa(path,name):
    try:
        ris= Factory.class_forname(path)
        ris.setName(name)
    except FactoryException as e:
        raise RisorsaException(e)
    return ris
Beispiel #10
0
    def Evaluate(self, pop):

        #print "ChainResEval: evaluating pop"

        assert (len(self.Exps) == 0)

        self.Individuals = pop
        nextID = Context.Database.NextAvailableID()

        exps = []
        for indi in pop:
            exp = Factory.ExperimentFromIndividual(Context.SimulationChain,
                                                   indi)
            exp.ID = nextID
            indi.ID = nextID
            Context.Database.append(exp)
            exps.append(exp)
            self.Exps.add(exp.ID)
            nextID += 1

        for exp in exps:
            self.PostMessage({"what": "EVALUATE", "exp": exp})

        while not self.AllDone.is_set():
            #print "ChainResEval: waiting"
            self.AllDone.wait(1.0)
        #print "ChainResEval: waiting over"
        self.AllDone.clear()
        self.Individuals = None

        Context.Database.Export(open("%s.tmp.plan" % Context.Name, "w"))
Beispiel #11
0
def test_bunch_equals():
    b = Factory.Bunch(pants="jeans", shirt="dressy")
    c = b.harden()
    assert c is not b
    assert c == b
    c.shirt = "sloppy"
    assert c != b
Beispiel #12
0
def test_missing_attr():
    fac = Factory.Factory(lambda x: x)
    assert_raises(AttributeError, getattr, fac, 'x')
    assert_raises(AttributeError, getattr, fac, 'y')
    fac.x = 'x'
    obj = fac()
    assert obj == 'x'
Beispiel #13
0
def test_getattr():
    def do_stuff(x, y):
        return x, y

    fac = Factory.Factory(do_stuff, x=1)
    assert fac.x == 1
    assert_raises(AttributeError, getattr, fac, 'y')
Beispiel #14
0
def getRisorsa(path, name):
    try:
        ris = Factory.class_forname(path)
        ris.setName(name)
    except FactoryException as e:
        raise RisorsaException(e)
    return ris
Beispiel #15
0
def test_bultin_instancemethod():
    L = [1, 2, 3]
    fac = Factory.Factory(L.append)
    fac(4)
    assert L == [1, 2, 3, 4]
    fac.bind(5)
    fac()
    assert L == [1, 2, 3, 4, 5]
def getProfiler():
    try:
        name = package_home(".", 'SysProf',
                            platform.system().lower(), 'profiler.Profiler')
        istance = Factory.class_forname(name)
    except FactoryException as e:
        raise LocalProfilerException(e)
    return istance
Beispiel #17
0
def test_subclass_of_builtin():
    class MyList(list):
        pass

    fac = Factory.Factory(MyList)
    fac.bind((1, 2, 3))
    L = fac()
    assert L == [1, 2, 3]
    assert isinstance(L, MyList)
Beispiel #18
0
    def updatestate(self):
        if not self.state:
            return

        state = self.state
        if not self.first_state_loaded:
            state = self.first_state
            self.first_state_loaded = True

        ##get all objects and set new position and speed
        for id in state:
            val = state[id]
            if id not in ScreenObject.screenObjs.keys():
                Factory.MakeScreenObject(self, val, id)
            else:
                obj = ScreenObject.screenObjs[id]
                Factory.LoadScreenObject(obj, val)
        self.state = None
Beispiel #19
0
def test_delattr():
    def called_with(x='pants'):
        return x

    fac = Factory.Factory(called_with)
    fac.x = 'shirt'
    assert fac() == 'shirt'
    del fac.x
    assert fac() == 'pants'
Beispiel #20
0
    def initializeTerrain(self):
        # initDict contains the initial terrain, and has the same structure of "myDict",
        # but the values are int instead of booleans
        # e.g: 1=water, 2=building, 3=tree, 4=land...
        # We will be needing a dictionary for every kind of terrain, or we may need to change the value type of myDict
        # into integers (and modify the )
        initTerrin = []
        # print("initialize")
        with open("Terrain.txt", "rt") as File:
            line = File.readline()
            while line:
                initTerrin.append(line)
                line = File.readline()
            File.close()
        # print(initTerrin)

        for x in range(0, SCREENWIDTHBYTILES):
            for y in range(0, SCREENHEIGHTBYTILES):
                type = int(initTerrin[y][x])
                # print(SPRITETYPE.SEA.value)
                if type == SPRITETYPE.TREE.value:
                    tree = Tree(self, x, y, -1)
                    self.addSprite(self.spriteDict, self.allSprites,
                                   self.allTrees, tree)
                    # self.Treedict[(x, y)] = tree
                elif type == SPRITETYPE.SEA.value:
                    sea = Sea(self, x, y)
                    self.addSprite(self.spriteDict, self.allSprites,
                                   self.allSea, sea)
                    self.seaX = x
                    self.seaY = y
                    # self.Seadict[(x, y)] = sea
                    # print("sea")
                elif type == SPRITETYPE.FACTORY.value:
                    factory = Factory(self, x - 1, y, x, y, -3)
                    self.addSprite(self.spriteDict, self.allSprites,
                                   self.allFactories, factory)
                    self.spriteDict[(x - 1, y)] = factory
                    # self.factoryCount += 1
                    # self.facTorydict[(x, y)] = factory
                elif type == SPRITETYPE.HOUSE.value:
                    house = House(self, x, y, -2)
                    self.addSprite(self.spriteDict, self.allSprites,
                                   self.allHouses, house)
                    # self.houseCount += 1
            try:
                checkSpritesCompletion = lambda sprite: not sprite.nextTurn()
                self.constructionList = list(
                    filter(checkSpritesCompletion, self.constructionList))
            except ():
                pass
                # self.dict[(x, y)] = house
            # print(self.treeCount)
        self.startTreeCount = self.treeCount
        self.seaX = 0
        self.seaY += 1
Beispiel #21
0
def test_callable_object():
    class CallMe(object):
        def __init__(self, x):
            self.x = x

        def __call__(self, y):
            return self.x + y

    fac = Factory.Factory(CallMe(1))
    assert fac(1) == 2
Beispiel #22
0
def test_bind_varargs():
    def mysum(*args):
        return sum(args)

    fac = Factory.Factory(mysum)
    fac.bind(1, 2, 3)
    fac.bind(4, 5, 6)
    fac.bind(7, 8, 9)
    assert fac() == 45
    assert fac(10) == 55
Beispiel #23
0
    def test_karusel(self):
        factory = Factory.Factory_converter()
        obj = Person("Amongus")
        factory.convert_obj_to_file(obj, "test.json")
        factory.convert("test.json", "test1.pickle")
        factory.convert("test1.pickle", "test2.yaml")
        factory.convert("test2.yaml", "test3.toml")

        obj2 = factory.convert_to_obj("test3.toml")
        self.assertEqual(obj.name, obj2.name)
Beispiel #24
0
    def __init__(self, spec):
        Method.__init__(self)

        self.Chromosome = Factory.Chromosome(Context.SimulationChain)
        self.ResEval = ChainResponseEvaluator()
        self.ResEval.Start()

        self.PenEval = Factory.CreatePenaltyEvaluator(spec)
        self.FitnessEval = EA.FitnessEvaluator()

        optiConfig = spec["OptimizerConfig"]
        popSize = optiConfig["PopulationSize"]
        self.OptimizerConfig = optiConfig

        postIterCallback = lambda gen, pop: self.PostIteration(gen, pop)

        self.BestExperiment = None

        if spec["Optimizer"] == "GA":
            self.Optimizer = EA.MonoObjectiveGA(self.Chromosome, self.ResEval,
                                                self.PenEval, self.FitnessEval,
                                                popSize, 2)
            self.Optimizer.PostIterationCallback = postIterCallback
            self.HistoryFile = open("%s.history.dat" % Context.Name, "w")
        elif spec["Optimizer"] == "SurrogateGA":
            Context.Database.Import(open(optiConfig["DOE"]))
            pop = Factory.PopulationFromPlan(self.Chromosome, Context.Database)
            self.Optimizer = EA.MonoObjectiveSurrogateGA(
                self.Chromosome, self.ResEval, self.PenEval, self.FitnessEval,
                pop)
        elif spec["Optimizer"] == "ParetoGA":
            self.Optimizer = EA.SPEA2(self.Chromosome, self.ResEval,
                                      self.PenEval,
                                      optiConfig["PopulationSize"],
                                      optiConfig["ArchiveSize"])
        elif spec["Optimizer"] == "ParetoSurrogateGA":
            Context.Database.Import(open(optiConfig["DOE"]))
            pop = Factory.PopulationFromPlan(self.Chromosome, Context.Database)
            self.Optimizer = EA.ParetoSurrogateGA(
                self.Chromosome, self.ResEval, self.PenEval, pop, popSize,
                optiConfig["ArchiveSize"], optiConfig["Update"],
                optiConfig["UpdateTruncation"])
Beispiel #25
0
def test_bind_varargs_preserves_order():
    # Now for a non-commutative operation.
    def join(*args):
        return ''.join(args)

    fac = Factory.Factory(join)
    fac.bind('a', 'b', 'c')
    fac.bind('d', 'e', 'f')
    fac.bind('g', 'h', 'i')
    assert fac() == 'abcdefghi'
    assert fac('j', 'k', 'l') == 'abcdefghijkl'
Beispiel #26
0
    def __init__(self, **kwargs):
        super(OptionsMenu, self).__init__("OptionsMenu", header_font=MENU_HEADER_FONT, option_font=MENU_OPTION_FONT, xcenter=True, **kwargs)
        self.header = "Options"
        self.options = Load.loadOptions()
        self.menu = Factory.textBoxes([
                ("Keymaps", lambda: self.call(KeymapMenu, caption=self.caption)),
                ], self, font=MENU_OPTION_FONT, colors={"background":self.colorscheme["background"],
                                                        "font":self.colorscheme["option"], },
                fill=MENU_3DBORDER_BACKGROUND,
                xcenter=True,
                )

        ## >inb4 immature jokes
        def turnOn(option, options):
            Log.debug(option)
            if options.get(option) != None:
                Log.warning("Turning on non-existent option: {}".format(repr(option)))
            options[option] = True
            Save.saveOptions()
        def turnOff(option, options):
            Log.debug(option)
            if options.get(option) != None:
                Log.warning("Turning off non-existent option: {}".format(repr(option)))
            options[option] = False
            Save.saveOptions()

        self.menu.extend(
                Factory.basicSwitches([
                    ("Uber-Tetromino", "uber_tetromino"),
                    ("Flip tetromino", "flip_tetromino"),
                    ], self, turnOn, turnOff, Shared.options["gameplay"],
                    font=MENU_OPTION_FONT,
                    colors=SWITCH_OPTION_COLORS,
                    boxwidth=8,
                    box_center=True,
                    fill=MENU_3DBORDER_BACKGROUND,
                    )
                )

        self.setupObjects()
Beispiel #27
0
    def __init__(self, **kwargs):
        super(MainMenu, self).__init__(
                "MainMenu", onHeaderClick=lambda: Webbrowser.open(PROJECT_SITE),
                header_font=MENU_HEADER_FONT, option_font=MENU_OPTION_FONT, isroot=True, xcenter=True,
                soundtrack=Path.join(Load.MUSICDIR, "jazz_cat_infinite_loop_cut.ogg"), sound_enabled=SOUND_ENABLED, **kwargs)

        self.title_blocks = BlockText.render(TITLE_TEXT, font=Load.loadBlockFont("standard"))
        blockwidth = (self.width) // len(self.title_blocks[0])
        Log.debug("title_board.blockwidth = {}".format(blockwidth))
        self.addJob("title_board",
                    Jobs.Board(
                        self,
                        y=SPACER,
                        height=len(self.title_blocks),
                        width=len(self.title_blocks[0]),
                        blockwidth=blockwidth,
                        bgcolor=self.bgcolor,
                        queue=100,
                        draw_grid=False,
                        draw_border=False,
                        )
                    )
        self.jobs.title_board.x = (self.width // 2) - (self.jobs.title_board.width // 2)
        for x, y in Matrix.matrixToSet(self.title_blocks):
            self.jobs.title_board.blocks[(x, y)] = (0xaa,0xaa,0xaa)
        self.options_pos[1] = self.jobs.title_board.y + self.jobs.title_board.height + SPACER*2

        self.menu = Factory.textBoxes([
                ("Single Player", lambda: self.call(TetrisGame.TetrisGame, caption="Loltris")),
                ("Two Player", lambda: self.call(TwoPlayerTetrisGame.TwoPlayerTetris, caption="Loltris - Two Player")),
                ("LAN Play", lambda: self.call(LANTetrisGame.LANMenu, caption="Loltris - LAN play")),
                ("Options", lambda: self.call(OptionsMenu, caption="Loltris - Options")),
                ("Creative", lambda: self.call(MakeTetromino.MakeTetromino, caption="Loltris - Creator")),
                ("Scores", lambda: self.call(HighscoreExplorer.HighscoreList, caption="Loltris - Highscores")),
                ("Credits", lambda: self.call(Credits.Credits, caption="Loltris - Credits")),
                ("Homepage", lambda: Webbrowser.open(PROJECT_SITE)),
                ("SandBox", lambda: self.call(SandBox.SandBox, caption="Loltris - SandBox")),
                ("Exit", self.quit),
                ],
                self,
                font=MENU_OPTION_FONT,
                fill=MENU_3DBORDER_BACKGROUND,
                xcenter=True,
                colors={
                    "background":self.colorscheme["background"],
                    "font":self.colorscheme["option"],
                    },
                )
        self.setupObjects()
        #self.loadHighscores()
        ## XXX: Temporary bugfix, scroll_filler is drawn on every frame while the board is not.
        del self.jobs.scroll_filler
Beispiel #28
0
 def __init__(self, **kwargs):
     super(KeymapMenu, self).__init__("KeymapMenu", header_font=MENU_HEADER_FONT, option_font=MENU_OPTION_FONT, xcenter=True, **kwargs)
     self.header = "Keymaps"
     self.menu = Factory.textBoxes([
             ("Tetris", lambda: self.call(self.Tetris, caption="Loltris - Tetris keymap")),
             ("Menu", lambda: self.call(self.Menu, caption="Loltris - Menu keymap")),
             ], self, font=MENU_OPTION_FONT, colors={"background":self.colorscheme["background"],
                                                     "font":self.colorscheme["option"], },
             fill=MENU_3DBORDER_BACKGROUND,
             xcenter=True,
             )
     self.setupObjects()
     self.getting = None
Beispiel #29
0
def test_basic_use_with_cooperative_constructors():
    fac = Factory.Factory(C)
    fac.z = 'z'
    fac.y = 'y'
    fac.x = 'x'
    obj = fac()
    assert obj.x == 'x'
    assert obj.y == 'y'
    assert obj.z == 'z'
    fac.bind(x='xx', y='yy')
    obj = fac()
    assert obj.x == 'xx'
    assert obj.y == 'yy'
    assert obj.z == 'z'
Beispiel #30
0
 def __init__(self, **kwargs):
     super(PauseMenu, self).__init__("PauseMenu", header_font=MENU_HEADER_FONT, option_font=MENU_OPTION_FONT, isroot=True, xcenter=True, **kwargs)
     self.header = "Pause"
     self.menu = Factory.textBoxes([
             ("Continue", self.quitGame),
             ("Exit to main menu", lambda: self.quitGame("MainMenu")),
             ("Exit Game", self.quit),
             ], self, font=MENU_OPTION_FONT, colors={"background":self.colorscheme["background"],
                                                     "font":self.colorscheme["option"], },
             fill=MENU_3DBORDER_BACKGROUND,
             xcenter=True,
             )
     self.setupObjects()
     self.running = self.mainLoop
Beispiel #31
0
def test_permits_varkwargs():
    def f(**kwargs):
        return kwargs  # This accepts any and all args.

    fac = Factory.Factory(f)
    fac.bind(x='x', y='y')
    assert fac() == {'x': 'x', 'y': 'y'}

    class A(object):
        def __init__(self, **kwargs):
            pass

    class B(A):
        def __init__(self, **kwargs):
            super(B, self).__init__(**kwargs)

    class C(B):
        def __init__(self, b=None):
            super(C, self).__init__({'b': b})

    B_fac = Factory.Factory(B)  # Should accept variable kwargs.
    C_fac = Factory.Factory(C)  # Should not accept variable kwargs.
    assert B_fac(x=1)
    assert_raises(AttributeError, C_fac.bind, x=1)
Beispiel #32
0
    def generator(self):
        '''
        :return:产生一个符合要求的随机整数,浮点数,或字符串
        '''
        if self.eleType is int:
            factory = Factory.elementSamplingFactory(self.condition, 1)
            while 1:
                ele = factory.randomIntSampling()
                for x in ele:
                    yield x

        if self.eleType is float:
            factory = Factory.elementSamplingFactory(self.condition, 1)
            while 1:
                ele = factory.randomFloatSampling()
                for x in ele:
                    yield x
        if self.eleType is str:
            factory = Factory.elementSamplingFactory(self.condition, 1,
                                                     self.len)
            while 1:
                ele = factory.randomStrSampling()
                for x in ele:
                    yield x
Beispiel #33
0
        def __init__(self, **kwargs):
            super(KeymapMenu.Graphics, self).__init__("GraphicsMenu", header_font=MENU_HEADER_FONT, option_font=MENU_OPTION_FONT, xcenter=True, **kwargs)
            ## >inb4 immature jokes
            def turnOn(option, options):
                options[option] = True
                Save.saveOptions()
            def turnOff(option, options):
                options[option] = False
                Save.saveOptions()

            self.menu = \
                Factory.basicSwitches([
                    ("Fullscreen", "fullscreen"),
                    ], self, turnOn, turnOff, Shared.options["gameplay"],
                    font=MENU_OPTION_FONT,
                    colors=SWITCH_OPTION_COLORS,
                    boxwidth=8,
                    box_center=True,
                    fill=MENU_3DBORDER_BACKGROUND,
                    )
Beispiel #34
0
import Base
import Factory
import Layout
from MethodUtils import CallBack

Factory = Factory.Factory(Base.Invalid, name="Printing")

class PageBreak(Layout.Box):
    """
        Will force a page break before printing any additional elements
    """
    def __init__(self, id=None, name=None, parent=None):
        Layout.Box.__init__(self, id=id, name=name, parent=parent)

        self.style['page-break-before'] = "always"

Factory.addProduct(PageBreak)


class HidePrint(Layout.Box):
    """
        Will hide any child elements from printing
    """
    def __init__(self, id=None, name=None, parent=None):
        Layout.Box.__init__(self, id=id, name=name, parent=parent)

        self.addClass('hidePrint')

Factory.addProduct(HidePrint)
Beispiel #35
0
    """

    def __init__(self, id=None, name=None, parent=None):
        WebElement.__init__(self, id, name, parent)
        self.tagName = "h2"

    def loadFromDictionary(self, valueDict):
        pass

    def content(self, variableDict=None, formatted=False):
        """
            Overrides content to return 'Invalid element' string
        """
        return "Invalid Element"

Factory.addProduct(Invalid)


class TemplateElement(WebElement):
    """
        A template WebElement is a web element that uses a template for its presantation and
        structure
    """
    factory = Factory
    template = None

    def __init__(self, id=None, name=None, parent=None, template=None, factory=None):
        WebElement.__init__(self, id, name, parent)
        self.tagName = 'div'

        if template:
Beispiel #36
0
    def addChildElement(self, childElement):
        if not self.toggle:
            return self.setToggleButton(Layout.Box.addChildElement(self, childElement))
        elif not self.menu:
            self.menu = Layout.Box.addChildElement(self, childElement)
            if self.id:
                self.menu.id = self.id + ":Content"
            self.menu.addClass("WebElementMenu")
            self.menu.addJavascriptEvent('onclick', 'isPopupOpen = true;')
            self.menu.hide()
            return self.menu
        else:
            return Layout.Box.addChildElement(self, childElement)

Factory.addProduct(DropDownMenu)


class CollapsedText(DropDownMenu):
    """
        Shows a limited amount of text revealing the rest when the user hovers over
    """
    properties = DropDownMenu.properties.copy()
    properties['lengthLimit'] = {'action':'classAttribute', 'type':'int'}
    properties['text'] = {'action':'setText'}

    def __init__(self, id=None, name=None, parent=None):
        DropDownMenu.__init__(self, id, name, parent)

        self.lengthLimit = 40
        self.label = self.addChildElement(Display.Label)
Beispiel #37
0
# -*- coding: utf-8 -*-
import Factory
if __name__ == '__main__':
    string = str(input("Please type the animal's name: "))
    ResultAnimal = Factory.get_classAnimal(string.upper())
    print(ResultAnimal)
Beispiel #38
0
        self.statusBar.addClass("WStatusBar")
        self.statusBar.hide()

        self.dropIndicator = self.statusBar.addChildElement(Display.Image())
        self.dropIndicator.setProperty('src', Base.IMAGES_URL + 'throbber.gif')
        self.dropIndicator.addClass("WDropIndicator")

        self.dropLabel = self.statusBar.addChildElement(Display.Label(id + "DropLabel"))
        self.dropLabel.setText("Drop Files Here")
        self.dropLabel.addClass("WDropLabel")

        self.files = self.addChildElement(Layout.Horizontal(id + "Files"))
        self.files.addClass("WFiles")

        baseFile = self.files.addChildElement(Layout.Vertical(id + "File"))
        baseFile.addClass("WFile")
        imageContainer = baseFile.addChildElement(Layout.Box())
        imageContainer.addClass("WImageContainer")
        preview = imageContainer.addChildElement(Display.Image())
        preview.addClass("WThumbnail")
        name = baseFile.addChildElement(Display.Label())
        name.addClass("WFileName")
        baseFile.hide()

        self.addScript(CallBack(self, 'jsConnections'))

    def jsConnections(self):
        return "WebElements.buildFileOpener('%s');" % self.fullId()

Factory.addProduct(FileUploader)
Beispiel #39
0
from MethodUtils import CallBack

Factory = Factory.Factory("Printing")

class PageBreak(Layout.Box):
    """
        Defines an area where a break in the page would be logical
    """
    __slots__ = ()

    def __init__(self, id=None, name=None, parent=None, **kwargs):
        Layout.Box.__init__(self, id=id, name=name, parent=parent)

        self.style['page-break-before'] = "always"

Factory.addProduct(PageBreak)


class UnPrintable(Layout.Box):
    """
        Defines content as being unprintable and therefore should be hidden from printing
    """
    __slots__ = ()

    def __init__(self, id=None, name=None, parent=None, **kwargs):
        Layout.Box.__init__(self, id=id, name=name, parent=parent)

        self.addClass('hidePrint')

Factory.addProduct(UnPrintable)
Beispiel #40
0
class NotEmpty(Validator):
    messages = {"notEmpty": "Please enter a value"}

    class ClientSide(Validator.ClientSide):
        def validate(self):
            with self.element.forElement.clientSide.value().IF == "" as context:
                context(self.showError(self.element.message("notEmpty")))
            return context

    def validate(self):
        if not self.forElement.value():
            self.showError(self.message("notEmpty"))


Factory.addProduct(NotEmpty)


class Int(Validator):
    messages = {"notInt": "Please enter an integer value"}

    class ClientSide(Validator.ClientSide):
        def validate(self):
            assignment = self.assign("value", self.element.forElement.clientSide.value())
            with self.value.IF != do.parseInt(self.value, 10) as context:
                context(self.showError(self.element.message("notInt")))

            return assignment(context)

    def validate(self):
        try:
Beispiel #41
0
    def toHtml(self, formatted=False, *args, **kwargs):
        """
            Changes toHtml behavior to only generate the html for the visible element
        """
        if self.stackElements:
            return self.visibleElement().toHtml(formatted=formatted, *args, **kwargs) or ""
        return ""

    def addChildElement(self, childElement, ensureUnique=True):
        self.stackElements.append(childElement)
        childElement.parent = self
        if len(self.stackElements) == 1:
            self.__setChildren__()
        return childElement

Factory.addProduct(Stack)


class Box(DOM.Div):
    """
        A container that allows child elements to be contained within
       the border of the container.
    """
    __slots__ = ()

Factory.addProduct(Box)


class Flow(Base.WebElement):
    """
        A container that does not impose a border around its childElements
Beispiel #42
0
Factory = Factory.Factory("DOM")

class A(WebElement):
    """
        Defines a link that when clicked changes the currently viewed page
    """
    __slots__ = ()
    tagName = "a"
    properties = WebElement.properties.copy()
    properties['href'] = {'action':'attribute'}
    properties['media'] = {'action':'attribute'}
    properties['rel'] = {'action':'attribute'}
    properties['target'] = {'action':'attribute'}
    properties['type'] = {'action':'attribute'}

Factory.addProduct(A)


class Abr(WebElement):
    """
        Defines an abbreviation or an acronym
    """
    __slots__ = ()
    tagName = "abr"

Factory.addProduct(Abr)


class Address(WebElement):
    """
        Defines contact info for the author of a document or article
Beispiel #43
0
        Base.WebElement.__init__(self, id, name, parent)

    def setDestination(self, destination):
        self.attributes['href'] = destination

    def destination(self):
        return self.attributes.get('href', "")

    def setText(self, text):
        self.textBeforeChildren = text
        self.emit('textChanged', text)

    def text(self):
        return self.textBeforeChildren

Factory.addProduct(Link)


class PopupLink(Link):
    """
        A link that will open the new page in a popup window
    """
    properties = Link.properties.copy()
    properties['width'] = {'action':'classAttribute'}
    properties['height'] = {'action':'classAttribute'}
    # the 'normal' flag allows you to retain the menu/toolbar
    properties['normal'] = {'action':'classAttribute'}
    properties['windowTitle'] = {'action':'classAttribute'}
    properties['separateWindow'] = {'action':'classAttribute', 'type':'bool'}

    def __init__(self, id=None, name=None, parent=None):
Beispiel #44
0
        container.style['float'] = align
        if width:
            container.style['vertical-align'] = 'middle'
            container.style['width'] = width

    def toHtml(self, valueDict=None, formatted=False):
        oldChildElements = self.childElements
        self.reset()
        for childElement in oldChildElements:
            self.__modifyChild__(childElement)
        lineBreak = Box.addChildElement(self, LineBreak())
        returnValue = Box.toHtml(self, valueDict, formatted=formatted)
        self.childElements = oldChildElements
        return returnValue

Factory.addProduct(Horizontal)


class Vertical(Box):
    """
        A container that encourage elements to be added vertically with minimum html
    """
    def __modifyChild__(self, childElement):
        height = childElement.style.pop('height', '')

        if not childElement.displayable:
            self.childElements.append(childElement)
        elif not childElement.tagName or height:
            container = Box()
            container.style['height'] = height
            childElement.style['height'] = "100%"
Beispiel #45
0
	def start(self):
		"""
			Starts the main loop of the interactive shell.
		"""
		
		# Command entered by the user
		cmd = ""
		self.logger.print_info("Type 'help' to show a list of available commands.")
		
		while (cmd.lower() != VmfShell.CMD_QUIT):
			try:
				self.output.write(VmfShell.PROMPT)
				user_input = sys.stdin.readline()
				tokens = user_input.rstrip().split()
				cmd = tokens[0]
				if (cmd.lower() == VmfShell.CMD_QUIT):
					pass
				elif (cmd.lower() == VmfShell.CMD_HELP):
					if (len(tokens) == 1):
						self.logger.print_info("{:s} <field>|all".format(VmfShell.CMD_SHOW))
						self.logger.print_info("{:s} <field> <value>".format(VmfShell.CMD_SET))
						self.logger.print_info("{:s} [field] {{bin, hex}}".format(VmfShell.CMD_HEADER))
						self.logger.print_info("{:s} <field>".format(VmfShell.CMD_HELP))
						self.logger.print_info("{:s} <field>".format(VmfShell.CMD_SEARCH))
						self.logger.print_info("{:s} <file>".format(VmfShell.CMD_SAVE))
						self.logger.print_info("{:s} <file>".format(VmfShell.CMD_LOAD))
						self.logger.print_info("{:s}".format(VmfShell.CMD_QUIT))
					else:
						param = tokens[1]
						if (param in Params.__dict__.keys()):
							help_msg = Params.parameters[param]['help']
							self.logger.print_info(help_msg)
							if (len(Params.parameters[param]['choices']) > 0):
								choices_msg = ', '.join([ choice for choice in Params.parameters[param]['choices']])
								self.logger.print_info("Available values: {:s}".format(choices_msg))
						else:
							self.logger.print_error("Unknown parameter/option: {:s}.".format(param))
				elif (cmd.lower() == VmfShell.CMD_SHOW):
					#
					# Displays the value of the given field
					#
					if (len(tokens) == 2):
						param = tokens[1]
						if (param in Params.parameters.keys()):
							value = Params.__dict__[param]
							if (isinstance(value, int)):
								value = "0x{:02x}".format(value)
							self.logger.print_info("{} = {}".format(param, value))
						elif param.lower() == "all":
							for p in Params.parameters.keys():
								value = Params.__dict__[p]
								self.logger.print_info("{} = {}".format(p, value))
						else:
							self.logger.print_error("Unknown parameter/option {:s}.".format(param))

					else:
						self.logger.print_error("Usage: {s} <field>".format(VmfShell.CMD_SHOW))
				elif (cmd.lower() == VmfShell.CMD_SET):
					#
					# Sets a field with the given value
					#
					# TODO: Issues with parameters with boolean values
					if (len(tokens) >= 3):
						param = tokens[1]
						value = ' '.join(tokens[2:])
						if (param in Params.__dict__.keys()):
							if (Params.parameters[param]["choices"]):
								if (value in Params.parameters[param]["choices"]):
									Params.__dict__[param] = value
									new_value = Params.__dict__[param]
									self.logger.print_success("{:s} = {:s}".format(param, new_value))
								else:
									self.logger.print_error("Invalid value ({:s}) for field {:s}.".format(value, param))
									self.logger.print_info("Values for field are : {:s}.".format(','.join(str(Params.parameters[param]["choices"]))))
							else:
								Params.__dict__[param] = value
								new_value = Params.__dict__[param]
								self.logger.print_success("{:s} = {:s}".format(param, new_value))
						else:
							self.logger.print_error("Unknown parameter {:s}.".format(param))
					else:
						self.logger.print_error("Usage: {:s} <field> <value>".format(VmfShell.CMD_SET))
				elif (cmd.lower() == VmfShell.CMD_HEADER):
					field = "vmfversion"
					fmt = "bin"
	
					if (len(tokens) >= 2):
						field = tokens[1]

					if (len(tokens) == 3):
						fmt = tokens[2]
					
					vmf_factory = Factory(_logger=self.logger)
					vmf_message = vmf_factory.new_message(Params)
					vmf_elem = vmf_message.header.elements[field]

					if (isinstance(vmf_elem, Field)):
						vmf_value = vmf_elem.value
					elif (isinstance(vmf_elem, Group)):
						vmf_value = "n/a"
					else:
						raise Exception("Unknown type for element '{:s}'.".format(field))

					vmf_bits = vmf_elem.get_bit_array()
					output = vmf_bits

					if (fmt == "bin"):
						output = vmf_bits.bin
					if (fmt == "hex"):
						output = vmf_bits.hex

					self.logger.print_success("{}\t{}\t{}".format(field, vmf_value, output))
				elif (cmd.lower() == VmfShell.CMD_SEARCH):
					keyword = ' '.join(tokens[1:]).lower()
					for p in Params.parameters.keys():
						help = Params.parameters[p]['help']
						if (p.lower() == keyword or keyword in help.lower()):
							self.logger.print_success("{:s}: {:s}".format(p, help))
				elif (cmd.lower() == VmfShell.CMD_SAVE):
					if len(tokens) == 2:
						file = tokens[1]
						
						tmpdict = {}
						for param in Params.parameters.keys():
							value = Params.__dict__[param]
							tmpdict[param] = value
							
						with open(file, 'w') as f:
							json.dump(tmpdict, f)
							
						self.logger.print_success("Saved VMF message to {:s}.".format(file))
					else:
						self.logger.print_error("Specify a file to save the configuration to.")
				elif (cmd.lower() == "test"):
					if (len(tokens) == 2):
						vmf_params = tokens[1]
					else:
						vmf_params = '0x4023'
					s = BitStream(vmf_params)
					bstream = BitStream('0x4023')
					vmf_factory = Factory(_logger=self.logger)
					vmf_message = vmf_factory.read_message(bstream)					
				elif (cmd.lower() == VmfShell.CMD_LOAD):
					if len(tokens) == 2:
						file = tokens[1]
						with open(file, 'r') as f:
							param_dict = json.load(f)
							for (param, value) in param_dict.iteritems():
								Params.__dict__[param] = value
						self.logger.print_success("Loaded VMF message from {:s}.".format(file))
					else:
						self.logger.print_error("Specify a file to load the configuration from.")
						
				else:
					self.logger.print_error("Unknown command {:s}.".format(cmd))
			except Exception as e:
				self.logger.print_error("An exception as occured: {:s}".format(e.message))
				traceback.print_exc(file=sys.stdout)
    def _getLexer(self):
        return get_lexer_by_name(self.lexer)

    def _render(self):
        """
           Renders the code with pygments if it is available otherwise with a simple pre-tag
        """
        if not hasPygments:
            self._textNode.setText(self.code)
            return

        self._tagName = "span"
        formatter = HtmlFormatter(linenos=self.showLineNumbers)
        self._textNode.setText(highlight(self._getCode(), self._getLexer(), formatter))

Factory.addProduct(CodeSnippet)


class SourceFile(CodeSnippet):
    """
        Enables adding a formatted source file directly to a page.
    """

    def _getCode(self):
        if self.code:
            with open(self.code, "r") as openFile:
                return openFile.read()
        return ""

    def _getLexer(self):
        if self.lexer:
Beispiel #47
0
    def __init__(self, id=None, name=None, parent=None):
        ScriptContainer.__init__(self)
        self.addClass("onLoadJavascript")
        self.hide()

    def content(self, variableDict=None, formatted=False):
        """
            Overrides the base WebElement content method to replace non-safe characters
        """
        script = ScriptContainer.content(self, variableDict, formatted=formatted)
        script = script.replace("&", "&amp;")
        script = script.replace("<", "&lt;")
        script = script.replace(">", "&gt;")
        return script

Factory.addProduct(AJAXScriptContainer)


class AjaxController(Layout.Box):
    """
        Abstract Page Controller Definition, separates a section of the page to update independent of the rest of the
        page using prototype.js AJAX convenience functions.
    """
    jsFunctions = ["ajaxUpdate", "ajaxDo", "ajaxParameters", "ajaxParametersMultiple",
                   "applyAjaxUpdate", "applyAjaxUpdateMultiple", "ajaxSubmit",
                   "_ajaxGet", "_ajaxGetMultiple", "abortAjaxUpdate", "_ajaxFields",
                   "_ajaxForms", "_ajaxSerialize"]

    autoload = True
    autoreload = False # set to a number of milliseconds if you want it to periodically reload
    callFunction = None # javascript function to call with JSON data
Beispiel #48
0
         """
        return self.name

    def setName(self, name):
        """
            Sets the name of the meta tag
        """
        self.name = name

    def shown(self):
        """
            Meta tags are never visible
        """
        return False

Factory.addProduct(MetaData)


class HTTPHeader(MetaData):
    """
        A webelement that represents an http header meta tag
    """
    __slots__ = ()
    def getName(self):
        """
            Returns the headers name
        """
        return self.attributes.get('http-equiv')

    def setName(self, name):
        """
Beispiel #49
0
        self.connect('rendering', None, self, '_updateReadOnly_')

    def _updateReadOnly_(self):
        """
            Update readonly attribute to reflect editable status
        """
        if not self.editable():
            self.attributes['readonly'] = 'readonly'

    def setDisabledJs(self, disabled):
        '''
            Returns javascript to disable this input clientside
        '''
        return 'WebElements.get(\'%s\').disabled = %s;' % (self.id, str(disabled))

Factory.addProduct(InputElement)


class CheckBox(InputElement):
    """
        Defines a checkbox '<input type="checkbox">' webelement
    """
    __slots__ = ()
    properties = InputElement.properties.copy()
    properties['valueAttribute'] = {'action':'setValueAttributeFromString'}

    class ClientSide(InputElement):

        def showIfChecked(self, elementToShow):
            return ClientSide.showIfChecked(elementToShow, self)
Beispiel #50
0
            self.tagSelfCloses = True
        elif extension == "png":
            self.tagName = "link"
            self.attributes["rel"] = "icon"
            self.attributes["type"] = "image/png"
            self.attributes["href"] = fileName
            self.resourceType = "css"
            self.tagSelfCloses = True
        else:
            self.tagName = "h2"
            self.textBeforeChildren = "Invalid Resource: %s" % fileName
            self.resourceType = None
            self.tagSelfCloses = False


Factory.addProduct(ResourceFile)


class ScriptContainer(Base.WebElement):
    """
        All scripts should be stored in a Script Box object
    """

    displayable = False
    tagName = "script"
    properties = Base.WebElement.properties.copy()
    properties["script"] = {"action": "addScript"}

    def __init__(self, id=None, name=None, parent=None):
        Base.WebElement.__init__(self)
        self.attributes["language"] = "javascript"
Beispiel #51
0
                elif unit.unit_type == bc.UnitType.Rocket:
                    Rocket.manage_rockets(gc, unit)
                elif unit.unit_type == bc.UnitType.Healer:
                    Healer.manage_healers(gc, unit)
                elif unit.unit_type == bc.UnitType.Knight:
                    Knight.turn(gc, unit)
                    # Knight.manage_knights(gc, unit, Globals.earth_enemy_center, earth_enemy_map, eneGlobals.us)
                elif unit.unit_type == bc.UnitType.Mage:
                    Mage.manage_mages(gc, unit)
                    # Mage.manage_mages(gc, unit, Globals.earth_enemy_center, earth_enemy_map, Globals.us)
                elif unit.unit_type == bc.UnitType.Ranger:
                    s = time.time()
                    Ranger.turn(gc, unit)
                    Globals.rtime += (time.time() - s)
                elif unit.unit_type == bc.UnitType.Factory:
                    Factory.factory_manager(gc, unit)
        print("Workers: ", Globals.wtime, "Rangers: ", Globals.rtime, "Find Karb: ", Globals.ftime)
        Globals.radar.remove_dead_units()
        Globals.radar.clear_being_shot_at_cache(bc.Planet.Earth)
        Globals.radar.clear_being_shot_at_cache(bc.Planet.Mars)
        Globals.radar.enemies_killed_this_turn = {}
        Globals.radar.enemy_center = None
        Globals.radar.enemy_center_found = -1
        # Globals.income = gc.karbonite() - Globals.prev_karb_amount
        # Globals.prev_karb_amount = gc.karbonite()
        print("----------------")
    # Allows us to locate errors in the code
    except Exception as e:
        print('Error:', e)
        traceback.print_exc()
Beispiel #52
0
            self.setValue(text)
            self.emit('textChanged', text)

    def shown(self):
        """
            A hiddenInput is never visible
        """
        return False

    def text(self):
        """
            Returns the hidden inputs value
        """
        return self.value()

Factory.addProduct(HiddenValue)


class HiddenBooleanValue(HiddenValue):
    """
        Defines a hidden value which accepts true or false values
    """

    def __init__(self, id=None, name=None, parent=None, key=None):
        HiddenValue.__init__(self, id, name, parent, key=key)
        self.attributes['value'] = ''

    def setValue(self, value):
        """
            Sets the hidden inputs value to 1 or '' to represent true or false
        """
Beispiel #53
0
        self.formError.parent.style["float"] = "right"


class InputField(BaseField):
    """
        A field using an input element
    """

    __slots__ = ()
    inputElement = Inputs.InputElement
    properties = BaseField.properties.copy()
    Base.addChildProperties(properties, Inputs.InputElement, "userInput")
    properties["type"] = {"action": "userInput.attribute", "name": "type"}


Factory.addProduct(InputField)


class TextField(BaseField):
    """
        A field with a textbox as the input
    """

    __slots__ = ()
    inputElement = Inputs.TextBox
    properties = BaseField.properties.copy()
    Base.addChildProperties(properties, Inputs.TextBox, "userInput")


Factory.addProduct(TextField)
Beispiel #54
0
    allowsChildren = False
    tagSelfCloses = True
    properties = ValueElement.properties.copy()
    properties['src'] = {'action':'setValue'}

    def __init__(self, id=None, name=None, parent=None):
        ValueElement.__init__(self, id, name, parent)

    def setValue(self, value):
        """
            Sets the location from which to load the image
        """
        ValueElement.setValue(self, value)
        self.attributes['src'] = value

Factory.addProduct(Image)


class HoverImage(Image):
    """
        Defines an image that changes on mouseover
    """
    properties = ValueElement.properties.copy()
    properties['imageOnHover'] = {'action':'classAttribute'}
    properties['imageOnClick'] = {'action':'classAttribute'}
    imageOnHover = None
    imageOnClick = None

    def __init__(self, id=None, name=None, parent=None):
        Image.__init__(self, id, name, parent)
Beispiel #55
0
from Inputs import ValueElement
from MethodUtils import CallBack

Factory = Factory.Factory("Display")


class Image(DOM.Img):
    """
        Adds an image to the page
    """
    __slots__ = ()

    allowsChildren = False
    tagSelfCloses = True

Factory.addProduct(Image)


class HoverImage(Image):
    """
        Defines an image that changes on mouseover
    """
    __slots__ = ()

    properties = Image.properties.copy()
    properties['imageOnHover'] = {'action':'classAttribute'}
    properties['imageOnClick'] = {'action':'classAttribute'}
    imageOnHover = None
    imageOnClick = None

    def __init__(self, id=None, name=None, parent=None, **kwargs):