Ejemplo n.º 1
0
def render_dummy_page(data=None):
    template = Template(filename='templates/dummy.html',
                        module_directory='templates/modules/')
    return template.render_unicode(data=data)
Ejemplo n.º 2
0
def gs_gpu(idata, itera=100):
    """Gerchberg-Saxton algorithm to calculate DOEs using the GPU
    
    Calculates the phase distribution in a object plane to obtain an 
    specific amplitude distribution in the target plane. It uses a 
    FFT to calculate the field propagation.
    The wavefront at the DOE plane is assumed as a plane wave.
    
    **ARGUMENTS:**
	
		========== ======================================================
		idata      numpy array containing the target amplitude distribution 
        itera      Maximum number of iterations
		========== ======================================================
    """

    pl = cl.get_platforms()[0]
    devices = pl.get_devices(device_type=cl.device_type.GPU)
    ctx = cl.Context(devices=[devices[0]])
    queue = cl.CommandQueue(ctx)

    plan = Plan(idata.shape, queue=queue,
                dtype=complex128)  #no funciona con "complex128"

    src = str(
        Template(KERNEL).render(
            double_support=all(has_double_support(dev) for dev in devices),
            amd_double_support=all(
                has_amd_double_support(dev) for dev in devices)))
    prg = cl.Program(ctx, src).build()

    idata_gpu = cl_array.to_device(queue,
                                   ifftshift(idata).astype("complex128"))
    fdata_gpu = cl_array.empty_like(idata_gpu)
    rdata_gpu = cl_array.empty_like(idata_gpu)
    plan.execute(idata_gpu.data, fdata_gpu.data)

    e = 1000
    ea = 1000
    for i in range(itera):
        prg.norm(queue, fdata_gpu.shape, None, fdata_gpu.data)
        plan.execute(fdata_gpu.data, rdata_gpu.data, inverse=True)
        tr = rdata_gpu.get()
        rdata = ifftshift(tr)

        #TODO: This calculation should be done in the GPU
        e = (abs(rdata) - idata).std()
        if e > ea:
            break
        ea = e

        prg.norm2(queue, rdata_gpu.shape, None, rdata_gpu.data, idata_gpu.data)

        plan.execute(rdata_gpu.data, fdata_gpu.data)

    fdata = fdata_gpu.get()

    #~ prg.norm(queue, fdata_gpu.shape, None,fdata_gpu.data)
    fdata = ifftshift(fdata)
    fdata = exp(1.j * angle(fdata))

    #~ fdata=fdata_gpu.get()
    return fdata
