Beispiel #1
0
def submit(request):
    params = request.params
    
    emailTemplate = Template(filename='relentless/templates/appointmentEmail.mak')
    outputBuffer = StringIO()
    contextObject = Context(outputBuffer, params=params)
    emailTemplate.render_context(contextObject)
    emailBody = outputBuffer.getvalue()

    msg = MIMEText(emailBody)

    # Email a copy of the booking to our email address
    sender = '*****@*****.**'
    receivers = ['*****@*****.**']

    msg['Subject'] = 'Relentless Cleaning Booking! %s ' %(params['inputAddress'])
    msg['From'] = sender
    msg['To'] = '*****@*****.**'

    server = smtplib.SMTP('smtp.gmail.com:587')
    username = '******'
    password = '******'
    server.ehlo()
    server.starttls()
    server.login(username, password)
    server.sendmail(sender, receivers, msg.as_string())
    server.quit()
    
    return {'params': params}
Beispiel #2
0
    def mako_notice(self, fnames):
        attach = []
        path = ''

        exp_date = date.today() + timedelta(30)
        exp_date = exp_date.strftime('%B %d, %Y')

        for fname in fnames:
            regex_dropdir = re.compile("dropdir/(.*)")
            r1 = regex_dropdir.search(self.attachDir)
            dirs = r1.groups()
            if not path: path = dirs[0]

            fname[2] = self.fhandling.filesize_notation(fname[1])
            fname[3] = urllib2.quote(fname[0].encode('utf-8'))

            fname[0] = self.fhandling.unicodeConvert(fname[0])

            attach.append(fname)

        EARStemplate = Template(filename='www/EARS.html',
                                input_encoding='utf-8',
                                output_encoding='utf-8',
                                encoding_errors='replace')
        buf = StringIO()
        ctx = Context(buf, filepath=path, attachments=attach, deldate=exp_date)

        try:
            EARStemplate.render_context(ctx)
            return buf.getvalue()
        except:
            return exceptions.html_error_template().render()
Beispiel #3
0
def render_perf_html_report(report_dir):
  """Generate a simple HTML report for the perf tests."""
  template_file = 'tools/run_tests/perf_html_report.template'
  try:
    mytemplate = Template(filename=template_file, format_exceptions=True)
  except NameError:
    print('Mako template is not installed. Skipping HTML report generation.')
    return
  except IOError as e:
    print('Failed to find the template %s: %s' % (template_file, e))
    return

  resultset = {}
  for result_file in glob.glob(os.path.join(report_dir, '*.json')):
    with open(result_file, 'r') as f:
      scenario_result = json.loads(f.read())
      test_case = scenario_result['scenario']['name']
      if 'ping_pong' in test_case:
        latency50 = round(scenario_result['summary']['latency50'], 2)
        latency99 = round(scenario_result['summary']['latency99'], 2)
        summary = {'latency50': latency50, 'latency99': latency99}
      else:
        summary = {'qps': round(scenario_result['summary']['qps'], 2)}
      resultset[test_case] = summary

  args = {'resultset': resultset}

  html_file_path = os.path.join(report_dir, 'index.html')
  try:
    with open(html_file_path, 'w') as output_file:
      mytemplate.render_context(Context(output_file, **args))
  except:
    print(exceptions.text_error_template().render())
    raise
  def render(self, template, output_name=None):
    """
    Render the metadata model using a Mako template as the view.

    The template gets the metadata as an argument, as well as all
    public attributes from the metadata_helpers module.

    The output file is encoded with UTF-8.

    Args:
      template: path to a Mako template file
      output_name: path to the output file, or None to use stdout
    """
    buf = StringIO.StringIO()
    metadata_helpers._context_buf = buf

    helpers = [(i, getattr(metadata_helpers, i))
                for i in dir(metadata_helpers) if not i.startswith('_')]
    helpers = dict(helpers)

    lookup = TemplateLookup(directories=[os.getcwd()])
    tpl = Template(filename=template, lookup=lookup)

    ctx = Context(buf, metadata=self.metadata, **helpers)
    tpl.render_context(ctx)

    tpl_data = buf.getvalue()
    metadata_helpers._context_buf = None
    buf.close()

    if output_name is None:
      print tpl_data
    else:
      file(output_name, "w").write(tpl_data.encode('utf-8'))
Beispiel #5
0
def render_interop_html_report(
  client_langs, server_langs, test_cases, auth_test_cases, http2_cases, 
  resultset, num_failures, cloud_to_prod, http2_interop):
  """Generate HTML report for interop tests."""
  html_report_dir = 'reports'
  template_file = os.path.join(html_report_dir, 'interop_html_report.template')
  try:
    mytemplate = Template(filename=template_file, format_exceptions=True)
  except NameError:
    print 'Mako template is not installed. Skipping HTML report generation.'
    return
  except IOError as e:
    print 'Failed to find the template %s: %s' % (template_file, e)
    return

  sorted_test_cases = sorted(test_cases)
  sorted_auth_test_cases = sorted(auth_test_cases)
  sorted_http2_cases = sorted(http2_cases)
  sorted_client_langs = sorted(client_langs)
  sorted_server_langs = sorted(server_langs)

  args = {'client_langs': sorted_client_langs, 
          'server_langs': sorted_server_langs,
          'test_cases': sorted_test_cases,
          'auth_test_cases': sorted_auth_test_cases,
          'http2_cases': sorted_http2_cases,
          'resultset': resultset,
          'num_failures': num_failures,
          'cloud_to_prod': cloud_to_prod,
          'http2_interop': http2_interop}
  html_file_path = os.path.join(html_report_dir, 'index.html')
  with open(html_file_path, 'w') as output_file:
    mytemplate.render_context(Context(output_file, **args))
Beispiel #6
0
 def to_markdown(self):
     template = Template(filename='pyzeef/markdown_template.md')
     buf = StringIO()
     context_dict = {'page': self}
     context = Context(buf, **context_dict)
     template.render_context(context)
     return buf.getvalue().encode('utf-8')
