Пример #1
0
def generateFile(isResponse, className, templatePath, properties, requestConf, headerList):
    templatePathH = templatePath + '.h'
    templatePathM = templatePath + '.m'
    templateH = Template(filename=templatePathH,input_encoding='utf-8',output_encoding='utf-8')
    templateM = Template(filename=templatePathM,input_encoding='utf-8',output_encoding='utf-8')
    writeFile(className + '.h', templateH.render(className=className, properties=properties, headerList=headerList))
    writeFile(className + '.m', templateM.render(className=className, requestConf=requestConf, headerList=headerList))
Пример #2
0
    def test_strict(self):
        t = Template("""
            % if x is UNDEFINED:
                undefined
            % else:
                x: ${x}
            % endif
        """, strict_undefined=True)

        assert result_lines(t.render(x=12)) == ['x: 12']

        assert_raises(
            NameError,
            t.render, y=12
        )

        l = TemplateLookup(strict_undefined=True)
        l.put_string("a", "some template")
        l.put_string("b", """
            <%namespace name='a' file='a' import='*'/>
            % if x is UNDEFINED:
                undefined
            % else:
                x: ${x}
            % endif
        """)

        assert result_lines(t.render(x=12)) == ['x: 12']

        assert_raises(
            NameError,
            t.render, y=12
        )
Пример #3
0
    def test_module_roundtrip(self):
        lookup = TemplateLookup()

        template = Template("""
        <%inherit file="base.html"/>

        % for x in range(5):
            ${x}
        % endfor
""", lookup=lookup)

        base = Template("""
        This is base.
        ${self.body()}
""", lookup=lookup)

        lookup.put_template("base.html", base)
        lookup.put_template("template.html", template)

        assert result_lines(template.render()) == [
            "This is base.", "0", "1", "2", "3", "4"
        ]

        lookup = TemplateLookup()
        template = ModuleTemplate(template.module, lookup=lookup)
        base = ModuleTemplate(base.module, lookup=lookup)

        lookup.put_template("base.html", base)
        lookup.put_template("template.html", template)

        assert result_lines(template.render()) == [
            "This is base.", "0", "1", "2", "3", "4"
        ]
Пример #4
0
    def test_args_complete(self):
        t = Template(
            """
        <%%def name="foo()" cached="True" cache_timeout="30" cache_dir="%s"
         cache_type="file" cache_key='somekey'>
            this is foo
        </%%def>

        ${foo()}
"""
            % module_base
        )
        m = self._install_mock_cache(t)
        t.render()
        eq_(m.kwargs, {"dir": module_base, "type": "file", "timeout": 30})

        t2 = Template(
            """
        <%%page cached="True" cache_timeout="30" cache_dir="%s"
         cache_type="file" cache_key='somekey'/>
        hi
        """
            % module_base
        )
        m = self._install_mock_cache(t2)
        t2.render()
        eq_(m.kwargs, {"dir": module_base, "type": "file", "timeout": 30})
Пример #5
0
def build_docs():
    """Build the Blogofile sphinx based documentation"""
    #Abort if sphinx isn't installed
    try:
        import sphinx
    except ImportError:
        return
    #print "Building the docs..."
    #Configure the theme
    #Insert the rendered head, headers, and footers into the theme
    config = sys.modules[globals()['__name__']]
    from mako.template import Template
    head_t = Template(open(os.path.join("_templates","head.mako")).read())
    head = head_t.render(**{'bf':bf})
    header_t = Template(open(os.path.join("_templates","header.mako")).read())
    header = header_t.render(**{'bf':bf})
    footer_t = Template(open(os.path.join("_templates","footer.mako")).read())
    footer = footer_t.render(**{'bf':bf})

    #Create the new layout.html from preparse_layout.html
    #Insert the rendered templates appropriately
    layout = open(os.path.join("_documentation","themes","blogofile",
                               "preparse_layout.html")).read()
    layout = layout.replace("blogofile_head_goes_here",head)
    layout = layout.replace("blogofile_header_goes_here",header)
    layout = layout.replace("blogofile_footer_goes_here",footer)
    layout_f = open(os.path.join("_documentation","themes","blogofile",
                               "layout.html"),"w")
    layout_f.write(layout)
    layout_f.close()
    logger.info("Compiling HTML Documentation..")
    sphinx.main(shlex.split("sphinx-build -q -b html _documentation "+
                            os.path.join("_site","documentation")))
Пример #6
0
def main(picard_dir, align_bam, ref_file, fastq_one, fastq_pair=None,
        bait_file=None, target_file=None, do_sort=False, sample_name=""):
    tmp_dir = _make_tmpdir()
    work_dir = os.getcwd()
    picard = PicardRunner(picard_dir)
    if do_sort:
        align_bam = picard_sort(picard, align_bam, tmp_dir)

    metrics = PicardMetrics(picard, tmp_dir)
    summary_table, metrics_graphs = metrics.report(
            align_bam, ref_file, fastq_pair is not None,
            bait_file, target_file)
    base, ext = os.path.splitext(align_bam)
    base = base.replace(".", "-")
    total_count, read_size, fastq_graphs = plot_fastq_stats(
            [fastq_one, fastq_pair], base, params)
    # add read_size to the total summary table
    summary_table[0] = (summary_table[0][0], summary_table[0][1],
            "%sbp %s" % (read_size, summary_table[0][-1]))
    ref_org = os.path.splitext(os.path.split(ref_file)[-1])[0]
    summary_table.insert(0, ("Reference organism",
        ref_org.replace("_", " "), ""))
    tmpl = Template(section_template)
    sample_name = "%s (%s)" % (sample_name.replace("_", "\_"),
            base.replace("_", " "))
    section = tmpl.render(name=sample_name, summary=None,
            summary_table=summary_table,
            figures=[(f, c) for (f, c) in metrics_graphs + fastq_graphs if f],
            recal_figures=_get_recal_plots(work_dir, align_bam))
    out_file = "%s-summary.tex" % base
    out_tmpl = Template(base_template)
    with open(out_file, "w") as out_handle:
        out_handle.write(out_tmpl.render(parts=[section]))
    run_pdflatex(out_file, params)
    shutil.rmtree(tmp_dir)
Пример #7
0
Файл: blt.py Проект: kohler/blt
def write_harness():
    global tmpdir
    function_tmpl = Template(
            filename=(os.path.join(env['blt'], 'templates', 'functions.mako')))
    funcs_str = function_tmpl.render(funcs=data['funcs'], class1=data['class1'],
            class2=data['class2'])

    traces_tmpl = Template(
            filename=(os.path.join(env['blt'], 'templates', 'traces.mako')))
    traces_str = traces_tmpl.render(traces=data['traces'], class1=data['class1'],
            class2=data['class2'])

    body_tmpl = Template(filename=(os.path.join(env['blt'], 'templates', 'body.mako')))
    body_str = body_tmpl.render(
            headers=[os.path.abspath(os.path.join(jfile_dir, h)) for h in data['header_files']],
            funcs_str=funcs_str, traces_str=traces_str,
            ntraces=(len(data['traces'])),
            seed=SEED)

    tmpdir = os.path.join(jfile_dir, 'blt_tmp')
    if os.path.exists(tmpdir):
        subprocess.call('rm -rf {0}'.format(tmpdir).split())
    os.mkdir(tmpdir)
    harness = open(os.path.join(tmpdir, 'harness.cpp'), 'w')
    harness.write(body_str)
    harness.close()
Пример #8
0
def answer_query(bot, update):
    query = update.callback_query
    chat_id = query.message.chat_id
    bot.sendChatAction(chat_id=chat_id, action=ChatAction.TYPING)
    parts = dict(enumerate(query.data.split('|', 1)))
    answer_type = parts[0]
    stop_number = parts.get(1)
    stop_service = StopService()
    route_service = RouteService()
    if answer_type == 'info':
        messages = route_service.get_route_messages_by_stop_number(stop_number)
        if len(messages) == 0:
            bot.sendMessage(chat_id=chat_id, text='No info for today')
            return
        message_tmpl = Template(filename='app/templates/route.txt')
        text = message_tmpl.render(messages=messages)
        bot.sendMessage(chat_id=chat_id, text=text)
    if answer_type == 'schedule':
        messages = stop_service.get_messages_by_stop_number(stop_number)
        is_head = stop_service.is_head_stop(stop_number)
        if len(messages) == 0:
            bot.sendMessage(chat_id=chat_id, text='No schedule for today')
            return
        if is_head:
            message_tmpl = Template(filename='app/templates/schedule_depart.txt')
            text = message_tmpl.render(messages=messages)
            bot.sendMessage(chat_id=chat_id, text=text)
        else:
            message_tmpl = Template(filename='app/templates/schedule_arrival.txt')
            text = message_tmpl.render(messages=messages)
            bot.sendMessage(chat_id=chat_id, text=text)
Пример #9
0
    def gen_uvb_confs(self):
        uvb_dir = self.generated_dir + self.UVB_DIR

        nodes = self.topology.get_nodes()
        for n in nodes:
            name = n.hostname.split(".")[0].replace("-", "_")
            
            template = Template(filename=self.demogrid_dir + self.UVB_TEMPLATE)
            uvb = template.render(domain = self.DOMAIN,
                                  ip = n.ip,
                                  gw = self.__gen_IP(0, 1),
                                  dgl = self.demogrid_dir,
                                  execscript = "post-install-chefsolo.sh",
                                  copy = "files-chefsolo.txt")   
            uvb_file = open(uvb_dir + "/uvb-chefsolo-%s.conf" % name, "w")
            uvb_file.write(uvb)
            uvb_file.close()          
            
            uvb = template.render(domain = self.DOMAIN,
                                  ip = n.ip,
                                  gw = self.__gen_IP(0, 1),
                                  dgl = self.demogrid_dir,
                                  execscript = "post-install-chefserver.sh",
                                  copy = "files-chefserver.txt")
            uvb_file = open(uvb_dir + "/uvb-chefserver-%s.conf" % name, "w")
            uvb_file.write(uvb)
            uvb_file.close()