Ejemplo n.º 3
0
    def testnonexpression(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(object):
                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"
Ejemplo n.º 4
0
 def _compile_from_file(self, path, filename):
     self.path = path
     return Template("foo bar").module
Ejemplo n.º 5
0
 def test_future_import(self):
     t = Template("${ x / y }", future_imports=["division"])
     assert result_lines(t.render(x=12, y=5)) == ["2.4"]
TEMPLATE_C = Template(COPYRIGHT + """
/* This file generated from ${filename}, don't edit directly. */

#define VK_PROTOTYPES
#include <vulkan/vulkan.h>

#include "lvp_private.h"
#include "pipe/p_context.h"
#include "vk_util.h"

% for c in commands:
% if c.name in manual_commands:
<% continue %>
% endif
% if c.guard is not None:
#ifdef ${c.guard}
% endif
VKAPI_ATTR ${c.return_type} VKAPI_CALL lvp_${c.name} (VkCommandBuffer commandBuffer
% for p in c.params[1:]:
, ${p.decl}
% endfor
)
{
   LVP_FROM_HANDLE(lvp_cmd_buffer, cmd_buffer, commandBuffer);

   vk_enqueue_${to_underscore(c.name)}(&cmd_buffer->queue
% for p in c.params[1:]:
, ${p.name}
% endfor
   );

% if c.return_type == 'VkResult':
   return VK_SUCCESS;
% endif
}
% if c.guard is not None:
#endif // ${c.guard}
% endif
% endfor

""",
                      output_encoding='utf-8')
Ejemplo n.º 7
0
 def create_configuration_to_string():
     template_path = resource_filename('nikola', 'conf.py.in')
     conf_template = Template(filename=template_path)
     return conf_template.render(**prepare_config(SAMPLE_CONF))
Ejemplo n.º 8
0
    def run(self, snapshot, recursive=False):
        dataset = snapshot.get('dataset') or snapshot.get('id').split('@')[0]
        id = snapshot.get('id') or '{0}@{1}'.format(dataset,
                                                    snapshot.get('name'))
        vm_snapname = self.environment.get('vmware_snapshot_name')
        failed_snapshots = self.environment.get('vmware_failed_snapshots', [])

        if not vm_snapname:
            return

        logger.info('VM snapshot name is: {0}'.format(vm_snapname))

        for mapping in self.datastore.query_stream('vmware.datasets'):
            if recursive:
                if not re.search('^{0}(/|$)'.format(mapping['dataset']), dataset) and \
                   not re.search('^{0}(/|$)'.format(dataset), mapping['dataset']):
                    continue
            else:
                if mapping['dataset'] != dataset:
                    continue

            peer = self.dispatcher.call_sync('peer.query',
                                             [('id', '=', mapping['peer'])],
                                             {'single': True})
            if not peer:
                failed_snapshots.append({
                    'when':
                    'connect',
                    'host':
                    '<mapping {0}>'.format(mapping['name']),
                    'datastore':
                    mapping['datastore'],
                    'error':
                    'Cannot find peer entry for mapping {0}'.format(
                        mapping['name'])
                })
                continue

            if any(
                    i.get('host') == q.get(peer, 'credentials.address')
                    for i in failed_snapshots):
                continue

            try:
                ssl_context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
                ssl_context.verify_mode = ssl.CERT_NONE
                si = connect.SmartConnect(host=q.get(peer,
                                                     'credentials.address'),
                                          user=q.get(peer,
                                                     'credentials.username'),
                                          pwd=q.get(peer,
                                                    'credentials.password'),
                                          sslContext=ssl_context)
                content = si.RetrieveContent()
                vm_view = content.viewManager.CreateContainerView(
                    content.rootFolder, [vim.VirtualMachine], True)
            except BaseException as err:
                logger.warning(
                    'Connecting to VMware instance at {0} failed: {1}'.format(
                        q.get(peer, 'credentials.address'), str(err)))

                failed_snapshots.append({
                    'when':
                    'connect',
                    'host':
                    q.get(peer, 'credentials.address'),
                    'datastore':
                    mapping['datastore'],
                    'error':
                    getattr(err, 'msg', str(err))
                })

                continue

            for vm in vm_view.view:
                if not any(i.info.name == mapping['datastore']
                           for i in vm.datastore):
                    continue

                if not vm.snapshot:
                    continue

                snapshot = find_snapshot(vm.snapshot.rootSnapshotList,
                                         vm_snapname)
                if not snapshot:
                    continue

                logger.info(
                    'Removing snapshot of VM {0} (datastore {1})'.format(
                        vm.summary.config.name, mapping['datastore']))

                try:
                    task.WaitForTask(snapshot.RemoveSnapshot_Task(True))
                except vmodl.MethodFault as err:
                    logger.warning(
                        'Deleting snapshot of {0} failed: {1}'.format(
                            vm.summary.config.name, err.msg))
                    failed_snapshots.append({
                        'when': 'delete',
                        'vm': vm.summary.config.name,
                        'datastore': mapping['datastore'],
                        'error': err.msg
                    })

            connect.Disconnect(si)

        if failed_snapshots:
            descr = Template(ALERT_TEMPLATE).render(
                id=id, failed_snapshots=failed_snapshots)
            self.dispatcher.call_sync(
                'alert.emit', {
                    'class': 'VMwareSnapshotFailed',
                    'target': dataset,
                    'title':
                    'Failed to create or remove snapshot of one or more VMware virtual machines',
                    'description': descr
                })
Ejemplo n.º 9
0
def main(argv):
    got_input = False
    module_directory = None
    dictionary = {}
    json_dict = {}
    got_output = False
    output_file = sys.stdout
    plugins = []
    output_name = None

    try:
        opts, args = getopt.getopt(argv, 'hm:d:o:p:')
    except getopt.GetoptError:
        out('Unknown option')
        showhelp()
        sys.exit(2)

    for opt, arg in opts:
        if opt == '-h':
            out('Displaying showhelp')
            showhelp()
            sys.exit()
        elif opt == '-o':
            if got_output:
                out('Got more than one output')
                showhelp()
                sys.exit(3)
            got_output = True
            output_name = arg
        elif opt == '-m':
            if module_directory is not None:
                out('Got more than one cache directory')
                showhelp()
                sys.exit(4)
            module_directory = arg
        elif opt == '-d':
            dict_file = open(arg, 'r')
            bunch.merge_json(json_dict, yaml.load(dict_file.read()))
            dict_file.close()
        elif opt == '-p':
            plugins.append(import_plugin(arg))

    for plugin in plugins:
        plugin.mako_plugin(json_dict)

    for k, v in json_dict.items():
        dictionary[k] = bunch.to_bunch(v)

    cleared_dir = False
    for arg in args:
        got_input = True
        with open(arg) as f:
            srcs = list(yaml.load_all(f.read()))
        for src in srcs:
            if isinstance(src, basestring):
                assert len(srcs) == 1
                template = Template(src,
                                    filename=arg,
                                    module_directory=module_directory,
                                    lookup=TemplateLookup(directories=['.']))
                with open(output_name, 'w') as output_file:
                    template.render_context(Context(output_file, **dictionary))
            else:
                # we have optional control data: this template represents
                # a directory
                if not cleared_dir:
                    if not os.path.exists(output_name):
                        pass
                    elif os.path.isfile(output_name):
                        os.unlink(output_name)
                    else:
                        shutil.rmtree(output_name, ignore_errors=True)
                    cleared_dir = True
                items = []
                if 'foreach' in src:
                    for el in dictionary[src['foreach']]:
                        if 'cond' in src:
                            args = dict(dictionary)
                            args['selected'] = el
                            if not eval(src['cond'], {}, args):
                                continue
                        items.append(el)
                    assert items
                else:
                    items = [None]
                for item in items:
                    args = dict(dictionary)
                    args['selected'] = item
                    item_output_name = os.path.join(
                        output_name,
                        Template(src['output_name']).render(**args))
                    if not os.path.exists(os.path.dirname(item_output_name)):
                        os.makedirs(os.path.dirname(item_output_name))
                    template = Template(
                        src['template'],
                        filename=arg,
                        module_directory=module_directory,
                        lookup=TemplateLookup(directories=['.']))
                    with open(item_output_name, 'w') as output_file:
                        template.render_context(Context(output_file, **args))

    if not got_input:
        out('Got nothing to do')
        showhelp()

    output_file.close()
Ejemplo n.º 10
0
]
modules.sort()
for module in modules:
    __import__(module)