Beispiel #7
0
 def executeTemplate(self, name):
     """execeute a single template with the data, return the output buffer"""
     tmplType = self.cfg[name].get('type', 'mako')
     if tmplType == 'mako':
         self.logger.debug('GEN | calling mako template')
         tLookup = TemplateLookup(directories=[self.getTemplateFolder()])
         template = Template("""<%%include file="%s"/>""" %
                             self.cfg[name].get('topFile'),
                             lookup=tLookup,
                             strict_undefined=True)
         buf = StringIO()
         ctx = Context(buf,
                       d=self.data,
                       systemCfg=self.controller.systemCfg,
                       generatorCfg=self.cfg,
                       logger=self.logger)
         template.render_context(ctx)
         buf.flush()
         buf.seek(0)
         return buf
     elif tmplType == 'jinja2':
         self.logger.debug('GEN | calling jinja2 template')
         env = Environment(
             loader=FileSystemLoader(self.getTemplateFolder()))
         template = env.get_template(self.cfg[name].get('topFile'))
         ns = {'d': self.data}
         ns['systemCfg'] = self.controller.systemCfg
         ns['generatorCfg'] = self.cfg
         ns['logger'] = self.logger
         tmp = template.render(ns)
         buf = StringIO(tmp)
         return (buf)
     else:
         raise Exception('Unknown template system: ' + tmplType)
Beispiel #8
0
    def make_config(self, cmdfile, paramfile):
        '''Docstring'''

        self.logger.info("\tWriting:%s" % paramfile)
        cmdblank = Template(filename=cmdfile,
                            input_encoding='utf-8',
                            output_encoding='utf-8')
        buf = StringIO()
        stri = 'Context(buf,'

        for key in self.config['wwm']:
            if self.config['wwm'][key] is True:
                ss = "'T'"
            elif self.config['wwm'][key] is False:
                ss = "'F'"
            else:
                ss = self.config['wwm'][key]
                if type(ss) != int and type(ss) != float:
                    ss = '"' + ss + '"'

            stri = stri + key + '=' + str(ss) + ','

        stri = stri[0:-1] + ')'
        ctx = eval(stri.encode('utf-8'))

        try:
            cmdblank.render_context(ctx)
        except:
            self.logger.info(exceptions.text_error_template().render())

        a = open(paramfile, 'w')
        a.write(buf.getvalue())
        a.close()
Beispiel #9
0
class Serializer(object):
    def __init__(self, outputPath, templateName):
        super(Serializer, self).__init__()
        self.outputPath = outputPath
        self.templateName = templateName
        fileutil.writeStringToFile("", self.outputPath)
        tmplResource = datamanager.findResourceByLabel(self.templateName)
        tmplContent = unicode(tmplResource.description())
        self.tmpl = Template(tmplContent)
        self.mapper = util.createDictFromResourceDescription("BibtexOntologyMapper")
        
    def serialize(self, resource):
        buf = StringIO()
        gresource = NepomukResource(resource)
        ctx = Context(buf, resource=gresource, mapper=self.mapper)
        self.tmpl.render_context(ctx)
        fileutil.appendStringToFile(buf.getvalue(), self.outputPath)
    
        
    def queryNextReadySlot(self, query):
        node = query.binding("r");
        resource = Nepomuk.Resource(node.uri())
        self.serialize(resource)
        query.next()
    
    def queryFinishedSlot(self):
        pass
    
    def setQuery(self, query):
        self.query = query
Beispiel #10
0
def lineage_report(template, command, time, today, data, report_stem, lineage,
                   flight_figure, import_report, raw_data_csv):
    mytemplate = Template(filename=template)
    buf = StringIO()

    import_data = parse_import_data(import_report)
    raw_data = parse_raw_data(raw_data_csv)

    ctx = Context(buf,
                  command=command,
                  timestamp=time,
                  date=today,
                  version=__version__,
                  summary_data=data,
                  lineage_data=[lineage],
                  flight_figure=flight_figure,
                  import_report=import_data,
                  raw_data=raw_data)

    try:
        mytemplate.render_context(ctx)
    except:
        traceback = RichTraceback()
        for (filename, lineno, function, line) in traceback.traceback:
            print("File %s, line %s, in %s" % (filename, lineno, function))
            print(line, "\n")
        print("%s: %s" %
              (str(traceback.error.__class__.__name__), traceback.error))

    with open(f"{report_stem}_{lineage}.html", "w") as fw:
        fw.write(buf.getvalue())
Beispiel #11
0
def render_index():
    
    good_cells = get_good_units()

    region_list = {'mld':[], 'ov':[], 'l':[], 'cm':[]}
    #render each unit
    for u in good_cells[0:28]:
        uregs = [a.name for a in u.recsite.areas]
        reg = 'l'
        if 'MLd' in uregs:
            reg = 'mld'
        elif 'CM' in uregs:
            reg = 'cm'
        elif 'OV' in uregs:
            reg = 'ov'
        region_list[reg].append(u)

    main_file = os.path.join(MAKO_DIR, 'index.html')
    output_file = os.path.join(OUTPUT_DIR, 'index.html')
    tpl = Template(filename=main_file)

    #render main index
    f = open(output_file, 'w')
    ctx = Context(f, region_list=region_list)
    tpl.render_context(ctx)
    f.close()
Beispiel #12
0
    def render(self, template, output_name=None):
        """
    Render the metadata model using a Mako template as the view.

    The template gets the metadata as an argument, as well as all
    public attributes from the metadata_helpers module.

    Args:
      template: path to a Mako template file
      output_name: path to the output file, or None to use stdout
    """
        buf = StringIO.StringIO()
        metadata_helpers._context_buf = buf

        helpers = [(i, getattr(metadata_helpers, i))
                   for i in dir(metadata_helpers) if not i.startswith('_')]
        helpers = dict(helpers)

        lookup = TemplateLookup(directories=[os.getcwd()])
        tpl = Template(filename=template, lookup=lookup)

        ctx = Context(buf, metadata=self.metadata, **helpers)
        tpl.render_context(ctx)

        tpl_data = buf.getvalue()
        metadata_helpers._context_buf = None
        buf.close()

        if output_name is None:
            print tpl_data
        else:
            file(output_name, "w").write(tpl_data)
