Example #1
0
    def __init__(self, fieldSize, screenSize=(400, 400), mainFieldHeight=380):
        #TODO NUR height übergeben
        pygame.init()
        self.screen = pygame.display.set_mode(screenSize)
        pygame.display.set_caption("Conway's Game of Life")
        self.mainField = Screen(fieldSize)

        self.fieldSize = fW, fH = fieldSize
        self.screenSize = w, h = screenSize

        self.field = None
        self.loadedTemplate = None

        mainScreenSize = mW, mH = int(mainFieldHeight * fW /
                                      fH), mainFieldHeight
        margin = int((h - mH) / 2)

        self.mainScreenRect = (w - mW - margin, margin, mW, mH)

        self.selectionField = SelectionField((100, mainFieldHeight))
        self.selectionFieldRect = (margin, margin, *self.selectionField.size)

        self.selectionField.add_template(
            Template('Test', figures.pentadecathlon))
        self.selectionField.add_template(
            Template('Test', figures.glider_diagonal_se))
        self.selectionField.add_template(Template('Test', figures.stick))
Example #2
0
    def testConstants(self):
        n = [0]

        def counter():
            n[0] += 1
            return n[0] - 1

        constants = {
            "author": "Andy 'Da Man' Wardley",
            "single": "foo'bar",
            "double": 'foo"bar',
            "joint": ", ",
            "col": {
                "back": "#ffffff",
                "text": "#000000"
            },
            "counter": counter
        }
        namespace = Constants(constants)
        self.assertEqual('"Andy \'Da Man\' Wardley"',
                         namespace.ident(["constants", 0, "'author'", 0]))
        self.assertEqual('"foo\'bar"',
                         namespace.ident(["constants", 0, "'single'", 0]))
        self.assertEqual("'foo\"bar'",
                         namespace.ident(["constants", 0, "'double'", 0]))
        self.assertEqual(
            "'#ffffff'",
            namespace.ident(["constants", 0, "'col'", 0, "'back'", 0]))
        self.assertEqual(
            "'#000000'",
            namespace.ident(["constants", 0, "'col'", 0, "'text'", 0]))
        factory = Directive({"NAMESPACE": {"const": namespace}})
        parser1 = Parser({"FACTORY": factory})
        parser2 = Parser({"NAMESPACE": {"const": namespace}})
        for parser in parser1, parser2:
            parsed = parser.parse('hello [% const.author %]\n'
                                  '[% "back is $const.col.back" %]'
                                  ' and text is {% const.col.text %]\n'
                                  'but a col is still a [% col.user %]\n')
            text = parsed["BLOCK"]
            self.assertNotEqual(-1, text.find('"Andy \'Da Man\' Wardley"'))
            self.assertNotEqual(-1, text.find("'back is ', '#ffffff'"))
            self.assertNotEqual(-1,
                                text.find("stash.get(['col', 0, 'user', 0])"))

        tt1 = Template({"NAMESPACE": {"const": namespace}})
        const2 = {
            "author": "abw",
            "joint": " is the new ",
            "col": {
                "back": "orange",
                "text": "black"
            },
            "fave": "back"
        }
        tt2 = Template({"CONSTANTS": const2})
        tt3 = Template({"CONSTANTS": const2, "CONSTANTS_NAMESPACE": "const"})
        engines = (("tt1", tt1), ("tt2", tt2), ("tt3", tt3))
        vars = {"col": {"user": "******", "luza": "blue"}, "constants": constants}
        self.Expect(DATA, engines, vars)
Example #3
0
class Gibson(Operation):

    name = 'Gibson Assembly'
    input_template = Template(type='DNA', shape='linear')
    output_template = Template(type='DNA',
                               shape='circular',
                               concentration='low')