classes = {}
for module in modules:
    classes[module] = []
    for name, obj in inspect.getmembers(sys.modules[module]):
        if inspect.isclass(obj) and obj.__module__ == module:
            classes[module].append(name)
module_file_names = []
for module_name, classes in six.iteritems(classes):
    file_name = module_name.replace('.', '_').lower()
    module_file_names.append(file_name)
    with open('standard/models/{name}.rst'.format(name=file_name), 'w') as sources:
        template = Template(filename='standard/models/models.rst.mako')
        sources.write(template.render(**{'module_name': module_name, 'classes': classes}))
with open('standard/models/index.rst', 'w') as sources:
    template = Template(filename='standard/models/index.rst.mako')
    sources.write(template.render(**{'module_file_names': module_file_names}))

# Add any paths that contain templates here, relative to this directory.
templates_path = ['doc/_buildtemplates']

# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
#
# source_suffix = ['.rst', '.md']
source_suffix = '.rst'

# The master toctree document.
Ejemplo n.º 11
0
      return insert(instr);
   }

    % if name == 'sop1' or name == 'sop2' or name == 'sopc':
        <%
        args[0] = 'WaveSpecificOpcode opcode'
        params = []
        for i in range(num_definitions):
            params.append('def%d' % i)
        for i in range(num_operands):
            params.append('op%d' % i)
        %>\\

   inline Result ${name}(${', '.join(args)})
   {
       return ${name}(w64or32(opcode), ${', '.join(params)});
   }

    % endif
    % endfor