def writeTemplate(tmplFileName,
                  outFileName,
                  namespace={},
                  encodeAsUTF8=True,
                  errorHandler=lambda ctx, msg: False):
    if os.access(outFileName, os.F_OK):
        os.chmod(outFileName, stat.S_IWRITE or stat.S_IREAD)
        os.unlink(outFileName)
    buf = StringIO.StringIO()
    ctx = Context(buf, **namespace)
    print tmplFileName.upper()
    try:
        tobj = Template(text=pkgutil.get_data(
            'kosek', 'config/templates/%s' % tmplFileName),
                        output_encoding='utf-8',
                        format_exceptions=True,
                        error_handler=errorHandler)
        tobj.render_context(ctx)
    except Exception as e:
        print str(e)
        print exceptions.text_error_template().render()
        raise
        #return None
    else:
        outFile = open(outFileName, mode='wt')
        outFile.write(buf.getvalue())
Beispiel #14
0
    def make_config(self, cmdfile,paramfile,module):
        '''Docstring''' 

        self.logger.info("\tWriting:%s" %paramfile)
        cmdblank = Template(filename=cmdfile,input_encoding='utf-8',output_encoding='utf-8')
        buf = StringIO()
        stri='Context(buf,'
        
        for key in self.config[module]:
            stri=stri+key+'='+str(self.config[module][key])+','

        stri=stri[0:-1]+')'
        ctx = eval(stri.encode('utf-8'))
        

        #cmdblank.render_context(ctx)
        try:
            cmdblank.render_context(ctx)
        except:
            self.logger.info(exceptions.text_error_template().render())

	
        a=open(paramfile,'w')
        a.write(buf.getvalue())
        a.close()
Beispiel #15
0
def zwolnienie_edit(request, pk):
    doc = get_object_or_404(Docs, id=pk)
    if request.method == "POST":
        form = DocsForm(request.POST, instance=doc)
        if form.is_valid():
            doc = form.save(commit=False)
            doc.publication_date = timezone.now()
            doc.form_type = 1
            doc.save()

            mytemplate = Template(
                filename='Documents/html&css/zwolnienie.mako')

            buf = StringIO()
            ctx = Context(buf, **request.POST)
            mytemplate.render_context(ctx)
            # '/tmp/'
            response = HttpResponse(content_type='application/pdf')
            response[
                'Content-Disposition'] = 'attachment; filename="zwolnienie indywidualne.pdf"'

            html = HTML(string=buf.getvalue())
            html.write_pdf(response,
                           stylesheets=[CSS('Documents/html&css/style.css')])
            return response
    else:
        form = DocsForm(instance=doc)
    return render(request, 'documents/zwolnienie_edit.html', {'form': form})
Beispiel #16
0
def patron_new(request):
    if request.method == "POST":
        form = DocsForm(request.POST)
        if form.is_valid():
            doc = form.save(commit=False)
            doc.publication_date = timezone.now()
            doc.form_type = 2
            doc.save()

            mytemplate = Template(filename='Documents/html&css/patron.mako')

            buf = StringIO()
            ctx = Context(buf, **request.POST)
            mytemplate.render_context(ctx)

            response = HttpResponse(content_type='application/pdf')
            response[
                'Content-Disposition'] = 'attachment; filename="Podanie o patronat.pdf"'

            html = HTML(string=buf.getvalue())
            html.write_pdf(response,
                           stylesheets=[CSS('Documents/html&css/style.css')])
            return response
    else:
        form = DocsForm()
    return render(request, 'documents/patron_edit.html', {'form': form})
Beispiel #17
0
def render_template(destination, **kwargs):
    """ Renders the Mako template, and writes output file to the specified destination.

    Args:
        destination (Path): Location of the output file.
        **kwargs (dict): Variables to be used in the Mako template.

    Raises:
        ERROR: Error log containing information about the line where the exception occurred.
        Exception: Re-raised Exception coming from Mako template.
    """
    destination.parent.mkdir(parents=True, exist_ok=True)
    with open(str(destination), 'w', newline='\n',
              encoding='utf-8') as rst_file:
        template = Template(filename=str(TEMPLATE_FILE),
                            output_encoding='utf-8',
                            input_encoding='utf-8')
        try:
            template.render_context(Context(rst_file, **kwargs))
        except Exception as exc:
            traceback = RichTraceback()
            logging.error(
                "Exception raised in Mako template, which will be re-raised after logging line info:"
            )
            logging.error("File %s, line %s, in %s: %r",
                          *traceback.traceback[-1])
            raise exc
Beispiel #18
0
def render_perf_html_report(report_dir):
    """Generate a simple HTML report for the perf tests."""
    template_file = 'tools/run_tests/perf_html_report.template'
    try:
        mytemplate = Template(filename=template_file, format_exceptions=True)
    except NameError:
        print(
            'Mako template is not installed. Skipping HTML report generation.')
        return
    except IOError as e:
        print('Failed to find the template %s: %s' % (template_file, e))
        return

    resultset = {}
    for result_file in glob.glob(os.path.join(report_dir, '*.json')):
        with open(result_file, 'r') as f:
            scenario_result = json.loads(f.read())
            test_case = scenario_result['scenario']['name']
            if 'ping_pong' in test_case:
                latency50 = round(scenario_result['summary']['latency50'], 2)
                latency99 = round(scenario_result['summary']['latency99'], 2)
                summary = {'latency50': latency50, 'latency99': latency99}
            else:
                summary = {'qps': round(scenario_result['summary']['qps'], 2)}
            resultset[test_case] = summary

    args = {'resultset': resultset}

    html_file_path = os.path.join(report_dir, 'index.html')
    try:
        with open(html_file_path, 'w') as output_file:
            mytemplate.render_context(Context(output_file, **args))
    except:
        print(exceptions.text_error_template().render())
        raise