Example #4
0
    def render(self):
        # render wrapper for handleEvent and callback functions
        out = os.path.join(self.outputdir, "ai.c")
        tempfile = os.path.join(self.templatedir, "wrappai.c")
        template = open(tempfile, "r")

        stream = Template(template.read()).render({
            'clbfuncs': self.clbfuncs,
            'events': self.events,
            'commands': self.commands,
            'templatedir': self.templatedir,
            'converter': converter,
            'options': self.options
        })
        template.close()
        outfile = open(out, "w")
        outfile.write(stream)
        outfile.close()

        # render interface
        out = os.path.join(self.outputdir, "PyAI", "interface.py")
        tempfile = os.path.join(self.templatedir, "aiInterface.py")
        template = open(tempfile, "r")

        stream = Template(template.read()).render({
            'classes': self.classes,
            'commands': self.commandfuncs,
            'cmd_types': self.command_types,
            'evt_types': self.event_types,
            'options': self.options
        })
        outfile = open(out, "w")
        outfile.write(stream)
        outfile.close()
Example #5
0
  def Expect(self, data, tproc=None, vars=None):
    vars = vars or {}
    data = re.sub(r"(?m)^#.*\n", "", data)
    match = re.search(r"\s*--\s*start\s*--\s*", data)
    if match:
      data = data[match.end():]
    match = re.search(r"\s*--\s*stop\s*--\s*", data)
    if match:
      data = data[:match.start()]
    tests = re.split(r"(?mi)^\s*--\s*test\s*--\s*", data)
    if not tests[0]:
      tests.pop(0)
    ttprocs = None
    if isinstance(tproc, dict):
      tproc = Template(tproc)
    elif isinstance(tproc, (tuple, list)):
      ttprocs = dict(tproc)
      tproc = tproc[0][1]
    elif not isinstance(tproc, Template):
      tproc = Template()
    for count, test in enumerate(tests):
      match = re.search(r"(?mi)^\s*-- name:? (.*?) --\s*\n", test)
      if match:
        name = match.group(1)
        test = test[:match.start()] + test[match.end():]
      else:
        name = "template text %d" % (count + 1)
      match = re.search(r"(?mi)^\s*--\s*expect\s*--\s*\n", test)
      if match:
        input, expect = test[:match.start()], test[match.end():]
      else:
        input, expect = test, ""
      match = re.match(r"(?mi)^\s*--\s*use\s+(\S+)\s*--\s*\n", input)
      if match:
        ttname = match.group(1)
        ttlookup = ttprocs.get(ttname)
        if ttlookup:
          tproc = ttlookup
        else:
          self.fail("no such template object to use: %s\n" % ttname)
        input = input[:match.start()] + input[match.end():]

      try:
        out = tproc.processString(input, vars)
      except Exception as e:
        self.fail("Test #%d: %s process FAILED: %s\n%s" % (
          int(count + 1), name, subtext(input), e))

      match = re.match(r"(?i)\s*--+\s*process\s*--+\s*\n", expect)
      if match:
        expect = expect[match.end():]
        try:
          expect = tproc.processString(expect, vars)
        except TemplateException as e:
          self.fail("Test #%d: Template process failed (expect): %s" % (
            count + 1, e))
      out = out.rstrip("\n")
      stripped = expect.rstrip("\n")
      self.assertEqual(stripped, out, "Test #%d:\n%s\n%r != %r" %
                       (count + 1, test, stripped, out))
Example #6
0
class Zymoprep(Operation):

    name = 'Zymoprep'
    input_template = Template(type='Yeast', concentration='high')
    output_template = Template(type='DNA',
                               shape='circular',
                               concentration='low')
Example #7
0
class Ligate(Operation):

    name = 'Ligate'
    input_template = Template(type='DNA', shape='linear')
    output_template = Template(type='DNA',
                               shape='circular',
                               concentration='low')
Example #8
0
class Quikchange(Operation):

    name = 'Quikchange'
    input_template = Template(type='DNA', shape='circular')
    output_template = Template(type='DNA',
                               shape='circular',
                               concentration='low')