% endfor
};

}
#endif /* _ACO_BUILDER_ */"""

from aco_opcodes import opcodes, Format
from mako.template import Template

print(Template(template).render(opcodes=opcodes, Format=Format))
    _filterL = filter(lambda e,_path=_path: os.path.commonprefix([_path, e])==e, filter_list)
    filtered = bool(list(_filterL))
    if filtered:
        print('filtered %r' % path)
    return filtered

if __name__=='__main__':
    resultL = []
    filterL = filter_list()
    print("generated Filterlist: \n%r" % filterL)

    for base_path in config['base_pathL']:
        log.debug('Find dirvish vaults in path %r', base_path)
        for dirname, dirnames, _ in os.walk(base_path):
            for possible_vault in dirnames:
                possible_vault_dir = os.path.join(base_path, possible_vault)
                if is_blacklisted(possible_vault_dir, filterL): 
                    continue
                print("Check directory in %r/%r" %(base_path, possible_vault))
                backupDir = backup_dir(base_path, possible_vault)
                if backupDir:
                    resultL.append(os.path.join(backupDir))
            dirnames.clear()
    with open('/etc/ptx_backup/dirvish.vault.script.sh', 'w') as file:
        try:
            template = Template(filename=config['templateFile'])
            file.write(template.render(dirL=resultL, config=config))
        except:
            print(exceptions.text_error_template().render())
            raise
Ejemplo n.º 13
0
    def _connections(self):
        fg = self._flow_graph
        templates = {
            key: Template(text)
            for key, text in fg.parent_platform.connection_templates.items()
        }

        def make_port_sig(port):
            # TODO: make sense of this
            if port.parent.key in ('pad_source', 'pad_sink'):
                block = 'self'
                key = fg.get_pad_port_global_key(port)
            else:
                block = 'self.' + port.parent_block.name
                key = port.key

            if not key.isdigit():
                key = repr(key)

            return '({block}, {key})'.format(block=block, key=key)

        connections = fg.get_enabled_connections()

        # Get the virtual blocks and resolve their connections
        connection_factory = fg.parent_platform.Connection
        virtual_source_connections = [
            c for c in connections
            if isinstance(c.source_block, blocks.VirtualSource)
        ]
        for connection in virtual_source_connections:
            sink = connection.sink_port
            for source in connection.source_port.resolve_virtual_source():
                resolved = connection_factory(fg.orignal_flowgraph, source,
                                              sink)
                connections.append(resolved)

        virtual_connections = [
            c for c in connections
            if (isinstance(c.source_block, blocks.VirtualSource)
                or isinstance(c.sink_block, blocks.VirtualSink))
        ]
        for connection in virtual_connections:
            # Remove the virtual connection
            connections.remove(connection)

        # Bypassing blocks: Need to find all the enabled connections for the block using
        # the *connections* object rather than get_connections(). Create new connections
        # that bypass the selected block and remove the existing ones. This allows adjacent
        # bypassed blocks to see the newly created connections to downstream blocks,
        # allowing them to correctly construct bypass connections.
        bypassed_blocks = fg.get_bypassed_blocks()
        for block in bypassed_blocks:
            # Get the upstream connection (off of the sink ports)
            # Use *connections* not get_connections()
            source_connection = [
                c for c in connections if c.sink_port == block.sinks[0]
            ]
            # The source connection should never have more than one element.
            assert (len(source_connection) == 1)

            # Get the source of the connection.
            source_port = source_connection[0].source_port

            # Loop through all the downstream connections
            for sink in (c for c in connections
                         if c.source_port == block.sources[0]):
                if not sink.enabled:
                    # Ignore disabled connections
                    continue
                connection = connection_factory(fg.orignal_flowgraph,
                                                source_port, sink.sink_port)
                connections.append(connection)
                # Remove this sink connection
                connections.remove(sink)
            # Remove the source connection
            connections.remove(source_connection[0])

        # List of connections where each endpoint is enabled (sorted by domains, block names)
        def by_domain_and_blocks(c):
            return c.type, c.source_block.name, c.sink_block.name

        rendered = []
        for con in sorted(connections, key=by_domain_and_blocks):
            template = templates[con.type]
            code = template.render(make_port_sig=make_port_sig,
                                   source=con.source_port,
                                   sink=con.sink_port)
            rendered.append(code)

        return rendered