Beispiel #19
0
class JavaClassMako(JavaClassFile):
    def __init__(self, project, java_class, tl_file):
        super(JavaClassMako, self).__init__(project, java_class)
        self._template = Template(filename=tl_file, input_encoding='utf-8')
        self._buf = None

    @property
    def class_path(self):
        return self._project.java_src + CONTEXT.separator + self._java_class.package.replace(
            '.', CONTEXT.separator)

    def generator(self):
        self._buf = StringIO()
        ctx = Context(self._buf, java_class=self._java_class)
        self._template.render_context(ctx)
        pass

    def write_file(self):
        if (self._buf is None):
            return
        if not os.path.exists(self.class_path):
            os.makedirs(self.class_path)
        with open(
                self.class_path + CONTEXT.separator +
                self._java_class.file_name, 'w') as f:
            f.write(self._buf.getvalue())
            f.close()
Beispiel #20
0
class Serializer(object):
    def __init__(self, outputPath, templateName):
        super(Serializer, self).__init__()
        self.outputPath = outputPath
        self.templateName = templateName
        fileutil.writeStringToFile("", self.outputPath)
        tmplResource = datamanager.findResourceByLabel(self.templateName)
        tmplContent = unicode(tmplResource.description())
        self.tmpl = Template(tmplContent)
        self.mapper = util.createDictFromResourceDescription(
            "BibtexOntologyMapper")

    def serialize(self, resource):
        buf = StringIO()
        gresource = NepomukResource(resource)
        ctx = Context(buf, resource=gresource, mapper=self.mapper)
        self.tmpl.render_context(ctx)
        fileutil.appendStringToFile(buf.getvalue(), self.outputPath)

    def queryNextReadySlot(self, query):
        node = query.binding("r")
        resource = Nepomuk.Resource(node.uri())
        self.serialize(resource)
        query.next()

    def queryFinishedSlot(self):
        pass

    def setQuery(self, query):
        self.query = query
Beispiel #21
0
 def _makePage(self, template, outfile, **context):
     myTemplate = Template(filename=template, lookup=myLookup)
     buf = StringIO()
     ctx = Context(buf, **context)
     myTemplate.render_context(ctx)
     print buf.getvalue()
     outfile = os.path.join(OUTDIR, outfile)
     open(outfile, 'w').write(buf.getvalue())
Beispiel #22
0
 def render(self, page):
     try:
         mytemplate = Template(page.templatefile, **self.kwargs)
         buf = io.StringIO()
         mytemplate.render_context(Context(buf, **page.context))
         return buf.getvalue()
     except NameError:
         return ''
Beispiel #23
0
 def render(self, page):
     try:
         mytemplate = Template(page.templatefile, **self.kwargs)
         buf = io.StringIO()
         mytemplate.render_context(Context(buf, **page.context))
         return buf.getvalue()
     except NameError:
         return ""
Beispiel #24
0
def run_mako(infile, outfile):
    # pylint: disable=bad-whitespace
    context = dict(coffee=coffee_filter, vers=version_filter)
    lookup = TemplateLookup(directories=['.'], output_encoding='utf-8')
    template = Template(filename=infile, lookup=lookup, input_encoding='utf-8')
    with open(outfile, 'w') as output:
        ctx = Context(output, **context)
        template.render_context(ctx)
def get_file_overlays(templatefile):
    t = Template(filename=templatefile)

    ctx = CaptureContext()

    t.render_context(ctx)

    return ctx.get_all_keys()
Beispiel #26
0
def build_code_for_ev_blk(component, ev_blk, ev_blk_index, build_data):
    func_name = "evaluate_event_block_%d" % (ev_blk_index)  # ${ev_blk_index}
    mytemplate = Template(ev_blk_function)
    buf = StringIO()
    ctx = Context(buf, ev_blk_index=ev_blk_index, ev_blk=ev_blk, component=component, bd=build_data)
    mytemplate.render_context(ctx)
    res = buf.getvalue() + ("\n" * 3)
    return res, func_name
Beispiel #27
0
def render_template(file, ctx, buf):
    mylookup = TemplateLookup(directories=['./'],
                              output_encoding='utf-8',
                              encoding_errors='replace')
    mytemplate = Template(filename='./templates/' + file,
                          module_directory='/tmp/mako_modules',
                          lookup=mylookup)
    mytemplate.render_context(ctx)
    return (buf.getvalue())
Beispiel #28
0
 def generator(self, tables:List):
     # print(type(tables))
     if not isinstance(tables, list) :
         print('sql just support list, get type(%s)' % (type(tables)))
         return
     template = Template(filename = path + '/sql.tl', input_encoding='utf-8')
     self._buf = StringIO()
     ctx = Context(self._buf, tables = tables)
     template.render_context(ctx)
Beispiel #29
0
    def _render(self, template_file, lookup_dirs, properties):
        # build the template and send back the output
        mylookup = TemplateLookup(directories=lookup_dirs)

        t = Template(filename=template_file, lookup=mylookup)
        buf = StringIO()
        ctx = Context(buf, c=properties)
        t.render_context(ctx)
        return buf.getvalue()
Beispiel #30
0
def render(filename):
  code = Code(filename)
  annotations = annotate(code)

  template = Template(filename="templates/annotated.txt")
  buf = StringIO()
  ctx = Context(buf, lines=code.lines, annotations=annotations)
  template.render_context(ctx)
  return buf.getvalue()
Beispiel #31
0
def render_mako_file(template, context):
    if os.path.isfile(template):
        template=file(template).read()
        t=Template(template)
        buf=StringIO()
        ctx=Context(buf, **context)
        t.render_context(ctx)
        return buf.getvalue()
    else:
        return None