Example #9
0
class Electroporation(Operation):

    name = 'Electroporation'
    input_template = Template(type='DNA',
                              shape='circular',
                              concentration='high')
    output_template = Template(type='Yeast', concentration='low')
Example #10
0
  def testStash(self):
    count = [20]
    def boz():
      count[0] += 10
      return count[0]
    def biz(*args):
      return args and args[0] or "<undef>"
    data = { "foo": 10,
             "bar": { "baz": 20 },
             "baz": lambda: { "boz": boz, "biz": biz },
             "obj": AnObject(name="an object"),
             "hashobj": HashObject(planet="World") }
    stash = Stash(data)
    self.assertEqual(10, stash.get("foo").value())
    self.assertEqual(20, stash.get(["bar", 0, "baz", 0]).value())
    self.assertEqual(20, stash.get("bar.baz").value())
    self.assertEqual(20, stash.get("bar(10).baz").value())
    self.assertEqual(30, stash.get("baz.boz").value())
    self.assertEqual(40, stash.get("baz.boz").value())
    self.assertEqual("<undef>", stash.get("baz.biz").value())
    self.assertEqual("<undef>", stash.get("baz(50).biz").value())  # args are ignored

    stash.set("bar.buz", 100)
    self.assertEqual(100, stash.get("bar.buz").value())

    ttlist = (("default", Template()),
              ("warn", Template({"DEBUG": constants.DEBUG_UNDEF,
                                 "DEBUG_FORMAT": ""})))
    self.Expect(DATA, ttlist, data)
Example #11
0
class Miniprep(Operation):

    name = 'Miniprep'
    input_template = Template(type='E.Coli', concentration='high')
    output_template = Template(type='DNA',
                               shape='circular',
                               concentration='high')
  def testContext(self):
    tt = Template({ 'INCLUDE_PATH': 'test/src:test/lib',
                    'TRIM': True,
                    'POST_CHOMP': 1 })
    ttpython = Template({ 'INCLUDE_PATH': 'test/src:test/lib',
                          'TRIM': True,
                          'POST_CHOMP': 1,
                          'EVAL_PYTHON': True })

    ctx = tt.service().context()
    self.failUnless(ctx)
    self.assertEquals(ctx, tt.context())
    self.failUnless(ctx.trim())
    self.failUnless(not ctx.eval_python())
    ctx = ttpython.service().context()
    self.failUnless(ctx)
    self.failUnless(ctx.trim())
    self.failUnless(ctx.eval_python())

    # template()

    # Test that we can fetch a template via template()
    tmpl = ctx.template('header')
    self.failUnless(tmpl)
    self.failUnless(isinstance(tmpl, Document))

    # Test that non-existence of a template is reported
    error = None
    try:
      tmpl = ctx.template('no_such_template')
    except Exception, e:
      error = e
Example #13
0
 def testService(self):
     config = {
         "INCLUDE_PATH": "test/src:test/lib",
         "PRE_PROCESS": ["config", "header"],
         "POST_PROCESS": "footer",
         "BLOCKS": {
             "demo": lambda *_: "This is a demo",
             "astext": "Another template block, a is '[% a %]'"
         },
         "ERROR": {
             "barf": "barfed",
             "default": "error"
         },
     }
     tt1 = Template(config)
     config["AUTO_RESET"] = 0
     tt2 = Template(config)
     config["ERROR"] = "barfed"
     tt3 = Template(config)
     config["PRE_PROCESS"] = "before"
     config["POST_PROCESS"] = "after"
     config["PROCESS"] = "process"
     config["WRAPPER"] = "outer"
     tt4 = Template(config)
     config["WRAPPER"] = ["outer", "inner"]
     tt5 = Template(config)
     replace = {"title": "Joe Random Title"}
     self.Expect(DATA, (("tt1", tt1), ("tt2", tt2), ("tt3", tt3),
                        ("wrapper", tt4), ("nested", tt5)), replace)