Ejemplo n.º 14
0
import tempfile
import textwrap
import time

from mako.template import Template

from .. import Messages, blocks
from ..Constants import TOP_BLOCK_FILE_MODE
from .FlowGraphProxy import FlowGraphProxy
from ..utils import expr_utils

DATA_DIR = os.path.dirname(__file__)

PYTHON_TEMPLATE = os.path.join(DATA_DIR, 'flow_graph.py.mako')

python_template = Template(filename=PYTHON_TEMPLATE)


class TopBlockGenerator(object):
    def __init__(self, flow_graph, file_path):
        """
        Initialize the top block generator object.

        Args:
            flow_graph: the flow graph object
            file_path: the path to write the file to
        """

        self._flow_graph = FlowGraphProxy(flow_graph)
        self._generate_options = self._flow_graph.get_option(
            'generate_options')
Ejemplo n.º 15
0
C_TEMPLATE = Template(textwrap.dedent(u"""\
    /* Autogenerated file -- do not edit
     * generated by ${file}
     *
     ${copyright}
     */

    #include <string.h>
    #include <vulkan/vulkan.h>
    #include <vulkan/vk_android_native_buffer.h>
    #include <vulkan/vk_layer.h>
    #include "util/macros.h"
    #include "vk_enum_to_str.h"

    % for enum in enums:

      % if enum.guard:
#ifdef ${enum.guard}
      % endif
    const char *
    vk_${enum.name[2:]}_to_str(${enum.name} input)
    {
        switch(input) {
    % for v in sorted(enum.values.keys()):
        case ${v}:
            return "${enum.values[v]}";
    % endfor
        default:
            unreachable("Undefined enum value.");
        }
    }

      % if enum.guard:
#endif
      % endif
    %endfor

    size_t vk_structure_type_size(const struct VkBaseInStructure *item)
    {
        switch((int)item->sType) {
    % for struct in structs:
        % if struct.extension is not None and struct.extension.define is not None:
    #ifdef ${struct.extension.define}
        case ${struct.stype}: return sizeof(${struct.name});
    #endif
        % else:
        case ${struct.stype}: return sizeof(${struct.name});
        % endif
    %endfor
        case VK_STRUCTURE_TYPE_LOADER_INSTANCE_CREATE_INFO: return sizeof(VkLayerInstanceCreateInfo);
        case VK_STRUCTURE_TYPE_LOADER_DEVICE_CREATE_INFO: return sizeof(VkLayerDeviceCreateInfo);
        default:
            unreachable("Undefined struct type.");
        }
    }

    void vk_load_instance_commands(VkInstance instance,
                                   PFN_vkGetInstanceProcAddr gpa,
                                   struct vk_instance_dispatch_table *table)
    {
        memset(table, 0, sizeof(*table));
        table->GetInstanceProcAddr = gpa;
    % for cmd in commands:
        % if not cmd.device_entrypoint and cmd.name != 'vkGetInstanceProcAddr':
            % if cmd.extension is not None and cmd.extension.define is not None:
    #ifdef ${cmd.extension.define}
        table->${cmd.name[2:]} = (PFN_${cmd.name}) gpa(instance, "${cmd.name}");
    #endif
            % else:
        table->${cmd.name[2:]} = (PFN_${cmd.name}) gpa(instance, "${cmd.name}");
            % endif
        % endif
    %endfor
    }

    void vk_load_device_commands(VkDevice device,
                                 PFN_vkGetDeviceProcAddr gpa,
                                 struct vk_device_dispatch_table *table)
    {
        memset(table, 0, sizeof(*table));
        table->GetDeviceProcAddr = gpa;
    % for cmd in commands:
        % if cmd.device_entrypoint and cmd.name != 'vkGetDeviceProcAddr':
            % if cmd.extension is not None and cmd.extension.define is not None:
    #ifdef ${cmd.extension.define}
        table->${cmd.name[2:]} = (PFN_${cmd.name}) gpa(device, "${cmd.name}");
    #endif
            % else:
        table->${cmd.name[2:]} = (PFN_${cmd.name}) gpa(device, "${cmd.name}");
            % endif
        % endif
    %endfor
    }
    """),
    output_encoding='utf-8')