Beispiel #32
0
def build_api(methods):
    from loadApi import config
    template_path = config.get('main', 'template')
    programming_language = config.get('default', 'languages')
    tplt = os.path.join(template_path, programming_language, 'api.mako')
    mytemplate = Template(filename=os.path.join(tplt))
    buf = StringIO()
    ctx = Context(buf, methods=methods)
    mytemplate.render_context(ctx)
    return buf.getvalue()
Beispiel #33
0
def doTemplateFromText(tmpl, namespace = {}, leftMargin = 0, rightMargin = 80, formatExceptions = True, encoding = 'utf-8'):
    buf = StringIO()
    ctx = Context(buf, **namespace)
    try:
        tobj = Template(text = tmpl, output_encoding = encoding, format_exceptions = formatExceptions) #, imports ='re'
        tobj.render_context(ctx)
    except:
        print(exceptions.text_error_template().render())
        return None
    return indentText(buf.getvalue(), leftMargin) #, rightMargin)
Beispiel #34
0
def main():
    argparser = argparse.ArgumentParser(
        description='CAN driver auto-generation script.')
    argparser.add_argument('template_file', help='Template file')
    argparser.add_argument('-s',
                           '--spec',
                           dest='xml_file',
                           required=True,
                           help='Filename of the XML bus specification')
    argparser.add_argument('-n',
                           '--node',
                           dest='node_name',
                           help='Name of the node for which to generate code')
    argparser.add_argument('-o',
                           '--out',
                           dest='output',
                           type=argparse.FileType('w'),
                           help='Output file name')
    args = argparser.parse_args()

    xml_tree = ET.parse(args.xml_file)
    root = xml_tree.getroot()
    messages = dict()
    nodes = list()
    for xml_node in root.iter('message'):
        m = Message(xml_node)
        messages[m.name] = m
    for xml_node in root.iter('node'):
        nodes.append(Node(xml_node, messages))

    node = None
    if args.node_name:
        for n in nodes:
            if n.name == args.node_name:
                node = n

    bus_name = root.attrib.get('name').lower()

    if not args.output:
        buf = StringIO()
    else:
        buf = args.output
    ctx = Context(buf,
                  xml_root=root,
                  node=node,
                  bus_name=bus_name,
                  messages=messages)
    try:
        bus_template = Template(filename=args.template_file)
        bus_template.render_context(ctx)
    except:
        print exceptions.text_error_template().render()

    if not args.output:
        print buf.getvalue()
Beispiel #35
0
    def student_view(self, context=None):
        tpl = Template(filename="multichoice/multichoice/static/html/student_view.html")
        buf = StringIO()
        ctx = Context(buf, xblock=self)
        tpl.render_context(ctx)

        frag = Fragment(buf.getvalue())
        frag.add_css(self.resource_string("static/css/student_view.css"))
        frag.add_javascript(self.resource_string("static/js/src/student_view.js"))
        frag.initialize_js('AnswerXBlock')
        return frag
Beispiel #36
0
def doTemplate(tmpl, namespace = {}, leftMargin = 0, rightMargin = 80, formatExceptions = True, encoding = 'utf-8'):
    buf = StringIO()
    ctx = Context(buf, **namespace)
    try:
        tobj = Template(filename = tmpl, output_encoding = encoding,  format_exceptions = formatExceptions) #, imports ='re' # TODO: imports parameter.
        tobj.render_context(ctx)
    except:
        print(exceptions.text_error_template().render())
        return None
    ##return strings.reformat(buf.getvalue(), leftMargin, rightMargin)
    return buf.getvalue()
Beispiel #37
0
def render_template(template: Template, context: Context) -> None:
    """Render the mako template with given context.

    Prints an error template to indicate where and what in the template caused
    the render failure.
    """
    try:
        template.render_context(context)
    except:
        out(exceptions.text_error_template().render())
        raise
Beispiel #38
0
 def _write_prject(self):
     ## 1.create pom
     template = Template(filename=path + '/tl/pom/controller.tl',
                         input_encoding='utf-8')
     buf = StringIO()
     ctx = Context(buf,
                   package_name=CONTEXT.package,
                   module_name=self._module.name)
     template.render_context(ctx)
     with open(self.path + CONTEXT.separator + 'pom.xml', 'w') as f:
         f.write(buf.getvalue())
         f.close()
Beispiel #39
0
def render_mako(template, context, fn=None):
    t = Template(template)
    if fn:
        buf = open(fn, 'wb')
    else:
        buf = StringIO()
    ctx = Context(buf, **context)
    t.render_context(ctx)
    if fn:
        buf.close()
    else:
        return buf.getvalue()
Beispiel #40
0
def test_render():
    if len(sys.argv) < 2:
        print "Missing filename"
        sys.exit(2)

    template = Template(filename=sys.argv[1])
    buf = StringIO()
    ctx = TestContext(buf)
    template.render_context(ctx)
    print buf.getvalue()

    sys.exit(0)
Beispiel #41
0
def test_render():
    if len(sys.argv) < 2:
        print "Missing filename"
        sys.exit(2)

    template = Template(filename=sys.argv[1])
    buf = StringIO()
    ctx = TestContext(buf)
    template.render_context(ctx)
    print buf.getvalue()

    sys.exit(0)
Beispiel #42
0
    def author_view(self, context=None):
        tpl = Template(filename="multichoice/multichoice/static/html/review_stud_quest.html")
        buf = StringIO()
        ctx = Context(buf, xblock=self)
        tpl.render_context(ctx)

        frag = Fragment(buf.getvalue())
        frag.add_css(self.resource_string("static/css/multichoice.css"))
        frag.add_css(self.resource_string("static/css/font-awesome.min.css"))
        frag.add_javascript(self.resource_string("static/js/src/questionnaire_review.js"))
        frag.initialize_js('MultiChoiceXBlock')
        return frag