Example #14
0
 def testTags(self):
   params = { "a": "alpha", "b": "bravo", "c": "charlie", "d": "delta",
              "e": "echo" }
   tt = (("basic", Template({ "INTERPOLATE": 1 })),
         ("htags", Template({ "TAG_STYLE": "html" })),
         ("stags", Template({ "START_TAG": r"\[\*", "END_TAG": r"\*\]" })))
   self.Expect(DATA, tt, params)
Example #15
0
 def testVarsV1(self):
   params = self.make_params()
   tt = (("default", Template({ "INTERPOLATE": 1,
                                "ANYCASE": 1,
                                "V1DOLLAR": 1 })),
         ("notcase", Template({ "INTERPOLATE": 1,
                                "V1DOLLAR": 0 })))
   self.Expect(DATA_V1, tt, params)
 def testBlocks(self):
   dir = os.getcwd() + "/test/lib"
   tt1 = Template({ 'INCLUDE_PATH': ['test/lib'],
                    'ABSOLUTE': True })
   tt2 = Template({ 'INCLUDE_PATH': ['test/lib'],
                    'EXPOSE_BLOCKS': True,
                    'ABSOLUTE': True })
   vars = { 'a': 'alpha', 'b': 'bravo', 'dir': dir }
   self.Expect(DATA, (('off', tt1), ('on', tt2)), vars)
 def testText(self):
   tt = (("basic", Template()),
         ("interp", Template({ "INTERPOLATE": 1 })))
   vars = self._callsign()
   v2 = { "ref": lambda obj: "%s[%s]" % (obj, obj.__class__.__name__),
          "sfoo": Stringy("foo"),
          "sbar": Stringy("bar") }
   vars.update(v2)
   self.Expect(DATA, tt, vars)
Example #18
0
    def response(self, msg, **kwargs):
        ## msg is parsed and your handled data.Actually,it is a dict.
        ## Your could specify a type by assign.ex response(type='music').I list all legal types.
        '''
        ex: response(message,type='yourType')
        optional kwargs:
        type='legal_types',content='yourContent',handler=foo,count=1 
        ps:when type is news,the count kwarg is nessceary
        support types:
        text,image,voice,video,music,news
        '''
        msg['receiver'], msg['sender'] = msg['sender'], msg['receiver']
        legal_types = ['text', 'music', 'image', 'voice', 'video', 'news']

        ## get some kwargs ##
        # key word content ---- which force type to textand return a static string
        if kwargs.get('type'):
            type = kwargs.get('type')
        else:
            type = msg['type']
        if type == 'music':
            if not msg['hq_musurl']:
                msg['hq_musurl'] = msg['musurl']
        # charge receiver and sender
        if kwargs.get('content'):
            msg['type'] = type = 'text'
            msg['content'] = to_unicode(kwargs.get('content'))
        if not type in legal_types:
            raise Exception(
                "Illgal type!You could only choose one type from legal_types!")
        # key word handler ---- which is a function object,accept a dict and return a modified dict
        else:
            msg['type'] = type
        if kwargs.get('handler'):
            msg = kwargs.get('handler')(msg)
        ## more kwargs ##

        if not type == 'news':
            template = to_unicode(getattr(Template(), type))
        else:
            count = kwargs.get('count')
            if count:
                temp = Template()
                template = to_unicode(temp.news(count))
            else:
                raise Exception(
                    'When type is set to news,the count kwarg is necessary!')

        logging.info(template.format(**msg))
        try:
            retdata = template.format(**msg)
        except:
            raise Exception(
                "You did't pass enough args or pass wrong args,please check args which template needed.Read template.py maybe inspire your mind"
            )
        return retdata
 def testDirectives(self):
     ttobjs = (('tt', Template()), ('pre', Template({'PRE_CHOMP': 1})),
               ('post', Template({'POST_CHOMP': 1})), ('trim',
                                                       Template({
                                                           'INCLUDE_PATH':
                                                           'test/lib',
                                                           'TRIM':
                                                           1
                                                       })))
     self.Expect(DATA, ttobjs, self._callsign())