Пример #10
0
def main():
    try:
        opt, args = opt_parse()
    except Exception:
        usage()

    yaml_doc = OrderedDict({
        'db': opt.db,
        'tables': OrderedDict({})
    })

    doc_file = opt.__dict__.pop("doc_file")
    erdump(**(opt.__dict__))
    
    con = MySQLdb.connect(**(opt.__dict__))
    cur = con.cursor()    
    s = "show tables;"
    cur.execute(s)

    for t in cur.fetchall():
        cur.execute("desc %s;" % t[0])
        columns = cur.fetchall()

        columns_doc = OrderedDict([(c[0], {'type':c[1],'null':c[2],'key':c[3],'default':c[4],'extra':c[5],'comment': ""}) for c in columns])
        
        yaml_doc['tables'][t[0]] = OrderedDict({'columns': columns_doc, 'comments': [""]})

    yaml_merge_out(doc_file, yaml_doc)

    tmpl = Template(filename='%s/mydoc_tmpl.mako' % mydoc_dir, output_encoding='utf-8')
    print tmpl.render(attributes=yaml_doc)
Пример #11
0
	def POST(self):
		form = login()
		
		if not form.validates():
			mytemplate=Template(filename='editar.html')
			return mytemplate.render(form=form)
			
		else:
			
			try:
				conn=pymongo.MongoClient()
			except pymongo.errors.ConnectionFailure, e:
				print "Could not connect to MongoDB: %s" % e 
			
			
			db = conn['usuarios']
			collection = db.my_collection
				
			doc = {'usuario': form.d.Nombre, 'apellidos': form.d.Apellidos, 'DNI': form.d.DNI, 'email': form.d.email, 'fecha_nacimiento': form.d.dia_nacimiento+'/'+form.d.mes_nacimiento+'/'+form.d.anio_nacimiento, 'direccion': form.d.direccion, 'pago': form.d.FormaPago, 'visa': form.d.NumeroVISA, 'password': form.d.Contrasenia}

			collection.insert(doc)
			
			fu=login4()
			f2=login2()
			mytemplate=Template(filename='prueba.html')
			consulta = list(db.my_collection.find({"usuario": form.d.Nombre}))
			return mytemplate.render(consulta=consulta, form=f2, fu=fu)
Пример #12
0
 def email_detail_template(self, email_id=''):
     title='SHIVA honeypot: view email'
     
     emails = backend_operations.retrieve_by_ids([email_id])
     
     # display error message and terminate
     if not emails:
         template = Template('<%include file="view_email.html"/>', lookup=self.template_lookup, output_encoding='utf-8', encoding_errors='replace')
         return template.render(title=title)
     
     mailFields = emails[0]
     
     
     
     if mailFields:        
         # store html content to static file if it doesn't exist
         staticHtmlFile = self.rawHtmlPath + '/' + email_id 
 
         if not os.path.exists(staticHtmlFile):
             f = open(staticHtmlFile, 'w')
             if f:
                 f.write(mailFields['html'].encode('utf8'))
                 f.close()
             else:
                 staticHtmlFile = ''
     
     email_result = backend_operations.get_results_of_email(mailFields['s_id'])
     template = Template('<%include file="view_email.html"/>', lookup=self.template_lookup, output_encoding='utf-8', encoding_errors='replace')
     return template.render(title=title, email_result=email_result, mailFields=mailFields, attachmentsPath=self.attachmentsPath,staticHtmlFile=staticHtmlFile)
Пример #13
0
    def test_html_error_template(self):
        """test the html_error_template"""
        code = """
% i = 0
"""
        try:
            template = Template(code)
            template.render()
        except exceptions.CompileException, ce:
            html_error = exceptions.html_error_template().render()
            assert ("CompileException: Fragment 'i = 0' is not a partial "
                    "control statement") in html_error
            assert '<style>' in html_error
            assert '</style>' in html_error
            html_error_stripped = html_error.strip()
            assert html_error_stripped.startswith('<html>')
            assert html_error_stripped.endswith('</html>')

            not_full = exceptions.html_error_template().render(full=False)
            assert '<html>' not in not_full
            assert '</html>' not in not_full
            assert '<style>' in not_full
            assert '</style>' in not_full

            no_css = exceptions.html_error_template().render(css=False)
            assert '<style>' not in no_css
            assert '</style>' not in no_css
Пример #14
0
	def POST(self):
		fb = login6()
		
		if not fb.validates():
			mytemplate=Template(filename='index.html')
			return mytemplate.render(fb=fb)
		else:
			noti = fb.d.noticia
			
			d = feedparser.parse('elpais.xml')
			
			tam = len(d.entries)
			pos = 0
			while pos < tam:
				if noti in d.entries[pos].title:
					titulo = d.entries[pos].title
					ent = d.entries[pos].content[0].value
					fotop = d.entries[pos].enclosures[0].href
					mytemplate=Template(filename='noticia.html')
					return mytemplate.render(titulo=titulo,ent=ent, fotop=fotop)
					
				else:
					pos = pos + 1
			
			titulo = 'Noticia no encontrada'
			ent = 'Pruebe buscando otro término'
			fotop=0
			mytemplate=Template(filename='noticia.html')
			return mytemplate.render(titulo=titulo,ent=ent,fotop=fotop)
Пример #15
0
    def test_invalidate(self):
        t = Template("""
            <%%def name="foo()" cached="True">
                foo: ${x}
            </%%def>

            <%%def name="bar()" cached="True" cache_type='dbm' cache_dir='%s'>
                bar: ${x}
            </%%def>
            ${foo()} ${bar()}
        """ % module_base)
        assert result_lines(t.render(x=1)) == ["foo: 1", "bar: 1"]
        assert result_lines(t.render(x=2)) == ["foo: 1", "bar: 1"]
        t.cache.invalidate_def('foo')
        assert result_lines(t.render(x=3)) == ["foo: 3", "bar: 1"]
        t.cache.invalidate_def('bar')
        assert result_lines(t.render(x=4)) == ["foo: 3", "bar: 4"]
 
        t = Template("""
            <%%page cached="True" cache_type="dbm" cache_dir="%s"/>
 
            page: ${x}
        """ % module_base)
        assert result_lines(t.render(x=1)) == ["page: 1"]
        assert result_lines(t.render(x=2)) == ["page: 1"]
        t.cache.invalidate_body()
        assert result_lines(t.render(x=3)) == ["page: 3"]
        assert result_lines(t.render(x=4)) == ["page: 3"]
Пример #16
0
 def gen_uvb_master_conf(self):
     uvb_dir = self.generated_dir + self.UVB_DIR
     if not os.path.exists(uvb_dir):
         os.makedirs(uvb_dir)    
                 
     template = Template(filename=self.demogrid_dir + self.UVB_TEMPLATE)
     uvb_master = template.render(domain = self.DOMAIN,
                                  ip = self.__gen_IP(0, 2),
                                  gw = self.__gen_IP(0, 1),
                                  dgl = self.demogrid_dir,
                                  execscript = "post-install-chefsolo.sh",
                                  copy = "files-chefsolo.txt")   
     uvb_masterfile = open(uvb_dir + "/uvb-chefsolo-master.conf", "w")
     uvb_masterfile.write(uvb_master)
     uvb_masterfile.close()          
     
     uvb_master = template.render(domain = self.DOMAIN,
                                  ip = self.__gen_IP(0, 2),
                                  gw = self.__gen_IP(0, 1),
                                  dgl = self.demogrid_dir,
                                  execscript = "post-install-chefserver.sh",
                                  copy = "files-chefserver.txt")
     uvb_masterfile = open(uvb_dir + "/uvb-chefserver-master.conf", "w")
     uvb_masterfile.write(uvb_master)
     uvb_masterfile.close()     
Пример #17
0
    def test_interpret_expression_from_arg_two(self):
        """test that cache_key=${foo} gets its value from
        the 'foo' argument regardless of it being passed
        from the context.

        This is here testing that there's no change
        to existing behavior before and after #191.

        """
        t = Template("""
        <%def name="layout(foo)" cached="True" cache_key="${foo}">
        foo: ${value}
        </%def>

        ${layout(3)}
        """, cache_impl="plain")

        eq_(
            result_lines(t.render(foo='foo', value=1)),
            ["foo: 1"]
        )
        eq_(
            result_lines(t.render(foo='bar', value=2)),
            ["foo: 1"]
        )
Пример #18
0
def check_arguments(function):
    assert isinstance(function, cpp_types.SimpleFunction)
    stmts = []
    arg_offset = 1

    if function.parent.proto.kind == cpp_types.FunctionKind.ClassMemberMethod:
        template = Template(filename = template_path + 'check_userdata_argument.cc')
        raw_cpp_type = '%s *' % function.parent.proto.fully_qualified_prefix
        stmt = template.render(arg = '__class_ptr', idx = arg_offset, hashcode = hash(raw_cpp_type))
        stmts.append(stmt)
        arg_offset += 1

    for idx, arg in enumerate([ function.parent.arguments[idx] for idx in xrange(0, function.argc) ]):
        arg_name = get_argument_name(arg, idx)
        narg = idx + arg_offset

        if type_traits.is_userdata_type(arg.type_):
            template = Template(filename = template_path + 'check_userdata_argument.cc')
            stat = template.render(arg = arg_name, idx = narg, hashcode = arg.type_.hashcode)
            stmts.append (stat)
        else:
            template = Template(filename = template_path + 'check_scalar_argument.cc')
            stat = template.render(arg = arg_name, idx = narg)
            stmts.append (stat)
    return stmts
Пример #19
0
 def test_no_lookup(self):
     t = Template("hi <%include file='foo.html'/>")
     try:
         t.render()
         assert False
     except exceptions.TemplateLookupException, e:
         assert str(e) == "Template 'memory:%s' has no TemplateLookup associated" % hex(id(t))