Beispiel #43
0
def build_code_for_ev_blk(component, ev_blk, ev_blk_index, build_data):
    func_name = "evaluate_event_block_%d" % (ev_blk_index)  #${ev_blk_index}
    mytemplate = Template(ev_blk_function)
    buf = StringIO()
    ctx = Context(buf,
                  ev_blk_index=ev_blk_index,
                  ev_blk=ev_blk,
                  component=component,
                  bd=build_data)
    mytemplate.render_context(ctx)
    res = buf.getvalue() + ('\n' * 3)
    return res, func_name
def main():
    csvfile = open(signals_file, 'r')
    ctrl_sig_reader = csv.DictReader(csvfile)
    fields = ctrl_sig_reader.fieldnames
    ctrl_signals = []
    signal_fields = []
    ctrl_signal_sizes = {}
    # Identify control signals needed
    for field in fields:
        signal_spec = field.split('[')
        sig = signal_spec[0]
        if not sig in ignore_fields:
            signal = sig.lower()
            ctrl_signals.append(signal)
            signal_fields.append(field)
            if len(signal_spec) == 2:
                sig_size = int(signal_spec[1].split(':')[0]) + 1
            else:
                sig_size = 1
            ctrl_signal_sizes[signal] = sig_size

    # Identify control signal values for each op
    ops = []
    for op_data in ctrl_sig_reader:
        op = {}
        for signal, field in zip(ctrl_signals, signal_fields):
            data = op_data[field]
            if data:
                val = data.replace("[", "").replace("]", "")
                val_size = len(val)
                sig_val = '%d\'b%s' % (val_size, val)
            else:
                sig_val = '%d\'d0' % ctrl_signal_sizes[signal]
            op[signal] = sig_val
        op['name'] = op_data['OP']
        op['opcode_hex'] = op_data['OPCODE']
        op['opcode'] = int(op['opcode_hex'], 16)
        ops.append(op)
   
    csvfile.close()

    # Write data to template file
    from mako.template import Template
    from mako.runtime import Context
    control_unit_template = Template(filename=template_file)
    control_unit_file = open(output_file, 'w')
    ctx = Context(control_unit_file, 
                  ctrl_signals=ctrl_signals,
                  ctrl_signal_sizes=ctrl_signal_sizes,
                  ops=ops)
    control_unit_template.render_context(ctx)
    control_unit_file.close()
Beispiel #45
0
 def _get_mako_tmpl_name(self):
     if self.mako_tmpl_name:
         try:
             mytemplate = Template(self.mako_tmpl_name or '')
             buf = StringIO()
             ctx = self._get_mako_context(buf)
             mytemplate.render_context(ctx)
             return buf.getvalue()
         except:
             _logger.error(
                 _("Error while calculating mako product name: %s") %
                 self.display_name)
     return self.display_name
Beispiel #46
0
 def FileGen(self, src, dest):
     try:
         tmpl = Template(u''+self.templates[src], input_encoding='utf-8')
         buf = StringIO()
         model = self.model
         ctx = Context(buf, root = model)
         tmpl.render_context(ctx)
         hf = codecs.open(self.projectpath + '/' + dest, 'w', encoding='utf-8')
         hf.write(buf.getvalue())
         hf.close()
     except Exception as e:
         global message
         message += e.message
Beispiel #47
0
    def student_view(self, context=None):
        tpl = Template(
            filename="multichoice/multichoice/static/html/student_view.html")
        buf = StringIO()
        ctx = Context(buf, xblock=self)
        tpl.render_context(ctx)

        frag = Fragment(buf.getvalue())
        frag.add_css(self.resource_string("static/css/student_view.css"))
        frag.add_javascript(
            self.resource_string("static/js/src/student_view.js"))
        frag.initialize_js('AnswerXBlock')
        return frag
Beispiel #48
0
class MakoTemplate(object):
    """ Wraps a mako template, context, and I/O Buffer. """

    def __init__(self, template, context=None, buf: StringIO=None):
        """ Initializes a template relevant data """
        # Sets template
        self._template = None
        if isinstance(template, str):
            self._template = Template(template)
        elif isinstance(template, Template):
            self._template = Template
        else:
            raise TypeError("Invalid template: expected string or Template")

        # Set internal string buffer
        self._buffer = buf
        if buf is None:
            self._buffer = StringIO()

        # Set context and context variables
        context = context if context is not None else {}
        self._context = Context(self._buffer, **context)

    @property
    def buffer(self) -> str:
        """ Returns contents of string buffer """
        return self._buffer.getvalue()

    def reset_buffer(self):
        """ Refreshes the internal buffer and resets the context """
        self._buffer = StringIO()
        self._context = Context(self._buffer, **self._context.kwargs)

    @property
    def context(self) -> dict:
        """ Returns a copy of the internal context namespace as a dict """
        return self._context.kwargs

    @context.setter
    def context(self, new_context: dict):
        """ Replaces current context with new context and refreshes buffer """
        self._buffer = StringIO()
        self._context = Context(self._buffer, **new_context)

    def render(self):
        """ Renders the template to the internal buffer."""
        try:
            self._template.render_context(self._context)
        except exceptions.MakoException:
            print(exceptions.text_error_template().render())