Ejemplo n.º 16
0
    def render_template_to_string(self, template, context):
        """ Render template to a string using context. """

        context.update(self.filters)

        return Template(template).render(**context)
Ejemplo n.º 17
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-

if __name__ == "__main__":
    from inpho.model import *
    from mako.template import Template

    node_q = Session.query(Node)
    idea_q = Session.query(Idea)
    thinker_q = Session.query(Thinker)
    profession_q = Session.query(Profession)
    nationality_q = Session.query(Nationality)

    nodes = node_q.all()
    ideas = idea_q.all()
    thinkers = thinker_q.all()
    professions = profession_q.all()
    nationalities = nationality_q.all()

    owl = Template(filename='/var/inpho/inphosite/scripts/owl/owl.xml',
                   default_filters=['decode.utf8', 'u', 'x'])
    print owl.render_unicode(nodes=nodes,
                             thinkers=thinkers,
                             ideas=ideas,
                             professions=professions,
                             nationalities=nationalities).encode(
                                 'utf-8', 'replace')

else:
    raise Exception("Must be called from command line")
Ejemplo n.º 18
0
    print("--- %s seconds ---" % (time.time() - start_time))

if __name__ == "__main__":
    hostname = socket.gethostname()

    if args.qsub:
        with MPICommExecutor(MPI.COMM_WORLD, root=0) as executor:
            if executor is not None:
                arrancar_simulacion(executor, cluster_env_var=ENV_VAR, optimize=args.optimize)
        exit()

    if 'labomat' in hostname:
        user = getpass.getuser()

        ENV_VAR = f'LD_LIBRARY_PATH=/home/{user}/lib64:/home/{user}/usr/lib64:$LD_LIBRARY_PATH /home/{user}/lib64/ld-2.17.so /home/{user}/usr/bin/'
        os.environ['ELMER_HOME'] = f'/home/{user}/usr/'

        with open(f'cluster.q', 'w') as text_file:
            cluster_template = Template(filename='cluster_template.q')
            cluster = cluster_template.render(
                workers=8 if args.optimize else 96,
                opt='-opt' if args.optimize else ''
                user=user)
            text_file.write(cluster)

        subprocess.run('qsub cluster.q')
        os.remove('cluster.q')
    else:
        cpus = 1 if args.optimize else multiprocessing.cpu_count()
        with ThreadPoolExecutor(max_workers=cpus) as executor: 
            arrancar_simulacion(executor, optimize=args.optimize)
Ejemplo n.º 19
0
 def create_configuration(target):
     template_path = resource_filename('nikola', 'conf.py.in')
     conf_template = Template(filename=template_path)
     conf_path = os.path.join(target, 'conf.py')
     with io.open(conf_path, 'w+', encoding='utf8') as fd:
         fd.write(conf_template.render(**prepare_config(SAMPLE_CONF)))