Пример #20
0
def get_func_call(func, args, argc):
    assert isinstance(func, parser.Function)
    assert isinstance(args, list)
    assert isinstance(argc, int)
    assert len(args) >= argc
    if len(args) != 0: assert isinstance(args[0], parser.ArgumentType)

    arg_names = []
    for idx, arg in enumerate(args):
        if idx == argc:
            break
        arg_name = get_arg_name(arg, idx+1)
        kind = arg.type_.kind
        if is_string_type(arg):
            pass
        elif kind == 'RECORD' or kind == 'LVALUEREFERENCE':
            arg_name = '*%s' % arg_name
        arg_names.append(arg_name)

    if func.is_constructor:
        arg_name_str = ', '.join(arg_names)
        template = Template( ''' new ${class_name}(${args}) ''')
        return template.render(class_name = func.fully_qualified_prefix, args = arg_name_str)
    elif func.is_class_member_method:
        arg_name_str = ', '.join(arg_names[1:])
        template = Template( ''' __class_ptr->${func_name}(${args}) ''')
        return template.render(func_name = func.name, args = arg_name_str)
    else:
        arg_name_str = ', '.join(arg_names)
        return '%s::%s(%s) ' % (func.fully_qualified_prefix, func.name, arg_name_str)
def construct_response(scenario_name):
    # load up response data
    data = json.load(open('scenario.cache','r'))
    lookup = TemplateLookup(directories=['./scenarios'])

    for path in glob2.glob('./scenarios/**/request.mako'):
        if path != scenario_name:
            continue
        event_name = path.split('/')[-2]
        template = Template("${response}")
        try:
            response = data[event_name].get('response', {})
            text = template.render(response=response).strip()
            response =  json.loads(text)
            del response["links"]
            for key, value in list(response.items()):
                response = value[0]
                type = key
                resource = balanced.Resource()
                object_type = resource.registry[type]
                object_instance = object_type()
                for key, value in list(response.items()):
                   setattr(object_instance, key, value)
            text = template.render(response=object_instance)
        except KeyError:
            text = ''
    return text
Пример #22
0
def main():
    argparser = argparse.ArgumentParser( description="A python implementation of the Embedded "
                                                     "Brainfuck compiler." )
    argparser.add_argument( "-v", "--verbose", action='count',
                            help="Enable verbose output while compiling the program." )
    argparser.add_argument( "infile",
                            help="A file containing Embedded Brainfuck instructions." )
    argparser.add_argument( "--prefix", default="",
                            help="The prefix to add to all output files." )
    argparser.add_argument( "--out_dir", default="",
                            help="The directory to write all output files to." )

    args = argparser.parse_args()

    with open(args.infile, 'r') as f:
        app = f.read()

    c = compiler.Compiler(app)
    c.compile()

    path = os.path.dirname(os.path.realpath(__file__))
    ebf_h_template = Template(filename=os.path.join(path, "templates", "ebf.h.mako"))
    main_c_template = Template(filename=os.path.join(path, "templates", "main.c.mako"))
    kwargs = c.config()

    with open(os.path.join( args.out_dir, args.prefix, "ebf.h"), 'w') as f:
        f.write(ebf_h_template.render(strict_undefined=True, **kwargs))

    with open(os.path.join( args.out_dir, args.prefix, "main.c"), 'w') as f:
        f.write(main_c_template.render(strict_undefined=True, application=c.application(), **kwargs))
Пример #23
0
def _generate_pdf(graphs, summary, overrep, bam_file, sample_name,
                  dirs, config):
    base = os.path.splitext(os.path.basename(bam_file))[0]
    sample_name = base if sample_name is None else " : ".join(sample_name)
    tmpl = Template(_section_template)
    sample_name = "%s (%s)" % (_safe_latex(sample_name),
                               _safe_latex(base))
    recal_plots = sorted(glob.glob(os.path.join(dirs["work"], "reports", "images",
                                                "%s*-plot.pdf" % base)))
    section = tmpl.render(name=sample_name, summary=None,
                          summary_table=summary,
                          figures=[(f, c, i) for (f, c, i) in graphs if f],
                          overrep=overrep,
                          recal_figures=recal_plots)
    out_file = os.path.join(dirs["work"], "%s-summary.tex" % base)
    out_tmpl = Template(_base_template)
    with open(out_file, "w") as out_handle:
        out_handle.write(out_tmpl.render(parts=[section]))
    if config["algorithm"].get("write_summary", True):
        cl = [config.get("program", {}).get("pdflatex", "pdflatex"), out_file]
        try:
            subprocess.check_call(cl)
        except:
            pass
    return "%s.pdf" % os.path.splitext(out_file)[0]
Пример #24
0
def main():
    query = cgi.FieldStorage()

    servers = {}

    if "server" not in query or "feature" not in query:
        # Define features here. Each tuple defines a
        # port@server and a tuple of feature names.
        licenses = [
            ('12345@server-name', ('feature-1', 'feature-2')),
            ('23456@server-name', ('feature-3', 'feature-4')),
        ]
    else:
        server = query.getvalue("server")
        feature = query.getvalue("feature")

        licenses = [(server, (feature,))]

    for server, features in licenses:
        servers[server] = {}

        for feature in features:
            servers[server][feature] = get_licenses(server, feature)

    template = Template(filename='flexlm.mako', module_directory='cache')

    print 'Content-Type: text/html'
    print

    print template.render(data=servers)
Пример #25
0
    def signup(self, username=None, password=None, from_page="/"):
        signup_template = Template(filename='signup.html')

        if username is None or password is None:
            return signup_template.render(msg="Enter login information", from_page=from_page)

        user_exist = self.check_user_exist(username)
        if user_exist:
            # username exist in the database, can't create
            return signup_template.render(msg="Username is taken, please try another one", from_page=from_page)
        else:
            # username does not exist in the database, can create it now
            group = "User"
            news_sources ={}
            news_targets ={}
            twitter_sources = []
            twitter_targets = []

            p = hashlib.md5()
            p.update(password)
            User(name = username,
                password = p.hexdigest(),
                group = group,
                news_sources = news_sources,
                news_targets = news_targets,
                twitter_sources = twitter_sources,
                twitter_targets = twitter_targets).save()

            # go to home page
            raise cherrypy.HTTPRedirect(from_page or "/")
Пример #26
0
    def location(self, name=None, thumbnails=None, deletechannels=None):
        repo = Repository()
        if deletechannels is not None:
            if (name is not None):
                repo.DeleteChannelsByLocation(unquote(name))
            else:
                repo.DeleteChannels()
            raise cherrypy.HTTPRedirect("/location", 307)

        if name is not None:
            if thumbnails is not None:
                channellist = repo.GetChannelsByLocation(name)
                template = Template(filename=TEMPLATE_BASE + "monitor_thumbnails.html")
                title = "Location: {0}".format(name)
                view = "location"
                return template.render(view=view, channellist=channellist, IPAddress=name, title=title)
            else:
                servers = repo.GetServers(unquote(name))
                for row in servers:
                   row.setdefault('URL', "/server?{0}".format(urlencode({'name':row['IPAddress']})))
                template = Template(filename=TEMPLATE_BASE + "monitor_servers.html")
                title = "Location: {0}".format(name)
                id = urlencode({'name':name})
                return template.render(model=servers, id=id, Location=name, title=title)
        else:
            locations = repo.GetLocations()
            for row in locations:
               row.setdefault('URL', "/location?{0}".format(urlencode({'name':row['Location']})))
            template = Template(filename=TEMPLATE_BASE + "monitor_locations.html")
            title = "All Locations"
            return template.render(model=locations, title=title)
Пример #27
0
    def search(self, term=None):
        if (term is None):
            template = Template(filename=TEMPLATE_BASE + "search.html")
            return template.render(model=None, title="Enter a Hostname, Location or Channel")
        else:
            print("Searching for {0}".format(term))
            repo = Repository()
            allchannels = repo.GetAllChannels()
            servers = query(allchannels).where(lambda x: x['Hostname'] == term).to_list()
            locations = query(allchannels).where(lambda x: x['Location'] == term).to_list()
            channels = query(allchannels).where(lambda x: x['Channel'] == term).to_list()
            template = Template(filename=TEMPLATE_BASE + "search.html")

            if (len(servers) > 0):
                to_return = servers
                title = "Found Server(s)"
            elif (len(locations) > 0):
                to_return = locations
                title = "Found Location(s)"
            elif (len(channels) > 0):
                to_return = channels
                title = "Found Channel(s)"
            else:
                to_return = []
                title = "Did not find any matches"

            if (to_return is not None):
               for row in to_return:
                   row.setdefault('URL', "/server?{0}".format(urlencode({'name':row['IPAddress']})))
            return template.render(model=to_return, title=title)
Пример #28
0
	def POST(self):
		
		form = login3()
		
		if not form.validates():
			mytemplate=Template(filename='log.html')
			return mytemplate.render(form=form)
		else:
			
			user = form.d.Nombre
			pas = form.d.Contrasenia
			
			try:
				conn=pymongo.MongoClient()
			except pymongo.errors.ConnectionFailure, e:
				print "Could not connect to MongoDB: %s" % e 
			
			
			db = conn['usuarios']
			collection = db.my_collection
			
		
			if db.my_collection.find({'password':form.d.Contrasenia,'usuario':form.d.Nombre}).count() == 1:

				fo = login2()
				fu = login4()
				mytemplate=Template(filename='principal.html')
				session.usuario = form.d.Nombre
				session.pagina = 'log'	
				session.pagantes = ''
				return mytemplate.render(fo=fo, user=user, fu=fu)
			else:
				mytemplate=Template(filename='log.html')
				return mytemplate.render(form=form)