Beispiel #49
0
def render_interop_html_report(
    client_langs,
    server_langs,
    test_cases,
    auth_test_cases,
    http2_cases,
    resultset,
    num_failures,
    cloud_to_prod,
    http2_interop,
):
    """Generate HTML report for interop tests."""
    template_file = "tools/run_tests/interop_html_report.template"
    try:
        mytemplate = Template(filename=template_file, format_exceptions=True)
    except NameError:
        print "Mako template is not installed. Skipping HTML report generation."
        return
    except IOError as e:
        print "Failed to find the template %s: %s" % (template_file, e)
        return

    sorted_test_cases = sorted(test_cases)
    sorted_auth_test_cases = sorted(auth_test_cases)
    sorted_http2_cases = sorted(http2_cases)
    sorted_client_langs = sorted(client_langs)
    sorted_server_langs = sorted(server_langs)

    args = {
        "client_langs": sorted_client_langs,
        "server_langs": sorted_server_langs,
        "test_cases": sorted_test_cases,
        "auth_test_cases": sorted_auth_test_cases,
        "http2_cases": sorted_http2_cases,
        "resultset": resultset,
        "num_failures": num_failures,
        "cloud_to_prod": cloud_to_prod,
        "http2_interop": http2_interop,
    }

    html_report_out_dir = "reports"
    if not os.path.exists(html_report_out_dir):
        os.mkdir(html_report_out_dir)
    html_file_path = os.path.join(html_report_out_dir, "index.html")
    try:
        with open(html_file_path, "w") as output_file:
            mytemplate.render_context(Context(output_file, **args))
    except:
        print (exceptions.text_error_template().render())
        raise
Beispiel #50
0
 def FileGenByDiagram(self, src, dest, diagram):
     global output_text
     try:
         tmpl = Template(self.templates[src], input_encoding='utf-8')
         buf = StringIO()
         model = diagram
         ctx = Context(buf, root = model)
         tmpl.render_context(ctx)
         #hf = codecs.open(self.projectpath + '/' + dest, 'w', encoding='utf-8')
         #hf.write(buf.getvalue())
         #hf.close()
         output_text += buf.getvalue()
     except Exception as e:
         global message
         message += e.message
    def create_single_pdf(self, cr, uid, ids, data, report_xml, context=None):
        if context is None:
            context = {}
        if report_xml.report_type != 'webkit':
            return super(WebKitParser,self).create_single_pdf(cr, uid, ids, data, report_xml, context=context)

        self.report_xml = report_xml
        self.parser_instance = self.parser(cr, uid, self.name2, context=context)
        self.pool = pooler.get_pool(cr.dbname)

        if not context.get('splitbrowse'):
            objs = self.getObjects(cr, uid, ids, context)
        else:
            objs = []
            self.parser_instance.localcontext['ids'] = ids
            self.parser_instance.localcontext['context'] = context
        self.parser_instance.set_context(objs, data, ids, report_xml.report_type)

        template = False
        if report_xml.report_file:
            path = addons.get_module_resource(report_xml.report_file)
            if path and os.path.exists(path):
                template = file(path).read()

        if self.tmpl:
            f = file_open(self.tmpl)
            template = f.read()
            f.close()

        if not template:
            raise osv.except_osv(_('Error!'), _('Webkit Report template not found !'))

        self.localcontext.update({'lang': context.get('lang')})
        self.parser_instance.localcontext.update({'setLang':self.setLang})
        self.parser_instance.localcontext.update({'formatLang':self.formatLang})


        null, tmpname = tempfile.mkstemp()
        fileout = codecs.open(tmpname, 'wb', 'utf8')
        body_mako_tpl = Template(template, input_encoding='utf-8', default_filters=['unicode'])
        try:
            mako_ctx = Context(fileout, _=self.translate_call, **self.parser_instance.localcontext)
            body_mako_tpl.render_context(mako_ctx)
            fileout.close()
        except Exception, e:
            msg = exceptions.text_error_template().render()
            netsvc.Logger().notifyChannel('Webkit render', netsvc.LOG_ERROR, msg)
            raise osv.except_osv(_('Webkit render'), msg)
Beispiel #52
0
def verify_and_replace_vars(raw_yaml, env_vars):
    missing_keys = set()
    matches = config_keys_re.findall(raw_yaml)

    for key_name in matches:
        key_name = key_name.strip()
        if key_name not in env_vars:
            missing_keys.add(key_name)

    if missing_keys:
        raise MissingEnvironmentKeys(missing_keys)

    buf = StringIO()
    template = Template(raw_yaml)
    context = Context(buf, **env_vars)
    template.render_context(context)
    rendered = buf.getvalue()
    return rendered
Beispiel #53
0
def build_simulation(component):
    print "C++ Simulation"
    print "Component", component

    ev_blks = utils.separate_integration_blocks(component)
    build_data = CPPBuildData(component, ev_blks)

    print ev_blks

    op_blks = ""
    func_names = []
    for i, ev_blk in enumerate(ev_blks):
        blk, func_name = build_code_for_ev_blk(
            component=component, ev_blk=ev_blk, ev_blk_index=i, build_data=build_data
        )
        op_blks = op_blks + blk
        func_names.append(func_name)

    mytemplate = Template(solver_function)
    buf = StringIO()
    ctx = Context(buf, ev_blk_func_names=func_names, component=component)

    mytemplate.render_context(ctx)
    res = buf.getvalue() + ("\n" * 3)

    data_mgr_txt = DataMgrBuilder(ev_blks=ev_blks, cpp_builddata=build_data, component=component).get_text()

    op_file = "out1.c"
    with open(op_file, "w") as fout:
        fout.write(header1)
        fout.write(data_mgr_txt)
        fout.write(header2)
        fout.write(op_blks)
        fout.write(res)

    print "File written to:", op_file
    print

    print
    print
    # mytemplate = Template("hello world!")
    # print mytemplate.render()

    assert False
Beispiel #54
0
def renderTemplate(
    filename=None, text=None, namespace={}, leftMargin=0, rightMargin=80, formatExceptions=True, encoding="utf-8"
):
    if filename is None and text is None:
        raise AttributeError("Neither 'filename' nor 'text' specified.")
    buf = StringIO()
    ctx = Context(buf, **namespace)
    try:
        if filename is not None:
            tobj = Template(
                filename=filename, output_encoding=encoding, format_exceptions=formatExceptions
            )  # , imports ='re' # TODO: imports parameter.
        elif text is not None:
            tobj = Template(text=text, output_encoding=encoding, format_exceptions=formatExceptions)  # , imports ='re'
        tobj.render_context(ctx)
    except:
        print exceptions.text_error_template().render()
        return None
    return strings.reformat(buf.getvalue(), leftMargin, rightMargin)