Example #20
0
 def testStop(self):
   ttblocks = { "header": lambda *_: "This is the header\n",
                "footer": lambda *_: "This is the footer\n",
                "halt1": halt }
   ttvars = { "halt": halt }
   ttbare = Template({ "BLOCKS": ttblocks })
   ttwrap = Template({"PRE_PROCESS": "header",
                      "POST_PROCESS": "footer",
                      "BLOCKS": ttblocks })
   self.Expect(DATA, (("bare", ttbare), ("wrapped", ttwrap)), ttvars)
 def compile(self, header, body, footer):
     header, body, footer = (Template(header), Template(body),
                             Template(footer))
     compiled = ''
     for post in self.posts:
         compiled += body.compile({
             'title': post.title,
             'date': post.pretty_date,
             'content': self.indent(post.content)
         })
     return (header.compile() + compiled + footer.compile())
 def testEvalPython(self):
     tt_no_python = Template({"INTERPOLATE": 1,
                              "POST_CHOMP": 1,
                              "EVAL_PYTHON": 0,
                              "INCLUDE_PATH": "test/lib"})
     tt_do_python = Template({"INTERPOLATE": 1,
                              "POST_CHOMP": 1,
                              "EVAL_PYTHON": 1,
                              "INCLUDE_PATH": "test/lib"})
     ttprocs = (("no_python", tt_no_python), ("do_python", tt_do_python))
     self.Expect(DATA, ttprocs, self._callsign())
Example #23
0
 def testProcess(self):
   config = { "INCLUDE_PATH": "test/src:test/lib",
              "PROCESS": "content",
              "TRIM": 1 }
   tt1 = Template(config)
   config["PRE_PROCESS"] = "config"
   config["PROCESS"] = "header:content"
   config["POST_PROCESS"] = "footer"
   config["TRIM"] = 0
   tt2 = Template(config)
   config["PRE_PROCESS"] = "config:header.tt2"
   config["PROCESS"] = ""
   tt3 = Template(config)
   replace = { "title": "Joe Random Title" }
   self.Expect(DATA, (("tt1", tt1), ("tt2", tt2), ("tt3", tt3)), replace)
Example #24
0
def main():
    try:
        manager = InfHoneydMan()
        windows = Template("windows")
        windows.set_personality("Microsoft Windows NT 4.0 SP3")
        windows.set_uptime(1728650)
        windows.set_ethernet("dell")
        windows.set_tcp_default("closed")
        windows.add_tcp_port(80, "/home/honeyd/honeyd/Honeyd-master/scripts/web.sh")
        windows.add_tcp_port(22, "/home/honeyd/honeyd/Honeyd-master/scripts/test.sh")
        windows.add_tcp_port(23, "/home/honeyd/honeyd/Honeyd-master/scripts/router-telnet.pl")
        windows.add_udp_port(53, "open")
        windows.add_udp_port(137, "open")
        windows.add_udp_port(161, "open")
        windows.add_udp_port(162, "filtered")

        ubuntu = Template("ubuntu")
        ubuntu.set_personality("Linux 2.6.15 (Ubuntu)")
        ubuntu.set_ethernet("dell")
        ubuntu.set_tcp_default("closed")
        ubuntu.add_tcp_port(80, "/home/honeyd/honeyd/Honeyd-master/scripts/web.sh")
        ubuntu.add_tcp_port(22, "/home/honeyd/honeyd/Honeyd-master/scripts/test.sh")
        ubuntu.add_tcp_port(23, "/home/honeyd/honeyd/Honeyd-master/scripts/router-telnet.pl")
        ubuntu.add_udp_port(54, "open")
        ubuntu.add_udp_port(138, "open")
        ubuntu.add_udp_port(163, "open")
        ubuntu.add_udp_port(164, "filtered")

        manager.add_template(windows)
        manager.add_template(ubuntu)
        templates = manager.template_list.values()
        for ii in range(1, 11):
            for jj in range(0, 10):
                addr_4 = ii*10 + jj
                vhost = "192.168.193." + str(addr_4)
                t_i = random.randint(1, 2)
                manager.add_honeypot(vhost, templates[t_i])
            print ii
            manager.update_config()
            time.sleep(5)

        # manager.add_honeypot("192.168.193.97", windows)
        # manager.add_honeypot("192.168.193.98", ubuntu)
        # manager.list_honeypots()
        # manager.update_config()
    except KeyboardInterrupt:
        LOG.info("MAIN ERROR: keyboard interrupt, now quit")
        sys.exit(0)