Пример #29
0
def convert_result_to_userdata(res, func_call):
    assert isinstance(func_call, basestring)
    assert isinstance(res, parser.ResultType)
    assert is_userdata_type(res)

    template_str = '''
    ${wrapper_type} * res = (${wrapper_type}*) lua_newuserdata(L, sizeof(${wrapper_type}));
    res->type_info.is_const = ${is_const};
    res->type_info.needs_gc = ${needs_gc};
    res->type_info.hash = ${type_hash};
    %s

    return 1;
    '''

    needs_gc = 'false'
    if res.type_.kind == 'LVALUEREFERENCE':
        template = Template('res->val = (void*) &( ${func_call} );') 
        template_str = template_str % template.render(func_call = func_call)
    elif res.type_.kind == 'POINTER':
        template = Template('res->val = (void*) ( ${func_call} );')
        template_str = template_str % template.render(func_call = func_call)
    elif res.type_.kind == 'RECORD':
        template = Template('res->val = (void*) (new ${base_type} ( ${func_call} ));')
        template_str = template_str % template.render(base_type = res.type_.base_type, func_call = func_call)
        needs_gc = 'true'
    else:
        assert false

    template = Template(template_str)
    return template.render(wrapper_type = 'UserdataWrapper', is_const = res.type_.is_const and 'true' or 'false', needs_gc = needs_gc
            , type_hash = hash(res.type_.conversion_type) )
Пример #30
0
    def admin(self, mode="main", module=None, csv=None, blizzardurl=None, remote=None,status=None, **kwargs):
        request = cherrypy.serving.request
	'''raise cherrypy.HTTPRedirect("http://sc2.no", 307)'''
        if (request.method == 'POST'):
          blizzardurl = blizzardurl.strip()
          #print "post data: %s" % blizzardurl
          match = self.bnetregex.search(blizzardurl)
          if match:
            (bnetid, nick) = match.groups()
            if bnetid and nick:
              result = self.sc2.add(nick.decode('utf8'),bnetid,"no")
              raise cherrypy.HTTPRedirect("/admin/add/player/?status=Saved %s,%s : %s" % (bnetid,nick,result))
          else:
            raise cherrypy.HTTPRedirect("/admin/add/player/?status=%s" % "Not matching eu.battle.net url...")
        else:
          if (mode=="add" and module=="player" and remote):
            (bnet,nick) = remote.split(",")
            self.sc2.log("[%s] WEB : SC2.NO : Adding %s (%s)" % (datetime.now(),nick,bnet))
            result = self.sc2.add(nick,bnet,"no")
            return "%s" % result
              
          elif (mode=="add" and module=="player"):
            mytemplate = Template(filename="%s/frontend/admin/player/add.html" % self.base, input_encoding='utf-8',
    output_encoding='utf-8')
            if status:
              return mytemplate.render(data=csv,status=status)
            else:
              return mytemplate.render(data=csv)
          return "woops"
Пример #31
0
def admin_home():
    template = Template(filename='%s/admin/home.mako' % template_dir)
    return template.render()
Пример #32
0
    def _generate_record_from_line(self, cr, uid, configurator, line, context):
        current_pool = self.pool.get(line.name.model)
        current_record_ids = current_pool.search(
            cr,
            uid,
            line.domain and safe_eval(line.domain) or [],
            context=context)

        for current_record_id in current_record_ids:
            record = current_pool.browse(cr, uid,
                                         current_record_id,
                                         context=context)
            #//++++++++++++++++++++++
            #if line.user_field_id and \
               #record[line.user_field_id.name] and \
               #record[line.user_field_id.name]._table_name != 'res.users':
                #raise orm.except_orm(
                    #_('Error'),
                    #_("The 'User' field of record %s (%s) "
                      #"does not refer to res.users")
                    #% (record[line.description_field_id.name],
                       #line.name.model))

            if (((line.description_field_id and
                  record[line.description_field_id.name]) or
                    line.description_code) and
                    record[line.date_start_field_id.name]):
                duration = False
                if (not line.duration_field_id and
                        line.date_stop_field_id and
                        record[line.date_start_field_id.name] and
                        record[line.date_stop_field_id.name]):
                    
                    #//+++++++++++++++++++++++
                    #date_start = datetime.strptime(
                        #record[line.date_start_field_id.name],
                        #tools.DEFAULT_SERVER_DATETIME_FORMAT
                    #)
                    try:
                        date_start = datetime.strptime(
                            record[line.date_start_field_id.name],
                            tools.DEFAULT_SERVER_DATETIME_FORMAT
                        )
                    except:
                        date_start = datetime.strptime(
                            record[line.date_start_field_id.name] + ' 00:00:00',
                            tools.DEFAULT_SERVER_DATETIME_FORMAT
                        )
                    
                    #//+++++++++++++++++++++++
                    #date_stop = datetime.strptime(
                        #record[line.date_stop_field_id.name],
                        #tools.DEFAULT_SERVER_DATETIME_FORMAT
                    #)
                    try:
                        date_stop = datetime.strptime(
                            record[line.date_stop_field_id.name],
                            tools.DEFAULT_SERVER_DATETIME_FORMAT
                        )
                    except:
                        date_stop = datetime.strptime(
                            record[line.date_stop_field_id.name] + ' 00:00:00',
                            tools.DEFAULT_SERVER_DATETIME_FORMAT
                        )
                    
                    duration = (date_stop - date_start).total_seconds() / 3600
                elif line.duration_field_id:
                    duration = record[line.duration_field_id.name]
                if line.description_type != 'code':
                    name = record[line.description_field_id.name]
                else:
                    parse_dict = {'o': record}
                    mytemplate = Template(line.description_code)
                    name = mytemplate.render(**parse_dict)
                super_calendar_values = {
                    'name': name,
                    'model_description': line.description,
                    'date_start': record[line.date_start_field_id.name],
                    'duration': duration,
                    'user_id': (
                        line.user_field_id and
                        record[line.user_field_id.name] and
                        record[line.user_field_id.name].id or
                        False
                    ),
                    'configurator_id': configurator.id,
                    'res_id': line.name.model+','+str(record['id']),
                    'model_id': line.name.id,
                    }
                
                #//++++++++++++++++++++++
                #return super_calendar_values
                self.pool.get('super.calendar').create(cr, uid,
                    super_calendar_values, context=context)
        return {}