Beispiel #55
0
def render_models_best(unit, score_values):
    
    upath = os.path.join(OUTPUT_DIR, 'units', unit.recsite.old_id)
    ipath = os.path.join(upath, 'images')
    
    preproc_types = ['rawspectrogram', 'lyons', 'surprise']
    model_types = ['linear', 'sepnl_dists', 'sepnl_spline', 'poisson', 'binomial', 'leglm']
    thresholds = [0.0, 0.25, 0.5, 0.75, 1.0]
    
    all_data = Struct()
    all_data.unit = unit
    all_data.preproc_types = preproc_types
    all_data.model_types = model_types
    all_data.model_types_strfs = ['linear', 'poisson', 'binomial', 'leglm']
    all_data.model_types_nls = model_types
    
    best_models = {}
    for ptype in preproc_types:
        best_models[ptype] = {}
        for mtype in model_types:
            tvals = score_values[ptype][mtype].keys()
            svt = score_values[ptype][mtype].values()
            scores_per_thresh = [s.mean() for s in svt]
            scores_per_thresh = np.array(scores_per_thresh)
            bindx = np.argmax(scores_per_thresh)
            best_thresh = tvals[bindx]
            prefix = '%s_%s_%0.2f'  % (ptype, mtype, best_thresh)
            s = Struct()
            s.strf_prefix = os.path.join(ipath, '%s_strf_mean' % prefix)
            s.nl_prefix = os.path.join(ipath, '%s_nl_mean' % prefix)
            best_models[ptype][mtype] = s

    all_data.img = best_models

    model_template = os.path.join(MAKO_DIR, 'models_best.html')
    fname = 'models_best.html'
    model_file = os.path.join(upath, fname)    
    tpl = Template(filename=model_template)
    f = open(model_file, 'w')
    ctx = Context(f, all_data=all_data)
    tpl.render_context(ctx)
    f.close()
Beispiel #56
0
class PageServlet(Servlet):
    def __init__(self, servletContainer, manifestEntry, sourceChangeCallback):
        Servlet.__init__(self, servletContainer, None if not manifestEntry else manifestEntry.pattern)
        self._servletContainer = servletContainer

        fullServletPath = os.path.abspath(os.path.join(servletContainer.rootDir, manifestEntry.filePath))

        templateLookup = TemplateLookup(directories=['/'],
                       module_directory=self.servletContainer.tempDir
        )

        self._makoTemplate = MakoTemplate(filename=fullServletPath, lookup=templateLookup, module_directory=self.servletContainer.tempDir)

        self._manifestEntry = manifestEntry

        self._sourceChangeCallback = sourceChangeCallback

        self._fileWatcher = FileWatcher(fullServletPath, lambda path: self._sourceChangeCallback(self))
        self._fileWatcher.start()

    def __str__(self):
        return str(self._manifestEntry)

    def unload(self):
        self._fileWatcher.stop()

    @property
    def manifestEntry(self):
        return self._manifestEntry

    @property
    def servletContainer(self):
        return self._servletContainer

    def handleRequest(self, request, response):
        response.sendResponse(CODE_OK)

        response.sendHeader(HDR_CONTENT_TYPE, MIME_HTML)

        self._makoTemplate.render_context(Context(response, request=request, response=response, **self._servletContainer.env))

        return True
Beispiel #57
0
def writeTemplate(tmplFileName, outFileName, namespace = {}, encodeAsUTF8 = True, errorHandler = lambda ctx, msg: False):
    if os.access(outFileName, os.F_OK):
        os.chmod(outFileName, stat.S_IWRITE or stat.S_IREAD)
        os.unlink(outFileName)
    buf = StringIO.StringIO()
    ctx = Context(buf, **namespace)
    print tmplFileName.upper()
    try:
        tobj = Template(text = pkgutil.get_data('kosek', 'config/templates/%s' % tmplFileName),
                            output_encoding = 'utf-8', format_exceptions = False, error_handler = errorHandler
                        )
        tobj.render_context(ctx)
    except Exception as e:
        print str(e)
        print exceptions.text_error_template().render()
        raise
        #return None
    else:
        outFile = open(outFileName, mode='wt')
        outFile.write(buf.getvalue())
Beispiel #58
0
def main():
    show_headers()

    form = cgi.FieldStorage()
    html_output = StringIO() 
    log_files = utils.get_log_files(LOG_DIR)
    limit, top_to_bottom, regex, files_to_search = get_user_args(form, log_files)

    srch_rslt = []
    result_count = 0
    for file_name in files_to_search:
        if result_count < limit:
            # Note we only allow files to be searched if they exist in this dict
            # Otherwise a user could traverse the filesystem and read in /etc/passwd!
            file_path = log_files[file_name]
            for result in utils.grep(regex, file(file_path,'r'), top_to_bottom):
                if result_count < limit:
                    # This assumes a syslog format (Date hostname program : content)
                    res_split = result.split(file_name, 1)
                    #res = [res[0]].extend(res[1].split(":", 1))
                    try:
                        srch_rslt.append((res_split[0], file_name, res_split[1]))
                    except:
                        srch_rslt.append((file_name, result))
                    result_count += 1
                else:
                    break
        else:
            break
        
    ctx = Context(html_output, page_title="FLS",app_name="Funky Log Seer", search_page="index.py", log_results=srch_rslt, file_options=log_files)
    # Try to lookup the template and to render it using our context
    try:
        mylkup = TemplateLookup(directories=['templates/'])
        mytemp = Template(filename='templates/index.mako', lookup=mylkup)
        mytemp.render_context(ctx)
    except:
        print exceptions.text_error_template().render()

    # Print the resulting HTML 
    print html_output.getvalue()