Ejemplo n.º 20
0
    def _build_email_body(self, mako_template_filepath: str,
                          role: UserRoleInWorkspace, content: Content,
                          actor: User) -> str:
        """
        Build an email body and return it as a string
        :param mako_template_filepath: the absolute path to the mako template to be used for email body building
        :param role: the role related to user to whom the email must be sent. The role is required (and not the user only) in order to show in the mail why the user receive the notification
        :param content: the content item related to the notification
        :param actor: the user at the origin of the action / notification (for example the one who wrote a comment
        :param config: the global configuration
        :return: the built email body as string. In case of multipart email, this method must be called one time for text and one time for html
        """
        logger.debug(
            self, 'Building email content from MAKO template {}'.format(
                mako_template_filepath))

        template = Template(filename=mako_template_filepath)
        # TODO - D.A. - 2014-11-06 - move this
        # Import is here for circular import problem
        import tracim.lib.helpers as helpers

        dictified_item = Context(
            CTX.EMAIL_NOTIFICATION,
            self._global_config.WEBSITE_BASE_URL).toDict(content)
        dictified_actor = Context(CTX.DEFAULT).toDict(actor)

        main_title = dictified_item.label
        content_intro = ''
        content_text = ''
        call_to_action_text = ''

        action = content.get_last_action().id
        if ActionDescription.COMMENT == action:
            content_intro = l_(
                '<span id="content-intro-username">{}</span> added a comment:'
            ).format(actor.display_name)
            content_text = content.description
            call_to_action_text = l_('Answer')

        elif ActionDescription.CREATION == action:

            # Default values (if not overriden)
            content_text = content.description
            call_to_action_text = l_('View online')

            if ContentType.Thread == content.type:
                call_to_action_text = l_('Answer')
                content_intro = l_(
                    '<span id="content-intro-username">{}</span> started a thread entitled:'
                ).format(actor.display_name)
                content_text = '<p id="content-body-intro">{}</p>'.format(content.label) + \
                               content.get_last_comment_from(actor).description

            elif ContentType.File == content.type:
                content_intro = l_(
                    '<span id="content-intro-username">{}</span> added a file entitled:'
                ).format(actor.display_name)
                if content.description:
                    content_text = content.description
                else:
                    content_text = '<span id="content-body-only-title">{}</span>'.format(
                        content.label)

            elif ContentType.Page == content.type:
                content_intro = l_(
                    '<span id="content-intro-username">{}</span> added a page entitled:'
                ).format(actor.display_name)
                content_text = '<span id="content-body-only-title">{}</span>'.format(
                    content.label)

        elif ActionDescription.REVISION == action:
            content_text = content.description
            call_to_action_text = l_('View online')

            if ContentType.File == content.type:
                content_intro = l_(
                    '<span id="content-intro-username">{}</span> uploaded a new revision.'
                ).format(actor.display_name)
                content_text = ''

            elif ContentType.Page == content.type:
                content_intro = l_(
                    '<span id="content-intro-username">{}</span> updated this page.'
                ).format(actor.display_name)
                previous_revision = content.get_previous_revision()
                title_diff = ''
                if previous_revision.label != content.label:
                    title_diff = htmldiff(previous_revision.label,
                                          content.label)
                content_text = str(l_('<p id="content-body-intro">Here is an overview of the changes:</p>'))+ \
                    title_diff + \
                    htmldiff(previous_revision.description, content.description)

            elif ContentType.Thread == content.type:
                content_intro = l_(
                    '<span id="content-intro-username">{}</span> updated the thread description.'
                ).format(actor.display_name)
                previous_revision = content.get_previous_revision()
                title_diff = ''
                if previous_revision.label != content.label:
                    title_diff = htmldiff(previous_revision.label,
                                          content.label)
                content_text = str(l_('<p id="content-body-intro">Here is an overview of the changes:</p>'))+ \
                    title_diff + \
                    htmldiff(previous_revision.description, content.description)

            # elif ContentType.Thread == content.type:
            #     content_intro = l_('<span id="content-intro-username">{}</span> updated this page.').format(actor.display_name)
            #     previous_revision = content.get_previous_revision()
            #     content_text = l_('<p id="content-body-intro">Here is an overview of the changes:</p>')+ \
            #         htmldiff(previous_revision.description, content.description)

        elif ActionDescription.EDITION == action:
            call_to_action_text = l_('View online')

            if ContentType.File == content.type:
                content_intro = l_(
                    '<span id="content-intro-username">{}</span> updated the file description.'
                ).format(actor.display_name)
                content_text = '<p id="content-body-intro">{}</p>'.format(content.get_label()) + \
                    content.description

        elif ActionDescription.STATUS_UPDATE == action:
            call_to_action_text = l_('View online')
            intro_user_msg = l_('<span id="content-intro-username">{}</span> '
                                'updated the following status:')
            content_intro = intro_user_msg.format(actor.display_name)
            intro_body_msg = '<p id="content-body-intro">{}: {}</p>'
            content_text = intro_body_msg.format(
                content.get_label(),
                content.get_status().label,
            )

        if '' == content_intro and content_text == '':
            # Skip notification, but it's not normal
            logger.error(
                self, 'A notification is being sent but no content. '
                'Here are some debug informations: [content_id: {cid}]'
                '[action: {act}][author: {actor}]'.format(
                    cid=content.content_id, act=action, actor=actor))
            raise ValueError('Unexpected empty notification')

        # Import done here because cyclic import
        from tracim.config.app_cfg import CFG
        body_content = template.render(
            base_url=self._global_config.WEBSITE_BASE_URL,
            _=l_,
            h=helpers,
            user_display_name=role.user.display_name,
            user_role_label=role.role_as_label(),
            workspace_label=role.workspace.label,
            content_intro=content_intro,
            content_text=content_text,
            main_title=main_title,
            call_to_action_text=call_to_action_text,
            result=DictLikeClass(item=dictified_item, actor=dictified_actor),
            CFG=CFG.get_instance(),
        )

        return body_content