Пример #33
0
        if item.path != '':
            animatorParameters += File(
                item.path,
                "/*/AnimatorController/m_AnimatorParameters/*/m_Name"
            ).readConsts()
    constClasses.append(
        createConstClass("AnimatorParameter",
                         createConstMembers(animatorParameters)))

    # Generate
    print("")
    print("Generating Const Classes.")
    with open(os.path.join(outputDirectoryPath, "R.cs"), "w") as file:
        print("Writing Const Classes.")
        file.write(
            template.render(timeStamp=datetime.datetime.utcnow(),
                            constClasses=constClasses))

    print(
        "                                                         ..\n"
        "                                         .    ....▄▀  ▀▄.\n"
        "                                       #█▄ .æ╙   └       ╙▀▄\n"
        "                                      ╫       ,    ▄▄       ▄\n"
        "                                     ╫⌐   ▄╜   º'  ▀█,      ▀▄\n"
        "                                    ╒▀ ▓'▄           ╙'' ╙█▄ ▐▌\n"
        "                                      ▌▀            ▀      ▐▀  █\n"
        "              ,⌐⌐                    ╓▀  ▓    ,          .▀▄   █\n"
        "            ╩    ▌                   █   ▀  .╩    ▀█▌    ┌╙▄¥ ▐▌\n"
        "           █    ▐                   ╫      ▓Ö            ⁿ▄╦φ▓█\n"
        "           █    b                   █      ╙▀            ¥  █▀\n"
        "           ┌▄   ▀                   █⌐(█∞⌐.   .,»▀▄         █⌐\n"
        "      ╓▀     ╙%▄  ▀,                └█  '½⌐.  .╓═'▀        .█\n"
Пример #34
0
 def test_entity(self):
     t = Template("foo ${bar | entity}")
     eq_(
         flatten_result(t.render(bar="<'some bar'>")),
         "foo &lt;'some bar'&gt;",
     )
Пример #35
0
    def test_non_expression(self):
        t = Template(
            """
        <%!
            def a(text):
                return "this is a"
            def b(text):
                return "this is b"
        %>

        ${foo()}
        <%def name="foo()" buffered="True">
            this is text
        </%def>
        """,
            buffer_filters=["a"],
        )
        assert t.render().strip() == "this is a"

        t = Template(
            """
        <%!
            def a(text):
                return "this is a"
            def b(text):
                return "this is b"
        %>

        ${'hi'}
        ${foo()}
        <%def name="foo()" buffered="True">
            this is text
        </%def>
        """,
            buffer_filters=["a"],
            default_filters=["b"],
        )
        assert flatten_result(t.render()) == "this is b this is b"

        t = Template(
            """
        <%!
            class Foo:
                foo = True
                def __str__(self):
                    return "this is a"
            def a(text):
                return Foo()
            def b(text):
                if hasattr(text, 'foo'):
                    return str(text)
                else:
                    return "this is b"
        %>

        ${'hi'}
        ${foo()}
        <%def name="foo()" buffered="True">
            this is text
        </%def>
        """,
            buffer_filters=["a"],
            default_filters=["b"],
        )
        assert flatten_result(t.render()) == "this is b this is a"

        t = Template(
            """
        <%!
            def a(text):
                return "this is a"
            def b(text):
                return "this is b"
        %>

        ${foo()}
        ${bar()}
        <%def name="foo()" filter="b">
            this is text
        </%def>
        <%def name="bar()" filter="b" buffered="True">
            this is text
        </%def>
        """,
            buffer_filters=["a"],
        )
        assert flatten_result(t.render()) == "this is b this is a"
Пример #36
0
 def test_global(self):
     t = Template("""
         <%page expression_filter="h"/>
         ${"<tag>this is html</tag>"}
     """)
     assert t.render().strip() == "&lt;tag&gt;this is html&lt;/tag&gt;"
Пример #37
0
              <%include file="footer"/>""".format(page_name)

    page = Template(html, lookup=mylookup, strict_undefined=False)

    try:

        # Retrieve accepted papers from directory
        if page_name in ['acceptedpapers', 'proposals']:
            attributes["papers"] = getAcceptedPapers(
                attributes["papers_dir"],
                attributes["papers_pdf_link"],
                attributes["posters_pdf_link"],
            )

        # Generating the different .htm files
        s = page.render(**attributes)
        outfile = open('../%s.htm' % page_name, "w")
        outfile.write(str(s))
        outfile.close()

        # Copy home as index
        if page_name == 'home':
            outfile = open('../index.htm', "w")
            outfile.write(str(s))
            outfile.close()

    except Exception as e:
        print('Error')
        print(page_name, e)

        ctc = re.findall(reg, open(page_name).read())
Пример #38
0
def do_test(root_types, explicit_locations, glsl_version, extensions,
            tests_path):
    if explicit_locations and len(root_types) > 1:
        return

    basename = generate_file_name(root_types, explicit_locations)
    fullname = os.path.join(tests_path, basename)

    print(fullname)

    shader_file = open(fullname, "w", buffering=1)

    names = random_ubo.unique_name_dict()

    instances = []
    structs = []

    for type in root_types:
        assign_names(type, names)
        create_getters_and_setters(type, None, instances)
        gather_structs(type, structs)

    t = Template(
        dedent("""\
    [require]
    GLSL >= ${glsl_version // 100}.${glsl_version % 100}
    % for ext in extensions:
    ${ext}
    % endfor

    % if explicit_locations:
    GL_ARB_explicit_attrib_location
    % endif

    [vertex shader]
    % for ext in extensions:
    #extension ${ext}: require
    % endfor
    #extension GL_ARB_shader_bit_encoding: enable
    #extension GL_ARB_gpu_shader5: enable

    % if explicit_locations:
    #extension GL_ARB_explicit_attrib_location : require
    % endif

    precision highp float;
    % for s in structures:

    struct ${s.type} {
        % for m in s.members:
        ${"{:<15}".format(m.type)} ${m.name};
        % endfor
    };
    % endfor

    % for r in root_types:
    % if explicit_locations:
    layout(location = 0)
    % endif
    flat out ${"{:<10}".format(r.type)} ${r.name};
    % endfor

    in vec4 piglit_vertex;

    #if defined(GL_ARB_shader_bit_encoding) || defined(GL_ARB_gpu_shader5) || __VERSION__ >= 430
    float float_get(float f, uint bits) { return uintBitsToFloat(bits); }
    #else
    float float_get(float f, uint bits) { return f; }
    #endif
    % if glsl_version >= 400 or "GL_ARB_gpu_shader_fp64" in extensions:
    double double_get(uvec2 bits) { return packDouble2x32(bits); }
    %endif

    void main()
    {
    % for inst in instances:
        % for s in inst.setters:
        ${s}
        % endfor
    % endfor

        gl_Position = piglit_vertex;
    }

    [fragment shader]
    % for ext in extensions:
    #extension ${ext}: require
    % endfor
    #extension GL_ARB_shader_bit_encoding: enable
    #extension GL_ARB_gpu_shader5: enable

    % if explicit_locations:
    #extension GL_ARB_explicit_attrib_location : require
    % endif

    precision highp float;

    % for s in structures:
    struct ${s.type} {
        % for m in s.members:
        ${"{:<15}".format(m.type)} ${m.name};
        % endfor
    };
    % endfor

    % for r in root_types:
    % if explicit_locations:
    layout(location = 0)
    % endif
    flat in ${"{:<11}".format(r.type)} ${r.name};
    % endfor

    out vec4 piglit_fragcolor;

    #if defined(GL_ARB_shader_bit_encoding) || defined(GL_ARB_gpu_shader5) || __VERSION__ >= 430
    bool float_match(float u, float f, uint bits) { return floatBitsToUint(u) == bits; }
    #else
    bool float_match(float u, float f, uint bits) { return u == f; }
    #endif
    % if glsl_version >= 400 or "GL_ARB_gpu_shader_fp64" in extensions:
    bool double_match(double u, uvec2 bits) { return unpackDouble2x32(u) == bits; }
    %endif

    void main()
    {
        bool pass = true;

    % for inst in instances:
        % for s in inst.checkers:
        if (${s})
            pass = false;
        % endfor
    % endfor

        piglit_fragcolor = pass ? vec4(0, 1, 0, 1) : vec4(1, 0, 0, 1);
    }

    [test]
    link success

    draw rect -1 -1 2 2
    probe all rgba 0.0 1.0 0.0 1.0"""))

    shader = t.render(glsl_version=glsl_version,
                      root_types=root_types,
                      explicit_locations=explicit_locations,
                      structures=structs,
                      extensions=extensions,
                      instances=instances)

    shader_file.write(shader)
    shader_file.close()
Пример #39
0
def parse_tmpl(_tmpl, **kwargs):
    """ Render _tmpl using the kwargs. """
    from mako.template import Template
    block_template = Template(_tmpl)
    return str(block_template.render(**kwargs))
Пример #40
0
class VoiceRecognitionManager(TabClass):
    def __init__(self, language):

        self.ipWavServer = "192.168.5.80"  #"audio.openqbo.org"
        self.portWavServer = "80"  #"8588"
        self.language = language
        self.juliusPath = roslib.packages.get_pkg_dir("qbo_listen")
        self.juliusAMPath = "/usr/share/qbo-julius-model/"
        self.htmlTemplate = Template(
            filename='voiceRecognition/templates/voiceRecognitionTemplate.html'
        )
        self.jsTemplate = Template(
            filename='voiceRecognition/templates/voiceRecognitionTemplate.js')
        self.tmpdir = "/tmp/"
        self.LMPaths = "/config/LM/"
        self.LMFileName = "/sentences.conf"
        self.PhonemsFileName = "/phonems"
        self.TiedlistFileName = "/tiedlist"
        self.languages_names = {
            'en': 'English',
            'es': 'Spanish',
            'pt': 'Português',
            'de': 'Deutsch',
            'fr': 'Français',
            'it': 'Italiano'
        }
        self.path = roslib.packages.get_pkg_dir(
            "qbo_webi") + "/src/voiceRecognition/"
        self.lan = self.language["current_language"]
        self.mac = get_mac()
        self.p = None

    @cherrypy.expose
    def voiceRecognitionJs(self, parameters=None):
        self.lan = self.language["current_language"]
        return self.jsTemplate.render(language=self.language)

    def getLanguages(self):
        try:
            dirList = os.listdir(self.juliusPath + self.LMPaths)
            dirList.sort()
        except:
            dirList = -1
        return dirList

    def isQboListenInstalled(self):
        if self.getLanguages() == -1:
            return False
        else:
            return True

    def getLanguageModels(self, language):
        try:
            dirList = os.listdir(self.juliusPath + self.LMPaths + language)
            dirList.sort()
        except:
            dirList = -1
        return dirList

    def getLMSentences(self, language, model):
        try:
            f = open(
                self.juliusPath + self.LMPaths + language + "/" + model +
                self.LMFileName, 'r')
            return f.read()
        except:
            sentences = ""
        return sentences

    @cherrypy.expose
    def getModels(self, lang):
        modelList = ""
        try:
            dirList = os.listdir(self.juliusPath + self.LMPaths + lang)
            dirList.sort()
            for model in dirList:
                modelList = modelList + model + "::"
            modelList = modelList[:-2]
        except:
            modelList = -1
        return modelList

    @cherrypy.expose
    def test1(self, lang, text):
        text = text.encode("utf-8")
        f = open(self.tmpdir + 'LModel', 'w')
        f.write(text)
        f.close()
        words = gen_grammar.verrors(
            self.tmpdir + 'LModel',
            self.juliusAMPath + lang + "/" + self.PhonemsFileName)
        if words == 0:
            return ""
        else:
            wordsList = ""
            for word in words:
                wordsList = wordsList + word + "::"
                print word
                wordsList = wordsList[:-2]
            return wordsList

    @cherrypy.expose
    def test2(self, lang, text):
        errorlist = ""
        text = text.encode("utf-8")
        print text
        wordlist = text.split()
        print wordlist
        for word in wordlist:
            if word[0] != "[" and word[0] != "<":
                print word
                f = open(self.tmpdir + 'word', 'w')
                f.write("[sentence]\n")
                f.write(word)
                f.close()
                gen_grammar.createvoca(
                    self.tmpdir + 'word',
                    self.juliusAMPath + lang + "/" + self.PhonemsFileName,
                    self.tmpdir + 'word')
                print self.tmpdir + 'word'
                print self.juliusAMPath + lang + "/" + self.TiedlistFileName
                if gen_grammar.perrors(
                        self.tmpdir + 'word.voca', self.juliusAMPath + lang +
                        "/" + self.TiedlistFileName) != 0:
                    errorlist = errorlist + word + "::"
        errorlist = errorlist[:-2]
        return errorlist.upper()

    @cherrypy.expose
    def saveToFile(self, lang, text, model):
        #try:
        print self.juliusPath + self.LMPaths + lang + "/" + model + self.LMFileName
        text = text.encode("utf-8")
        f = open(
            self.juliusPath + self.LMPaths + lang + "/" + model +
            self.LMFileName, 'w')
        text11 = " will save to file!!!\n"
        print text11
        f.write(text)
        f.close()
        gen_grammar.compilegrammar(model, lang)
        #subprocess.Popen("roslaunch qbo_listen voice_recognizer.launch".split())
        #except:
        #		return "ERROR: Cant write the file"
        return ""

    @cherrypy.expose
    def getFile(self, lang="", model=""):
        if lang == "" or model == "":
            return "ERROR: lang:" + lang + "; model:" + model
        else:
            #print self.getLMSentences(lang,model)
            return self.getLMSentences(lang, model)

    @cherrypy.expose
    def index(self):
        tmp = ""
        if self.isQboListenInstalled():
            for lang in self.getLanguages():
                for LM in self.getLanguageModels(lang):
                    text = self.getLMSentences(lang, LM)
                    break
                break

            return self.htmlTemplate.render(language=self.language,
                                            lannames=self.languages_names,
                                            alllanguage=self.getLanguages())
        else:
            return "Qbo listen not installed"
#        return self.htmlTemplate.render(language=self.language)

    @cherrypy.expose
    def rec(self):

        #   n = self.getLenght("Arturo","sp")
        #   print "***** "+n

        #Borramos la anterior grabacion, si la habia
        try:
            cmd = "rm " + self.path + "tmp/*"
            self.p = Popen(cmd.split())
        except ValueError:
            print "Nada que borrar"
        '''
        try:    
            cmd="rm "+self.path+"/*_en"
            self.p = Popen(cmd.split())
        except ValueError:
            print "Nada que borrar"

        try:
            cmd="rm "+path+"/*sp"
            print cmd
            self.p = Popen(cmd.split())

        except ValueError:
            print "Nada que borrar"
        '''

        self.filename = str(self.mac) + "_" + self.lan
        #filename = filename.replace("\"","")

        #   filename = "tmp.wav"

        print "FILENAME == " + self.filename

        print "grabnando!!!! " + self.path + "tmp/" + self.filename
        cmd = "arecord -f S16_LE  -r 44100 -c 1 " + self.path + "tmp/" + self.filename

        self.p = Popen(cmd.split())

        name = "oleole"
        return name

    @cherrypy.expose
    def stop(self):

        if (self.p == None):
            print "P ES NULL!!??"
        else:
            print "matar grabacin"
            self.p.send_signal(signal.SIGINT)

        cmd = "python " + self.path + "sendWav2Server.py " + self.path + "tmp/" + self.filename + " " + self.ipWavServer + " " + self.portWavServer
        print cmd
        out = runCmd(cmd)

        print out[0]

        if out[1] != "":
            print "Error"
            return "error"

        return unicode(out[0], 'utf8')

    @cherrypy.expose
    def play(self):
        print "play sound"

        os.system('aplay ' + self.path + "tmp/" + self.filename)

        return "ok"

    @cherrypy.expose
    def save(self, transcripcion):
        print "SAVE! transcripcion=" + transcripcion

        cmd = "python " + self.path + "sendTranscription2Server.py " + str(
            self.mac
        ) + " \"" + transcripcion + "\" " + self.lan + " " + self.ipWavServer + " " + self.portWavServer
        print cmd
        out = runCmd(cmd)

        if out[1] != "":
            print "Error " + out[1]
            return "error"

        return out[0]
Пример #41
0
class globalCheck(chekers):
    def __init__(self, lang):
        chekers.__init__(self, 'globalCheck', lang)

        #Codigo ROS
        self.test_client = rospy.ServiceProxy('/qbo_arduqbo/test_service',
                                              Test)

        self.htmlTmpl = Template(filename='sysChecks/chekers/' + self.name +
                                 '/templates/globalCheckTemplate.html')
        self.cssTmpl = Template(filename='sysChecks/chekers/' + self.name +
                                '/templates/globalCheckTemplate.css')
        #print self.cssTmpl
        #print chekers.cssTmpl
        testDic = self.doTest()

    def unlockWheel(self, src):
        src = src[0]
        if (src == "left"):
            os.system("rosservice call /qbo_arduqbo/unlock_motors_stall")
        elif (src == "right"):
            os.system("rosservice call /qbo_arduqbo/unlock_motors_stall")
        return "ok"

    def get_html_content(self):
        testDic = self.doTest()
        return self.htmlTmpl.render(language=self.language,
                                    check_result=testDic)

    def doTest(self):
        try:
            testResponse = self.test_client()
            testDic = {}
            testDic['SRFcount'] = testResponse.SRFcount
            testDic['SRFAddress'] = testResponse.SRFAddress
            testDic['SRFNotFound'] = testResponse.SRFNotFound
            testDic['Gyroscope'] = testResponse.Gyroscope
            testDic['Accelerometer'] = testResponse.Accelerometer
            testDic['LCD'] = testResponse.LCD
            testDic['Qboard3'] = testResponse.Qboard3
            testDic['Qboard1'] = testResponse.Qboard1
            testDic['Qboard2'] = testResponse.Qboard2
            testDic['leftMotor'] = testResponse.leftMotor
            testDic['rightMotor'] = testResponse.rightMotor
            testDic['Total'] = testDic['Gyroscope'] and testDic[
                'Accelerometer'] and testDic['LCD'] and testDic[
                    'Qboard3'] and testDic['Qboard2'] and testDic[
                        'Qboard1'] and testDic['leftMotor'] and testDic[
                            'rightMotor'] and len(testDic['SRFNotFound']) == 0
            print 'Diccionario:', testDic
        #return self.htmlTmpl.render(language=self.language)
        except Exception, e:
            testDic = {}
            testDic['SRFcount'] = False
            testDic['SRFAddress'] = False
            testDic['SRFNotFound'] = False
            testDic['Gyroscope'] = False
            testDic['Accelerometer'] = False
            testDic['LCD'] = False
            testDic['Qboard3'] = False
            testDic['Qboard1'] = False
            testDic['Qboard2'] = False
            testDic['leftMotor'] = False
            testDic['rightMotor'] = False
            testDic['Total'] = False
            print 'Error: ', e
        if testDic['Total']:
            self.result = 'ok'
        else:
            self.result = 'fail'
        return testDic
Пример #42
0
def _generate_abstract_impl(gapi):
    prim_name = gapi['parameters']['prim_name']
    prim_cores = _prim_cores(gapi['cores'], prim_name)

    techlibs = _techlibs(prim_cores)

    if not 'generic' in techlibs:
        raise ValueError("Techlib generic is required, but not found for "
                         "primitive %s." % prim_name)
    print("Implementations for primitive %s: %s" %
          (prim_name, ', '.join(techlibs)))

    # Extract port list out of generic implementation
    generic_core = _core_info_for_techlib(prim_cores, 'generic')[1]
    generic_module_name = 'prim_generic_' + prim_name
    top_module_filename = _top_module_file(generic_core['files'],
                                           generic_module_name)
    top_module_file = os.path.join(generic_core['core_root'],
                                   top_module_filename)

    print("Inspecting generic module %s" % (top_module_file, ))
    generic_hdr = _parse_module_header(top_module_file, generic_module_name)

    # Render abstract primitive HDL from template
    print("Creating SystemVerilog module for abstract primitive")
    abstract_prim_sv_tpl_filepath = os.path.join(os.path.dirname(__file__),
                                                 'primgen',
                                                 'abstract_prim.sv.tpl')
    abstract_prim_sv_tpl = Template(filename=abstract_prim_sv_tpl_filepath)

    abstract_prim_sv = abstract_prim_sv_tpl.render(
        encoding="utf-8",
        prim_name=prim_name,
        module_header_imports=generic_hdr['package_import_declaration'],
        module_header_params=generic_hdr['parameter_port_list'],
        module_header_ports=generic_hdr['ports'],
        # Creating the code to instantiate the primitives in the Mako templating
        # language is tricky to do; do it in Python instead.
        instances=_create_instances(prim_name, techlibs,
                                    generic_hdr['parameters']))
    abstract_prim_sv_filepath = 'prim_%s.sv' % (prim_name)
    with open(abstract_prim_sv_filepath, 'w') as f:
        f.write(abstract_prim_sv)
    print("Abstract primitive written to %s" %
          (os.path.abspath(abstract_prim_sv_filepath), ))

    # Create core file depending on all primitive implementations we have in the
    # techlibs.
    print("Creating core file for primitive %s." % (prim_name, ))
    abstract_prim_core_filepath = os.path.abspath('prim_%s.core' % (prim_name))
    dependencies = []
    dependencies.append('lowrisc:prim:prim_pkg')
    dependencies += [
        _core_info_for_techlib(prim_cores, t)[0] for t in techlibs
    ]
    abstract_prim_core = {
        'name': "lowrisc:prim_abstract:%s" % (prim_name, ),
        'filesets': {
            'files_rtl': {
                'depend': dependencies,
                'files': [
                    abstract_prim_sv_filepath,
                ],
                'file_type': 'systemVerilogSource'
            },
        },
        'targets': {
            'default': {
                'filesets': [
                    'files_rtl',
                ],
            },
        },
    }
    with open(abstract_prim_core_filepath, 'w') as f:
        # FuseSoC requires this line to appear first in the YAML file.
        # Inserting this line through the YAML serializer requires ordered dicts
        # to be used everywhere, which is annoying syntax-wise on Python <3.7,
        # where native dicts are not sorted.
        f.write('CAPI=2:\n')
        yaml.dump(abstract_prim_core,
                  f,
                  encoding="utf-8",
                  default_flow_style=False,
                  sort_keys=False)
    print("Core file written to %s" % (abstract_prim_core_filepath, ))
}
""")

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('--out-c', help='Output C file.', required=True)
    parser.add_argument('--out-h', help='Output H file.', required=True)
    parser.add_argument('--xml',
                        help='Vulkan API XML file.',
                        required=True,
                        action='append',
                        dest='xml_files')
    args = parser.parse_args()

    for filename in args.xml_files:
        _init_exts_from_xml(filename)

    for ext in EXTENSIONS:
        assert ext.type == 'instance' or ext.type == 'device'

    template_env = {
        'MAX_API_VERSION': MAX_API_VERSION,
        'instance_extensions': [e for e in EXTENSIONS if e.type == 'instance'],
        'device_extensions': [e for e in EXTENSIONS if e.type == 'device'],
    }

    with open(args.out_c, 'w') as f:
        f.write(_TEMPLATE_C.render(**template_env))
    with open(args.out_h, 'w') as f:
        f.write(_TEMPLATE_H.render(**template_env))
Пример #44
0
#!/usr/bin/python

from mako.template import Template
import cgi
import json

data = json.load(open('data.json'))

html = Template(filename='templates/player.html')
print 'Content-Type: text/html'
print

arguments = cgi.FieldStorage()
if 'v' in arguments:
    try:
        index = int(arguments['v'].value)
    except:
        pass
    else:
        vids = data['videos']
        if index >= 0 and index < len(vids):
            print html.render(playlist=vids[index]['playlist'])
Пример #45
0
 def overview_template(self, overview_list, title, start=0, count=10):
     template = Template('<%include file="overview.html"/>', lookup=self.template_lookup, output_encoding='utf-8', encoding_errors='replace')
     return template.render(headline=title, title=title, overview_list=overview_list, start=start, count=count)
Пример #46
0
 def get_code(self):
     path = join(dirname(__file__), 'acceleration_eval_cython.mako')
     template = Template(filename=path)
     main = template.render(helper=self)
     return main
Пример #47
0
def admin_component_type():
    # Get component_type data
    component_types = model.session.query(model.ComponentType).all()
    template = Template(filename='%s/admin/component_type.mako' % template_dir)
    return template.render(component_types=component_types)
Пример #48
0
 def help_template(self,report_overview=[]):
     template = Template('<%include file="help.html"/>', lookup=self.template_lookup, output_encoding='utf-8', encoding_errors='replace')
     return template.render(title='SHIVA honeypot: help') 
Пример #49
0
    def _generate_cython_code(self):
        name = self.name
        all_py_data = [[], []]
        all_c_data = [[], []]

        # Process input function
        py_data, c_data, input_expr = self._wrap_cython_code(self.input_func,
                                                             func_type='input')
        self._append_cython_arg_data(all_py_data, all_c_data, py_data, c_data)

        # Process segment function
        use_segment = True if self.is_segment_func is not None else False
        py_data, c_data, segment_expr = self._wrap_cython_code(
            self.is_segment_func, func_type='segment')
        self._append_cython_arg_data(all_py_data, all_c_data, py_data, c_data)

        # Process output expression
        calc_last_item = False
        calc_prev_item = False

        py_data, c_data, output_expr = self._wrap_cython_code(
            self.output_func, func_type='output')
        if self.output_func is not None:
            calc_last_item = self._include_last_item()
            calc_prev_item = self._include_prev_item()
        self._append_cython_arg_data(all_py_data, all_c_data, py_data, c_data)

        # Add size argument
        py_defn = ['long SIZE'] + all_py_data[0]
        c_defn = ['long SIZE'] + all_c_data[0]
        py_args = ['SIZE'] + all_py_data[1]
        c_args = ['SIZE'] + all_c_data[1]

        # Only use unique arguments
        py_defn = drop_duplicates(py_defn)
        c_defn = drop_duplicates(c_defn)
        py_args = drop_duplicates(py_args)
        c_args = drop_duplicates(c_args)

        self.arg_keys = c_args

        if self._config.use_openmp:
            template = Template(text=scan_cy_template)
        else:
            template = Template(text=scan_cy_single_thread_template)
        src = template.render(name=self.name,
                              type=self.type,
                              input_expr=input_expr,
                              scan_expr=self.scan_expr,
                              output_expr=output_expr,
                              neutral=self.neutral,
                              c_arg_sig=', '.join(c_defn),
                              py_arg_sig=', '.join(py_defn),
                              py_args=', '.join(py_args),
                              openmp=self._config.use_openmp,
                              calc_last_item=calc_last_item,
                              calc_prev_item=calc_prev_item,
                              use_segment=use_segment,
                              is_segment_start_expr=segment_expr,
                              complex_map=self.complex_map)
        self.tp.add_code(src)
        self.tp.compile()
        return getattr(self.tp.mod, 'py_' + self.name)
 def __str__(self):
     self.pre_print()
     t = Template(filename='migrate_oracle_to_nz_ddl.sql')
     return t.render(table=self, settings=self.settings)
Пример #51
0
% for kind,values in info:

const char *
spirv_${kind.lower()}_to_string(Spv${kind} v)
{
   switch (v) {
    % for name in values:
   case Spv${kind}${name}: return "Spv${kind}${name}";
    % endfor
   case Spv${kind}Max: break; /* silence warnings about unhandled enums. */
   }

   return "unknown";
}
% endfor
""")

if __name__ == "__main__":
    pargs = parse_args()

    spirv_info = json.JSONDecoder().decode(open(pargs.json, "r").read())

    info = [
        collect_data(spirv_info, "Capability"),
        collect_data(spirv_info, "Decoration"),
        collect_opcodes(spirv_info),
    ]

    with open(pargs.out, 'w') as f:
        f.write(TEMPLATE.render(info=info))
 def _404(self):
     tmpl = os.path.join(_HERE, 'templates', '404.mako')
     with open(tmpl) as f:
         tmpl = Template(f.read())
     body = tmpl.render()
     return Response(status=404, body=body)
Пример #53
0
def generate(filename, info):

    functions = []
    function_length = 0
    for cn, cat in info.items():
        for fn, func in cat.items():
            functions.append(func['snake_name'])
            if function_length < len(fn):
                function_length = len(fn)
    function_length += 2

    unimplemented = []
    with open(abspath(join(
        dirname(abspath(__file__)),
        '..', '..', '..',
            'src', 'functions', 'implements', 'unimplemented.c'))) as f:
        for l in f.readlines():
            l = l.rstrip()
            m = re.search('exec_([0-9a-z_]+)', l)
            if m:
                unimplemented.append(m.groups(0)[0])

    implemented = {}
    implement_types = ['float', 'generic']
    impl_length = 14
    for root, dirs, files in walk(abspath(join(dirname(abspath(__file__)),
                                               '..', '..', '..', 'src'))):
        for fn in files:
            if splitext(fn)[1] == '.c':
                with open(join(root, fn), encoding='utf-8') as f:
                    code = f.read()
                    m = re.findall('allocate_([0-9a-z_]+)_local_context', code)
                    if m:
                        func_name = m[0]
                        if func_name not in implemented:
                            implemented[func_name] = []
                        func_f = re.findall('exec_{}'.format(func_name), code)
                        if func_f:
                            implemented[func_name].append('float')
                        func_g = re.findall('([0-9a-z_]+)_generic', code)
                        if func_g:
                            implemented[func_name].append('generic')

    count = 0
    count_impl = 0
    counts = {}
    counts_impl = {}
    for cn, cat in info.items():
        counts[cn] = 0
        counts_impl[cn] = 0
        for fn, func in cat.items():
            count += 1
            counts[cn] += 1
            if func['snake_name'] not in unimplemented:
                count_impl += 1
                counts_impl[cn] += 1

    table = ''
    table += '# Implement status\n'
    table += '\n'
    table += 'Total {}/{}\n'.format(count_impl, count)
    table += '\n'
    implement_types = sorted(implement_types)
    header = '|{{:^{}}}|{{:^{}}}|'.format(
        function_length, impl_length).format('Function', 'Available')
    for impl in implement_types:
        header += '{{:^{}}}|'.format(impl_length).format(impl)
    header += '\n'
    header += '|{{:^{}}}|{{:^{}}}|'.format(
        function_length, impl_length).format('-' * function_length, '-' * impl_length)
    for impl in implement_types:
        header += '{{:^{}}}|'.format(impl_length).format('-'*impl_length)
    header += '\n'

    for cn, cat in info.items():
        table += '\n'
        table += '## {}\n'.format(cn)
        table += 'Count {}/{}\n'.format(counts_impl[cn], counts[cn])
        table += '\n'
        table += header
        for fn, func in cat.items():
            name = fn
            if func['snake_name'] in unimplemented:
                line = '|{{:^{}}}|{{:^{}}}|'.format(
                    function_length, impl_length).format(fn, 'no')
                for impl in implement_types:
                    line += '{{:^{}}}|'.format(impl_length).format('-')
            else:
                line = '|{{:^{}}}|{{:^{}}}|'.format(
                    function_length, impl_length).format(fn, 'yes')
                for impl in implement_types:
                    if func['snake_name'] in implemented:
                        if impl in implemented[func['snake_name']]:
                            line += '{{:^{}}}|'.format(
                                impl_length).format('yes')
                        else:
                            line += '{{:^{}}}|'.format(impl_length).format('-')
                    else:
                        line += '{{:^{}}}|'.format(impl_length).format('?')
            table += line + '\n'

    from mako.template import Template
    from mako import exceptions
    try:
        tmpl = Template(filename=filename)
        output = tmpl.render(table=table)
        return output
    except:
        print(exceptions.text_error_template().render())
    return None
Пример #54
0
    def _generate(self):
        if self.backend == 'cython':
            if self.func is not None:
                self.tp.add(self.func)
                py_data, c_data = self.cython_gen.get_func_signature(self.func)
                self._correct_return_type(c_data)
                name = self.func.__name__
                cargs = ', '.join(c_data[1])
                map_expr = '{name}({cargs})'.format(name=name, cargs=cargs)
            else:
                py_data = (['int i', '{type}[:] inp'.format(type=self.type)],
                           ['i', '&inp[0]'])
                c_data = (['int i',
                           '{type}* inp'.format(type=self.type)], ['i', 'inp'])
                map_expr = 'inp[i]'
            py_defn = ['long SIZE'] + py_data[0][1:]
            c_defn = ['long SIZE'] + c_data[0][1:]
            py_args = ['SIZE'] + py_data[1][1:]
            template = Template(text=reduction_cy_template)
            src = template.render(name=self.name,
                                  type=self.type,
                                  map_expr=map_expr,
                                  reduce_expr=self.reduce_expr,
                                  neutral=self.neutral,
                                  c_arg_sig=', '.join(c_defn),
                                  py_arg_sig=', '.join(py_defn),
                                  py_args=', '.join(py_args),
                                  openmp=self._config.use_openmp,
                                  get_parallel_range=get_parallel_range)
            self.tp.add_code(src)
            self.tp.compile()
            return getattr(self.tp.mod, 'py_' + self.name)
        elif self.backend == 'opencl':
            if self.func is not None:
                self.tp.add(self.func)
                py_data, c_data = self.cython_gen.get_func_signature(self.func)
                self._correct_opencl_address_space(c_data)
                name = self.func.__name__
                expr = '{func}({args})'.format(func=name,
                                               args=', '.join(c_data[1]))
                arguments = convert_to_float_if_needed(', '.join(
                    c_data[0][1:]))
                preamble = convert_to_float_if_needed(self.tp.get_code())
            else:
                arguments = '{type} *in'.format(type=self.type)
                expr = None
                preamble = ''

            from .opencl import get_context, get_queue
            from pyopencl.reduction import ReductionKernel
            from pyopencl._cluda import CLUDA_PREAMBLE
            cluda_preamble = Template(text=CLUDA_PREAMBLE).render(
                double_support=True)

            ctx = get_context()
            self.queue = get_queue()
            knl = ReductionKernel(ctx,
                                  dtype_out=self.dtype_out,
                                  neutral=self.neutral,
                                  reduce_expr=self.reduce_expr,
                                  map_expr=expr,
                                  arguments=arguments,
                                  preamble="\n".join(
                                      [cluda_preamble, preamble]))
            return knl
        elif self.backend == 'cuda':
            if self.func is not None:
                self.tp.add(self.func)
                py_data, c_data = self.cython_gen.get_func_signature(self.func)
                self._correct_opencl_address_space(c_data)
                name = self.func.__name__
                expr = '{func}({args})'.format(func=name,
                                               args=', '.join(c_data[1]))
                arguments = convert_to_float_if_needed(', '.join(
                    c_data[0][1:]))
                preamble = convert_to_float_if_needed(self.tp.get_code())
            else:
                arguments = '{type} *in'.format(type=self.type)
                expr = None
                preamble = ''

            from .cuda import set_context
            set_context()
            from pycuda.reduction import ReductionKernel
            from pycuda._cluda import CLUDA_PREAMBLE
            cluda_preamble = Template(text=CLUDA_PREAMBLE).render(
                double_support=True)

            knl = ReductionKernel(dtype_out=self.dtype_out,
                                  neutral=self.neutral,
                                  reduce_expr=self.reduce_expr,
                                  map_expr=expr,
                                  arguments=arguments,
                                  preamble="\n".join(
                                      [cluda_preamble, preamble]))
            return knl
 def GET(self):
     t = Template(filename='03-backbonejs-collection.html',
                  input_encoding='utf-8')
     return t.render()
Пример #56
0
def extract(articles, encoding):
    tpl = Template(filename="scrape.tpl")
    text = tpl.render(attrs={"articles": articles})
    file = open("screenshot.txt", "w", encoding=encoding)
    file.write(text)
    file.close()
    def simular(self):
        mesh_start_time = time.time()
        submarino = Submarino(self.submarin_conf, self.file_name)
        submarino.meshear()
        time_mesh = time.time() - mesh_start_time

        vcc = 'Variable time; Real MATC "corriente(tx-1)"'
        corriente_vals = [
            c / ((4 * np.pi * (self.submarin_conf['sensor.radio']**2)) / 2)
            for c in self.sim_params_join['corriente_sensor']
        ]

        if not os.path.exists(self.sim_folder):
            os.mkdir(self.sim_folder)

        cond_agua = 'Variable time; Real MATC "conductividad(tx-1)"'
        cond_vals = self.sim_params_join['conductividad_agua']

        with open(f'{self.sim_folder}/case.sif', 'w') as text_file:
            case_template = Template(filename='case_template.sif')
            case = case_template.render(
                folder_sim=self.sim_folder,
                num_params=len(self.sim_combs),
                conductividad_vals=' '.join(map(str, cond_vals)),
                conductividad_agua=cond_agua,
                corriente_vals=' '.join(map(str, corriente_vals)),
                vcc=vcc)
            text_file.write(case)

        grid_start_time = time.time()
        subprocess.run(
            f'{self.cluster_env_var}ElmerGrid 14 2 {self.file_name}.msh -out {self.sim_folder} -unite -removeintbcs -removelowdim -removeunused -3d',
            shell=True,
            stdout=subprocess.DEVNULL)
        time_grid = time.time() - grid_start_time

        os.remove(f'{self.file_name}.msh')

        solver_start_time = time.time()
        subprocess.run(
            f'{self.cluster_env_var}ElmerSolver {self.sim_folder}/case.sif',
            shell=True,
            stdout=subprocess.DEVNULL)
        time_solver = time.time() - solver_start_time

        voltages = []
        for vtu in glob.glob(f'{self.sim_folder}/case_*.vtu'):
            reader = vtk.vtkXMLUnstructuredGridReader()
            reader.SetFileName(vtu)
            reader.Update()
            output = reader.GetOutput()
            potential = output.GetPointData().GetArray('potential')

            voltages.append(vtk_to_numpy(potential).max())

        times = {
            'time.mesh': time_mesh,
            'time.grid': time_grid,
            'time.solver': time_solver
        }

        res_dicts = []
        for i in range(len(self.sim_combs)):
            d = {
                'v': voltages[i],
                'id': self.file_name,
                **self.sim_combs[i],
                **self.submarin_conf,
                **times
            }
            res_dicts.append(d)

        return res_dicts
Пример #58
0
#include <${header}>

namespace FishEngine
{

${functions}

} // namespace FishEngine
'''
template = Template(template_str)

runtime_root_dir = os.path.abspath('../../Engine/Source/Runtime')
editor_root_dir = os.path.abspath('../../Engine/Source/Editor')

output_hpp_dir = os.path.join(runtime_root_dir, "generate")
output_hpp_dir_editor = os.path.join(editor_root_dir, "generate")

for e in enums.keys():
    item = enums[e]
    enum_functions = GenEnumFunctions(e, item['scope_prefix'],
                                      enums[e]['data'])
    s = template.render(header=item['header_file'],
                        scope=item['scope_prefix'],
                        functions=enum_functions)
    d = output_hpp_dir
    #print(item['path'], editor_root_dir)
    if item['path'].startswith(editor_root_dir):
        d = output_hpp_dir_editor
    output_file_path = os.path.join(d, "Enum_{}.hpp".format(e))
    UpdateFile(output_file_path, s)
Пример #59
0
    config = json.loads(config_init.read())

if str(args.handoff)[-3:] != "xsa":
    print("Handoff file must be in .xsa format.")
    print(
        colored(
            "usage: gen_pl_overlay.py [-h] [-c CONFIG] [-f HANDOFF] [-o OUTPUT] [-d DEVICE_TREE_COMPILER]",
            "green"))
    sys.exit(1)

HANDOFF_FILE = str(args.handoff)
vlnv = config["config"]["xcel_rdai_vlnv"]
device_vlnv_gen = Template(
    '${ip_vendor}:${ip_library}:${ip_name}:${ip_version}')
DEVICE_VLNV = device_vlnv_gen.render(ip_vendor=vlnv["vendor"],
                                     ip_library=vlnv["library"],
                                     ip_name=vlnv["name"],
                                     ip_version=vlnv["version"])
VIVADO_PROJECT_NAME = config["config"]["name"]
OUTPUT_DIR = "work/output"

if args.output != None:
    OUTPUT_HANDOFF = str(args.output)
    print(colored("Output handoff files placed in: " + OUTPUT_HANDOFF))
elif args.output == None and config["config"]["vivado_handoff_dir"] != None:
    OUTPUT_HANDOFF = config["config"]["vivado_handoff_dir"]
    print(
        colored(
            "Output handoff files placed in: " + OUTPUT_HANDOFF +
            " (output directory specified in config.json)", "green"))
else:
    OUTPUT_HANDOFF = "."
Пример #60
0
def main():
    ## 
    print "Content-type: text/html\n"
    page = 1
    connector = MySQLdb.connect(host="localhost",db="proposal_recommender",user="******",passwd="")
    connector.autocommit(True)
    cursor = connector.cursor()


    ## request parameters
    form = cgi.FieldStorage()
    # userId
    if form.has_key("userId"):
        userId = form["userId"].value

    # page
    if form.has_key("page"):
        page = int(form["page"].value) + 1
    
    # like    
    if form.has_key("like"):
        ## insert result_like data
        for i in form.getlist("like"):
            sql5 = "select genre_id from image where id = " + str(i)
            cursor.execute(sql5)
            result5 = cursor.fetchall()
            genreId = result5[0][0]
            sql4 = "insert into result_like (image_id, user_id, genre_id) values (" + str(i) + " , " + str(userId) + " , " + str(genreId) + ")"
            cursor.execute(sql4)


    ## create data
    list = []
    for i in range(6):
        sql1 = "select * from history where genre_id = " + str(i) + " and user_id = " + str(userId) + " and shown_flg = 0 limit 1"
        cursor.execute(sql1)
        result1 = cursor.fetchall()

        for row in result1:
            imageId = row[0]
            
            sql2 = "select file_name from image where id = " + str(imageId)
            cursor.execute(sql2)
            result2 = cursor.fetchall()
    
            name = result2[0][0]
            
            image = Image(imageId, name, i)
            list.append(image)


    ## update history to be shown
    for image in list:
        sql3 = "update history set shown_flg = 1 where image_id = " + str(image.id) + " and user_id =  " + str(userId)
        cursor.execute(sql3)
        connector.commit()


    ## data for view
    t = Template(filename = dirpath + "/templates/study.html")
 
#    ip = os.environ["REMOTE_ADDR"]
    ip = "localhost"
    data = {"list": list, "ip": ip, "page": page, "userId": userId}
 
    html = t.render(**data)
    print html