Example #25
0
def main():

    max_iterations = 10
    operations = op.get_default_operations()

    network = Network()
    network.add_node(Template(no_input=True))

    for iteration in xrange(max_iterations):

        #print 'Current nodes:',network.all_nodes
        #print 'Current edges:',network.all_edges
        #print 'Iteration {}'.format(iteration)

        additions = 0  # determines if nothing is growing

        for operation in operations:

            new_edges = build_edge(operation, network.all_nodes,
                                   network.all_edges)

            if not new_edges:
                continue

            if network.add_edges(new_edges, operation.name):
                additions = 1

        if additions == 0:
            break

    network.display_flowchart()
    def testCompile(self):
        ttcfg = {
            "POST_CHOMP": 1,
            "INCLUDE_PATH": "test/src",
            "COMPILE_EXT": ".ttc"
        }
        # Check that compiled template files exist.
        compiled = "test/src/foo.ttc"
        self.assert_(os.path.exists(compiled))
        self.assert_(os.path.exists("test/src/complex.ttc"))

        # Ensure template metadata is saved in compiled file.
        output = Template(ttcfg).process("baz", {"showname": 1})
        self.assertNotEqual(-1, output.find("name: baz"))

        # We're going to hack on the foo.ttc file to change some key text.
        # This way we can tell that the template was loaded from the compiled
        # version and not the source.
        fh = open(compiled, "r+")
        stat = os.fstat(fh.fileno())
        foo = fh.read()
        fh.seek(0)
        fh.write(foo.replace("the foo file", "the hacked foo file"))
        fh.close()
        os.utime(compiled, (stat.st_atime, stat.st_mtime))

        self.Expect(DATA, ttcfg)
Example #27
0
 def test_variable(self):
     rendered = Template('''
         hello, {{ name }}
         ''').render(name='flango')
     self.assertEqual(rendered, '''
         hello, flango
         ''')
Example #28
0
 def testPostChomp(self):
     tmpl = Template({'POST_CHOMP': 1, 'BLOCKS': blocks})
     self.AssertExpectedOutput(tmpl, "foo", vars, "\n3.14")
     self.AssertExpectedOutput(tmpl, "bar", vars, "2.718")
     self.AssertExpectedOutput(tmpl, "baz", vars, "\n1.618\n")
     self.AssertExpectedOutput(tmpl, "ding", vars, "!Hello!")
     self.AssertExpectedOutput(tmpl, "dong", vars, "! World !")
Example #29
0
 def testPreChomp(self):
     tmpl = Template({"PRE_CHOMP": 1, "BLOCKS": blocks})
     self.AssertExpectedOutput(tmpl, "foo", vars, "3.14\n")
     self.AssertExpectedOutput(tmpl, "bar", vars, "2.718")
     self.AssertExpectedOutput(tmpl, "baz", vars, "\n1.618\n")
     self.AssertExpectedOutput(tmpl, "ding", vars, "!Hello!")
     self.AssertExpectedOutput(tmpl, "dong", vars, "! World !")
Example #30
0
def print_jsfile(titles, fp):
    var = {
        'escape_simple': lambda s: cgi.escape(s, True),
        'titles': titles,
        'server': server,
    }
    fp.write(Template().display('suggest_js', var))