def index(releases, bucket, older_releases=None): with open('site/index.mustache', 'r') as f: template = f.read() released = [ {'name': release.get('name')[1:], 'body': BeautifulSoup(markdown(release.get('body'), extensions=[GithubFlavoredMarkdownExtension()]), 'html.parser').prettify() if release.get('body') else '', 'date': release.get('created_at')[:10]} for release in releases if is_version_uploaded(bucket, get_name(release)) ] if older_releases is not None: released += older_releases renderer = pystache.Renderer(missing_tags='strict') rendered = renderer.render(template, {'releases': released}) bucket.put_object(Key='index.html', Body=rendered, ACL='public-read', ContentType='text/html') site_files = [('site/style.css', 'style.css'), ('site/privacy.html', 'privacy.html')] for source, destination in site_files: with open(source, 'rb') as data: mime_type = mimetypes.guess_type(source)[0] if not mime_type: mime_type = 'application/octet-stream' bucket.put_object(Key=destination, Body=data, ACL='public-read', ContentType=mime_type)
def appendToNotebook(template, info, gene_name): """ saves pymol script to pictures. if run from current folder, this scripts saves pdb id to file. """ renderer = pystache.Renderer() lines = [] (pdbid, reference, ref_selection, pair_chain, pair_selection, sulfur_pairs) = info with open(template, 'r') as k: for i in k.readlines(): s = renderer.render( i, { 'pdbid': pdbid, 'onco_chain': reference, 'peptide_chain': pair_chain, 'onco_resnum': "+".join(map(str, ref_selection)), 'peptide': '+'.join(map(str, pair_selection)), 'pept_cys': '+'.join(map(lambda x: str(x[1]), sulfur_pairs)) }) lines.append(s) if not os.path.exists("notebooks"): os.mkdir("notebooks") image = os.path.join("notebooks", gene_name + ".ipynb") with open(image, 'a') as f: for line in lines: f.write(line) #cmd([" ".join(["pymol -c", "pictures"+reference+"_"+pair_chain+".pml"])]) pass
class StateSearch(): query_renderer = pystache.Renderer() def __init__(self, zip_code=None): self.zip_code = zip_code def zip_code(self): return self.zip_code def query(self): query = json.loads(self.query_renderer.render(self)) results = current_app.elasticsearch.search( index=current_app.config['ADDRESS_INDEX'], body=query) states = [ result["key"] for result in results["aggregations"]["state"]["buckets"] ] states = list(set(state.lower() for state in states)) if len(states) == 0: query = json.loads( self.query_renderer.render_path('all_states.mustache')) results = current_app.elasticsearch.search( index=current_app.config['ADDRESS_INDEX'], body=query) states = [ result["key"] for result in results["aggregations"]["state"]["buckets"] ] states = list(set(state.lower() for state in states)) return {"states": states}
def _render(self, result, output_path): context = ReportModel(result=result, html_output=output_path) template = pkg_resources.resource_string( 'avocado_result_html', 'resources/templates/report.mustache') # pylint: disable=E0611 try: if hasattr(pystache, 'Renderer'): renderer = pystache.Renderer('utf-8', 'utf-8') report_contents = renderer.render(template, context) else: from pystache import view v = view.View(template, context) report_contents = v.render('utf8') except UnicodeDecodeError as details: # FIXME: Remove me when UnicodeDecodeError problem is fixed LOG_UI.critical("\n" + ("-" * 80)) LOG_UI.critical("HTML failed to render the template: %s\n\n", template) LOG_UI.critical("-" * 80) LOG_UI.critical("%s:\n\n", details) LOG_UI.critical("%r", getattr(details, "object", "object not found")) LOG_UI.critical("-" * 80) raise with codecs.open(output_path, 'w', 'utf-8') as report_file: report_file.write(report_contents)
def main(): sys.stdout.buffer.write(b'Content-type: text/html; charset=utf-8\n\n') vc = vlccontroller.VLCController(password=VLCPASS) vc.connect() request = Request(vc=vc) renderer = pystache.Renderer() if request.action == 'toggle_play': vc.pause() return if request.action == 'toggle_subs': vc.set_subtitle_track(-1) return if request.action == 'play': target = os.sep.join( (DIR, urllib.parse.unquote_plus(request.form.getfirst('target')))) vc.clear() vc.add(target) vc.play() return if request.action == 'enqueue': target = os.sep.join( (DIR, urllib.parse.unquote_plus(request.form.getfirst('target')))) vc.enqueue(target) return sys.stdout.buffer.write( renderer.render_name('dadisk.html', request).encode('utf-8')) return
def load_templates(self): self.pages = { 'homepage': get_web_template('homepage'), 'not-implemented-yet': get_web_template('not-implemented-yet'), 'message': get_web_template('message'), 'simulation.full': get_web_template('simulation/full'), 'scenario': get_web_template('simulation/scenario'), 'bankrupt': get_web_template('simulation/results/bankrupt'), 'loss': get_web_template('simulation/results/loss'), 'profit': get_web_template('simulation/results/profit'), 'level': get_web_template('simulation/scenario'), } self.partials = { 'page_start': get_partial_template('page_start'), 'main_header': get_partial_template('main_header'), 'page_end': get_partial_template('page_end'), 'main_menu': get_partial_template('main_menu'), 'panel_content': get_partial_template('panel/content'), 'panel_tabs': get_partial_template('panel/tabs'), 'hidden_field': get_partial_template('fields/hidden'), 'combobox_field': get_partial_template('fields/combobox'), 'text_field': get_partial_template('fields/text'), 'results_summary': get_partial_template('simulation/outputs'), } self.renderer = pystache.Renderer(partials=self.partials)
def produce_web_page(self): import pystache report = self.make_report() simplerenderer = pystache.Renderer(escape=lambda u: u) with open(os.path.join(args.templatedir, "template.tmpl"), "r") as outer: with open(os.path.join(args.templatedir, "test_results.tmpl"), "r") as template: outfilenamebits = [ "report", getpass.getuser(), self.impl_name() ] if args.title: outfilenamebits.append(args.title) outfilenamebits.extend( [time.strftime("%Y-%m-%dT%H%M%SZ", time.gmtime())]) outfilename = "-".join(outfilenamebits) + ".html" with open(os.path.join(args.reportdir, outfilename), "w") as outfile: outfile.write( simplerenderer.render( outer.read(), {"body": pystache.render(template.read(), report) })) if not args.noindex: self.index_reports()
def render_post_page(posts, current_post_index): """Renders a single post page. Arguments: posts - A list of Post objects sorted by published date. current_post_index - The index of the current post in the list of posts. Returns: A string or unicode object containing the rendered page. """ def get_post_dict(index): if 0 <= index < len(posts): return posts[index].to_dict() return None template_params = { "posts": [post.to_dict() for post in posts], "displayed_post": get_post_dict(current_post_index), "html_content": posts[current_post_index].get_html_content(), "next_post": get_post_dict(current_post_index - 1), "previous_post": get_post_dict(current_post_index + 1), "upcoming_post": info.upcoming_post, } renderer = pystache.Renderer(missing_tags="strict") return renderer.render(POST_TEMPLATE, template_params)
def generate_travis_yml(): """Generates content for a .travis.yml file from templates.""" def get_mustache_file(file_name): return pkg_resources.resource_string(__name__, file_name).decode('utf-8') template = get_mustache_file('travis.yml.mustache') before_install_linux = get_mustache_file('before_install_linux.mustache') before_install_osx = get_mustache_file('before_install_osx.mustache') env_osx_with_pyenv = get_mustache_file('env_osx_with_pyenv.mustache') docker_build_image = get_mustache_file('docker_build_image.mustache') docker_run_image = get_mustache_file('docker_run_image.mustache') context = { 'header': HEADER, 'integration_shards': range(0, num_integration_shards), 'integration_shards_length': num_integration_shards, } renderer = pystache.Renderer(partials={ 'before_install_linux': before_install_linux, 'before_install_osx': before_install_osx, 'env_osx_with_pyenv': env_osx_with_pyenv, 'docker_build_image': docker_build_image, 'docker_run_image': docker_run_image }) print(renderer.render(template, context))
def generate_mw_files(num, X, Y, VX, VY): mkdir_p('classic') renderer = pystache.Renderer() cml = renderer.render_path('model.cml.mustache', { 'model_number': num }) f = open('classic/model{}.cml'.format(num), 'w') f.write(cml) f.close() atoms = [{ 'rx': 100*x, 'ry': 100*y, 'vx': 100*vx, 'vy': 100*vy } for (x, y, vx, vy) in zip(X, Y, VX, VY)] mml = renderer.render_path('model$0.mml.mustache', { 'number_of_particles': len(atoms), 'epsilon': epsilon, 'sigma': 100 * sigma, 'mass': mass / 120, 'width': width * 100, 'height': height * 100, 'atoms': atoms }) f = open('classic/model{}$0.mml'.format(num), 'w') f.write(mml) f.close()
def write_section(section_url): print(section_url) module = module_name(section_url) with open(os.path.join(LIB_PATH, '{}.py'.format(module)), 'wb') as fd: renderer = pystache.Renderer(string_encoding='utf-8', escape=lambda u: u) fd.write(renderer.render(ApiClass(section_url)).encode())
def _render_report(self): context = ReportModel(json_input=self.json, html_output=self.output) base_path = os.path.dirname(sys.modules[__name__].__file__) html_resources_path = os.path.join(base_path, 'resources', 'htmlresult') template = os.path.join(html_resources_path, 'templates', 'report.mustache') # pylint: disable=E0611 try: if hasattr(pystache, 'Renderer'): renderer = pystache.Renderer('utf-8', 'utf-8') report_contents = renderer.render( open(template, 'r').read(), context) else: from pystache import view v = view.View(open(template, 'r').read(), context) report_contents = v.render('utf8') # encodes into ascii report_contents = codecs.decode("utf8") # decode to unicode except UnicodeDecodeError as details: # FIXME: Removeme when UnicodeDecodeError problem is fixed import logging ui = logging.getLogger("avocado.app") ui.critical("\n" + ("-" * 80)) ui.critical("HTML failed to render the template: %s\n\n", open(template, 'r').read()) ui.critical("-" * 80) ui.critical("%s:\n\n", details) ui.critical("%r\n\n", self.json) ui.critical("%r", getattr(details, "object", "object not found")) ui.critical("-" * 80) raise static_basedir = os.path.join(html_resources_path, 'static') output_dir = os.path.dirname(os.path.abspath(self.output)) utils_path.init_dir(output_dir) for resource_dir in os.listdir(static_basedir): res_dir = os.path.join(static_basedir, resource_dir) out_dir = os.path.join(output_dir, resource_dir) if os.path.exists(out_dir): shutil.rmtree(out_dir) shutil.copytree(res_dir, out_dir) with codecs.open(self.output, 'w', 'utf-8') as report_file: report_file.write(report_contents) if self.args is not None: if getattr(self.args, 'open_browser', False): # if possible, put browser in separate process group, so # keyboard interrupts don't affect browser as well as Python setsid = getattr(os, 'setsid', None) if not setsid: setsid = getattr(os, 'setpgrp', None) inout = file(os.devnull, "r+") cmd = ['xdg-open', self.output] subprocess.Popen(cmd, close_fds=True, stdin=inout, stdout=inout, stderr=inout, preexec_fn=setsid)
def create_document(self): renderer = pystache.Renderer(file_extension="tex") self.context["course info"]["lecture number"] += 1 json.dump(self.context, open(self.context_path, "w")) return renderer.render(self)
def test_t(self): # print(pystache.render('Hi {{person}}!', {'person': 'Mom'})) # todo # hello = SayHello() # Hello, {{to}}! # print(hello) # renderer = pystache.Renderer() # print(renderer.render(hello)) # todo print(pystache.render('Hi {{person}}!', {'person': 'seveniruby'})) # Hi seveniruby! # todo print("==" * 30) parsed = pystache.parse(u"Hey {{#who}}{{.}}!{{/who}}") # 模版与变量 # print(parsed) renderer = pystache.Renderer() print(renderer.render(parsed, {'who': 'Pops'})) print(renderer.render(parsed, {'who': 'you'})) # 另一套体系 context = {'author': 'Chris Wanstrath', 'maintainer': 'Chris Jerdonek'} print( pystache.render("Author: {{author}}\nMaintainer: {{maintainer}}", context)) print( renderer.render( pystache.parse(u"test: {{#author}}{{.}}!{{/author}}"), {'author': 'maintainer'}))
def write_index(self): # Build letter index index = {} for entry in self.entries: letter = entry.title[0].lower() if letter not in index: index[letter] = { 'letter': letter, 'upper': letter.upper, 'entries': [] } index[letter]['entries'].append(entry) # Sort entries for letter in index: index[letter]['entries'] = sorted( index[letter]['entries'], key=lambda entry: entry.title.lower()) index_data = [index[k] for k in sorted(index.keys())] # Render renderer = pystache.Renderer() output = renderer.render_path( path.join(path.dirname(path.abspath(__file__)), 'index.mustache'), { 'index': index_data, 'lastUpdate': datetime.date.today().isoformat() }) with open('index.html', "w", encoding="utf8") as text_file: text_file.write(output)
def __init__(self, args: argparse.Namespace, version: str, help_info: Dict) -> None: self._args = args self._version = version def get_tpl(name: str) -> str: # Note that loading relative to __name__ may not always work when __name__=='__main__'. buf = pkgutil.get_data("generate_docs", f"docs_templates/{name}") if buf is None: raise ValueError(f"No such template: {name}") return buf.decode() options_scope_tpl = get_tpl("options_scope_reference.md.mustache") single_option_tpl = get_tpl("single_option_reference.md.mustache") target_tpl = get_tpl("target_reference.md.mustache") self._renderer = pystache.Renderer( partials={ "scoped_options": options_scope_tpl, "single_option": single_option_tpl, "target": target_tpl, } ) self._category_id: Optional[str] = None # Fetched lazily. # Load the data. self._options_info = self.process_options_input(help_info, sync=self._args.sync) self._targets_info = self.process_targets_input(help_info)
def __init__(self, corpus_file='', model_pattern='', topic_range=None, context_type='', label_module=None, config_file='', fulltext=False, corpus_path='', **kwargs): super(Application, self).__init__() self.config_file = config_file # setup routes self.renderer = pystache.Renderer(escape=lambda u: u, string_encoding='utf8') self.icons = kwargs.get('icons', 'link') if fulltext: self._serve_fulltext(corpus_path) self._setup_routes(**kwargs) # load corpus self.context_type = context_type self.label_name = self.context_type + '_label' self._load_label_module(label_module, config_file) self._load_corpus(corpus_file) # load viewers self.v = dict() self.topic_range = topic_range self.colors = dict() self._load_viewers(model_pattern)
def prepare(doc): """ Parse metadata to obtain list of mustache templates, then load those templates. """ doc.mustache_files = doc.get_metadata('mustache') if isinstance(doc.mustache_files, basestring): # process single YAML value stored as string if not doc.mustache_files: doc.mustache_files = None # switch empty string back to None else: doc.mustache_files = [doc.mustache_files ] # put non-empty string in list # with open('debug.txt', 'a') as the_file: # the_file.write(str(doc.mustache_files)) # the_file.write('\n') if doc.mustache_files is not None: doc.mustache_hashes = [ yaml.load(open(file, 'r').read(), Loader=yaml.SafeLoader) for file in doc.mustache_files ] doc.mhash = { k: v for mdict in doc.mustache_hashes for k, v in mdict.items() } # combine list of dicts into a single dict else: doc.mhash = {} if len(doc.metadata.content) > 0: # Local variables in markdown file wins over any contained in mustache_files doc.mhash.update( {k: doc.get_metadata(k) for k in doc.metadata.content}) doc.mrenderer = pystache.Renderer(escape=lambda u: u, missing_tags='strict') else: doc.mhash = None
def test_create_shift(self): data = {"timeZone": "China Standard Time", "shiftName": "shift 22"} data2 = pystache.Renderer().render_name('shift', data) print(data2) r = requests.post(self.shift_url, auth=self.auth, data=data2) print(r.json()) assert r.status_code == 201
def render_html_into_template(source_directory, tmplData): result = [] if (tmplData['meta']['publish']): renderer = pystache.Renderer() html_html = renderer.render_path(source_directory + os.sep + tmplData['meta']['template'], tmplData) html_path = tmplData['meta']['directory']['html'] + os.sep + tmplData['content']['slugs']['html'] html_file = codecs.open(html_path, 'w', encoding="utf-8") html_file.write(html_html) html_file.close() result.extend([html_path]) json_json = json.dumps(tmplData) json_path = tmplData['meta']['directory']['html'] + os.sep + tmplData['content']['slugs']['json'] json_file = codecs.open(json_path, 'w', encoding="utf-8") json_file.write(json_json) json_file.close() result.extend([json_path]) return result
def index_reports(self): import pystache import urllib # Get a list of all non-index html files in the reportdir filenames = filter( lambda x: x != "index.html", filter(lambda x: x.endswith(".html"), os.listdir(args.reportdir))) filenames.sort() filenames = map( lambda x: { "linkname": os.path.basename(x), "filename": urllib.quote(os.path.basename(x)) }, filenames) simplerenderer = pystache.Renderer(escape=lambda u: u) with open(os.path.join(args.templatedir, "template.tmpl"), "r") as outer: with open(os.path.join(args.templatedir, "index.tmpl"), "r") as template: with open(os.path.join(args.reportdir, "index.html"), "w") as outfile: outfile.write( simplerenderer.render( outer.read(), { "body": pystache.render(template.read(), {"testlist": filenames}) }))
def body(self, environ, file_like): """Pass environ and **self.variables into the template.""" return [ pystache.Renderer().render(file_like.read(), environ=environ, **self.variables).encode('utf-8') ]
def __init__(self, srcdir, javadir, package, xmldir, exceptions): self.srcdir = srcdir self.javadir = javadir self.package = package self.exceptions = exceptions project = CApi.Project() project.initFromDir(xmldir) project.check() self.parser = AbsApi.CParser(project) self.parser.functionBl = [ 'linphone_factory_create_core_with_config', 'linphone_factory_create_core', 'linphone_factory_create_core_2', 'linphone_factory_create_core_with_config_2', 'linphone_vcard_get_belcard', 'linphone_core_get_current_vtable', 'linphone_factory_get', 'linphone_factory_clean', 'linphone_call_zoom_video', 'linphone_core_get_zrtp_cache_db', 'linphone_config_get_range' ] self.parser.parse_all() self.translator = JavaTranslator(package, exceptions) self.renderer = pystache.Renderer() self.jni = Jni(package) self.proguard = Proguard(package) self.enums = {} self.interfaces = {} self.classes = {}
def main(argv): parser = OptionParser(usage="Usage %prog [resources.json] [destdir]") (options, args) = parser.parse_args(argv) if len(args) != 3: parser.error("Wrong number of arguments") source = args[1] dest_dir = args[2] renderer = pystache.Renderer(search_dirs=[TOPDIR], missing_tags='strict') processor = AsteriskProcessor(wiki_prefix=WIKI_PREFIX) # Build the models base_dir = os.path.dirname(source) resources = ResourceListing().load_file(source, processor) for api in resources.apis: api.load_api_declaration(base_dir, processor) # Render the templates for api in resources.apis: for transform in API_TRANSFORMS: transform.render(renderer, api, dest_dir) for transform in RESOURCES_TRANSFORMS: transform.render(renderer, resources, dest_dir)
def main(): args = get_args() mustache_renderer = pystache.Renderer() # Grab current directory since our mustache template is relative to us current_file_dir = os.path.dirname(os.path.realpath(__file__)) mustache_parsed_category = create_mustache_category( os.path.join(current_file_dir, u'category.graphml.mustache')) categories = get_category_dirs(args.directory_in) print(u'Importing {} categories...'.format(len(categories))) for category in categories: svg_files = get_svg_files(category) category_name = os.path.basename(category) if len(svg_files) == 0: print(u'No icons found in "{}"!'.format(category_name)) continue mustache_vars = generate_mustache_args(svg_files) category_filename = 'AWS - {}.graphml'.format(category_name) category_file = os.path.join(args.directory_out, category_filename) with io.open(category_file, 'w', encoding='utf-8') as f: rendered = mustache_renderer.render(mustache_parsed_category, mustache_vars) f.write(rendered) print(u'Imported "{}" ({} icons)'.format(category_name, len(svg_files)))
def load_eqn_template(problem_data, template_file, renderer = pystache.Renderer(escape=lambda u: u)): """Loads pystache template and uses it to generate code. Parameters ---------- problem_data - dict Workspace defining variables for template template_file - str Path to template file to be used renderer Renderer used to convert template file to code Returns ------- Code generated from template """ template_path = beluga.root()+'/optimlib/templates/'+problem_data['method']+'/qcpi/'+template_file with open(template_path) as f: tmpl = f.read() # Render the template using the data code = renderer.render(tmpl, problem_data) return code
class CitySearch(): query_renderer = pystache.Renderer() def __init__(self, zip_code, state): self.zip_code = zip_code self.state = state def state(self): return self.state def zip_code(self): return self.zip_code def query(self): query = json.loads(self.query_renderer.render(self)) results = current_app.elasticsearch.search( index=current_app.config['ADDRESS_INDEX'], body=query) cities = [ result["key"] for result in results["aggregations"]["city"]["buckets"] ] if len(cities) == 0: query = json.loads( self.query_renderer.render_path('cities_for_state.mustache', self)) results = current_app.elasticsearch.search( index=current_app.config['ADDRESS_INDEX'], body=query) cities = [ result["key"] for result in results["aggregations"]["city"]["buckets"] ] return {"cities": list(set(city.lower() for city in cities))}
def template(template_file, variables={}): variables.update(colors) f = open(dscan.PWD + 'common/template/' + template_file, 'r') template = f.read() renderer = pystache.Renderer(search_dirs=dscan.PWD) return renderer.render(template, variables)
class AddressSearch(): query_renderer = pystache.Renderer() def __init__(self, zip_code, state, city, address): self.zip_code = zip_code self.state = state self.city = city self.address = address def address(self): return self.address def city(self): return self.city def state(self): return self.state def zip_code(self): return self.zip_code def query(self): query = json.loads(self.query_renderer.render(self)) results = current_app.elasticsearch.search( index=current_app.config['ADDRESS_INDEX'], body=query) addresses = [ result["_source"]["address"] for result in results["hits"]["hits"] ] return { "addresses": list(set(address.lower() for address in addresses))[:10] }
def find(): env = { 'base_url': '/'.join(request.base_url.split('/')[:-1]), 'id_url': request.base_url.strip('()'), 'title': request.base_url.strip('()').split('/')[-1], 'updated': datetime.utcnow().isoformat(), 'entries': [] } if 'id' in request.args: name = request.args['id'].strip('\'') pkgs = Package.query.filter_by(name=name).all() # TODO: use .one() elif 'searchTerm' in request.args: name = request.args['searchTerm'].strip('\'') if name: pkgs = Package.query.filter(Package.name.like('%' + name + '%')).all() else: pkgs = Package.query.all() if pkgs and len(pkgs) > 0: env['entries'] = [] for pkg in pkgs: vers = pkg.versions if request.args.get('includePrerelease', 'false') == 'false': vers = vers.filter(Version.is_prerelease is not True) env['entries'].extend([ver.to_json() for ver in vers.all()]) renderer = pystache.Renderer() xml = renderer.render_path('feed.mustache', env) return Response(xml, mimetype='application/atom+xml')