Ejemplo n.º 21
0
def template(tmpl):
    return Template(filename=os.path.join(root, 'setup/templates', tmpl))
Ejemplo n.º 22
0
 def test_import_2(self):
     t = Template("""
     trim this string: ${"  some string to trim   " | filters.trim} continue\
     """, imports=["from mako import filters"])
     #print t.code
     assert t.render().strip()=="trim this string: some string to trim continue"
Ejemplo n.º 23
0
 def test_via_template(self):
     t = Template("foo", lexer_cls=self._fixture())
     self._test_custom_lexer(t)
Ejemplo n.º 24
0
 def test_encode_filter(self):
     t = Template("""# coding: utf-8
         some stuff.... ${x}
     """, default_filters=['decode.utf8'])
     #print t.code
     assert t.render_unicode(x="voix m’a réveillé").strip() == u"some stuff.... voix m’a réveillé"
Ejemplo n.º 25
0
 def test_canuse_builtin_names(self):
     template = Template("""
         exception: ${Exception}
         id: ${id}
     """)
     assert flatten_result(template.render(id='some id', Exception='some exception')) == "exception: some exception id: some id"
Ejemplo n.º 26
0
    def test_basic(self):
        t = Template("""
        ${x | myfilter}
""")
        assert flatten_result(t.render(x="this is x", myfilter=lambda t: "MYFILTER->%s<-MYFILTER" % t)) == "MYFILTER->this is x<-MYFILTER"
Ejemplo n.º 27
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;"
Ejemplo n.º 28
0
import os

from mako.template import Template

myTemplate = Template(filename='template.html', strict_undefined=True)

# The installed gobos picture folder
src_dir = "C:/ProgramData/MA Lighting Technologies/grandma/gma2_V_3.9.60/gobos/"
# The generated filename. Default into gobo folder
genfile = open(src_dir + "./generated.html", "w", encoding='utf8')

i = 1
egysor = {1: {'sorszam': 0, 'filename': 'lófasz'}, }
for r, d, f in os.walk(src_dir):
    for file in f:
        if ".png" in file or ".bmp" in file:
            filename = os.path.join(r, file)
            egysor[i] = {'filename': filename}
            i += 1
genfile.write(myTemplate.render(rows=egysor, mappa=src_dir))
genfile.close()
Ejemplo n.º 29
0
 def test_convert_str(self):
     """test that string conversion happens in expressions before sending to filters"""
     t = Template("""
         ${x | trim}
     """)
     assert flatten_result(t.render(x=5)) == "5"
Ejemplo n.º 30
0
def render_login_page(data=None):
    login_template = Template(filename='templates/login.html', )
    return login_template.render_unicode()