Ejemplo n.º 1
0
def match_lexeme_forms_to_template(lexeme_forms: list,
                                   template: Template) -> MatchedTemplate:
    template = cast(MatchedTemplate, copy.deepcopy(template))
    for lexeme_form in lexeme_forms:
        best_template_forms = match_lexeme_form_to_template_forms(
            'test' in template, lexeme_form, template['forms'])
        if len(best_template_forms) == 1:
            best_template_form = cast(MatchedTemplateForm,
                                      best_template_forms[0])
            best_template_form.setdefault('lexeme_forms',
                                          []).append(lexeme_form)
        elif best_template_forms:
            template.setdefault('ambiguous_lexeme_forms',
                                []).append(lexeme_form)
        else:
            template.setdefault('unmatched_lexeme_forms',
                                []).append(lexeme_form)
    return template
Ejemplo n.º 2
0
async def login_post(request):
    post_data = await request.post()
    username = post_data['username']
    if username.lower() != verified_username:
        return Template('login.html', message='Invalid username')
    password = post_data['password']
    sid = await client.login(username, password)
    r = web.HTTPFound('/')
    r.set_cookie('sid', sid, max_age=31557600)
    return r
Ejemplo n.º 3
0
    def format_msg(self):
        # Construct email message with MIME
        msg = MIMEMultipart("alternative")
        msg["From"] = self.from_email
        msg["To"] = ", ".join(self.to_emails)
        msg["Subject"] = self.subject

        # If a text-type template was passed get the context
        if self.template_text_name is not None:
            template_filepath = Template(template_name=self.template_text_name,
                                         context=self.context)

            # context is already passed to template_filepath just need to render.
            template_content_string: str = template_filepath.render()
            txt_part = MIMEText(template_content_string, "plain")
            print(f"txt_part: {txt_part}")
            msg.attach(txt_part)

        if self.template_html_name is not None:
            template_filepath = Template(template_name=self.template_html_name,
                                         context=self.context)

            template_content_string: str = template_filepath.render()
            html_part = MIMEText(template_content_string, "html")
            print(f"html_part: {html_part}")
            msg.attach(html_part)

        msg_str: str = msg.as_string()

        return msg_str
Ejemplo n.º 4
0
    def exportWaypoints(self, waypoints, **kwargs):
        if 'path' in kwargs:
            filepath = os.path.join(kwargs['path'], 'waypoints.txt')
        else:    
            filepath = Utilities.getAppPrefix('waypoints.txt')
        
        template = Template.from_file(Utilities.getAppPrefix('waypoint_template.txt'))
        rendered = template.render(waypoints = waypoints)

        with open(filepath,'wt') as f:
            f.write(rendered)
            
        self.logger.debug('Successfully wrote waypoints to %s' % filepath)
        return filepath
Ejemplo n.º 5
0
    def exportWaypoints(self, waypoints, **kwargs):
        if 'path' in kwargs:
            filepath = os.path.join(kwargs['path'], 'waypoints.txt')
        else:    
            filepath = Utilities.getAppPrefix('waypoints.txt')
        
        template = Template.from_file(Utilities.getAppPrefix('waypoint_template.txt'))
        rendered = template.render(waypoints = waypoints)

        with open(filepath,'wt') as f:
            f.write(rendered)
            
        self.logger.info('Successfully wrote waypoints to %s' % filepath)
        return filepath
Ejemplo n.º 6
0
    def _createTemplateFiles(self):
        #
        prj_config_folder = self.appSettings.getFolder('con-fig-folder')
        prj_tmpl_folder = self.appSettings.getFolder('temp-lates-folder')
        prj_expand_folder = self.appSettings.getFolder('expanded-folder')

        # look in the expand folder to pick up the generated config files
        file_list = Util().getFileList(prj_expand_folder, '.json')

        files=[]
        #
        '''
        for conf_name in file_list:
            parts = conf_name.split('.')
            stuff = {'type':parts[1],
                     'config': conf_name,
                     'template-expected': self.appSettings.to_tmpl_expected(conf_name),
                     'template-actual': self.appSettings.to_tmpl(conf_name)}
            print('stuff', stuff)

            files.append(stuff)
        '''

        for stuff in File_Preview(): # formerly Stuff
            #print('stuff', stuff)
            tmplFile = None
            # custom template available when ==
            # no custom and no default available when
            if stuff['template-expected'] == stuff['template-actual']: # means custom file is available
                print('A Custom Template', stuff)
                #tmplFile = TemplateFile(prj_tmpl_folder, stuff['template']).read()
                tmplFile = Template({}, prj_tmpl_folder, stuff['template-expected'])

            elif stuff['template-actual'] == 'table-api-test.pg.tmpl':
                # look for tests attribute
                print('B API Test Template', stuff)
                #print(' * Function_UpsertTest goes here')
                tmplFile = Template_InterfaceTest({}) # with no dictionary to avoid templatization

            else:
                print('C Default Template', stuff)

                tmplFile = TextFile(prj_tmpl_folder, stuff['template-actual']).read()

            if len(tmplFile) == 0 :
                #print('folder', prj_tmpl_folder)
                raise Exception('Empty template {}'.format(stuff['template-actual']))

            # copy files to expand folder
            #print('Z copy', prj_expand_folder, stuff['template-expected'])
            Util().deleteFile(prj_expand_folder, stuff['template-expected'])
            tmplFile.copy(prj_expand_folder, stuff['template-expected'])

        return self
Ejemplo n.º 7
0
 def __export(self, tracks, path, **kwargs):
     if os.path.exists(Utilities.getAppPrefix('exportTemplates', 'pre', '%s.py' % self.name)):
         sys.path.append(Utilities.getAppPrefix('exportTemplates', 'pre'))
         pre_processor = __import__(self.name)
         for track in tracks:
             pre_processor.pre(track)
     
     if not os.path.exists(path):
         os.mkdir(path)
         
     path = os.path.join(path, "%s.%s" % (tracks[0].date.strftime("%Y-%m-%d_%H-%M-%S"), self.extension))
     #first arg is for compatibility reasons
     t = Template.from_file(Utilities.getAppPrefix('exportTemplates', '%s.txt' % self.name))
     rendered = t.render(tracks = tracks, track = tracks[0])
     
     with open(path, 'wt') as f:
         f.write(rendered)
Ejemplo n.º 8
0
 def __export(self, tracks, path, **kwargs):
     if os.path.exists(Utilities.getAppPrefix('exportTemplates', 'pre', '%s.py' % self.name)):
         sys.path.append(Utilities.getAppPrefix('exportTemplates', 'pre'))
         pre_processor = __import__(self.name)
         for track in tracks:
             pre_processor.pre(track)
     
     if not os.path.exists(path):
         os.mkdir(path)
         
     path = os.path.join(path, "%s.%s" % (tracks[0].date.strftime("%Y-%m-%d_%H-%M-%S"), self.extension))
     #first arg is for compatibility reasons
     t = Template.from_file(Utilities.getAppPrefix('exportTemplates', '%s.txt' % self.name))
     rendered = t.render(tracks = tracks, track = tracks[0])
     
     with open(path, 'wt') as f:
         f.write(rendered)
     return path
Ejemplo n.º 9
0
def application(environ, start_response):
    headers = [('Content-type', 'text/html')]
    try:
        path = environ.get('PATH_INFO', None)
        if path is None:
            raise NameError
        func_name, func, args = resolve_path(path)
        body = Template.answer(func_name, func(*args))
        body = func(*args)
        status = "200 OK"
    except NameError:
        status = "404 Not Found"
        body = '<h1>Not Found</h1>'
    except Exception:
        status = '500 Internal Server Error'
        body = '<h1>Internal Server Error</h1>'
        print(traceback.format_exc())
    finally:
        headers.append(('Content-length', str(len(body))))
        start_response(status, headers)
        return [body.encode('utf8')]
Ejemplo n.º 10
0
    def format_msg(self):
        msg = MIMEMultipart('alternative')
        msg['From'] = self.from_email
        msg['To'] = ", ".join(self.to_emails)
        msg['Subject'] = self.subject

        if self.template_name != None:
            tmpl_str = Template(template_name= self.template_name,context = self.context)
            txt_part = MIMEText(tmpl_str.render(), 'plain')
            print(txt_part)
            msg.attach(txt_part)
        if self.template_html != None:
            tmpl_str = Template(template_name= self.template_html,context = self.context)
            html_part = MIMEText(tmpl_str.render(), 'html')
            print(html_part)
            msg.attach(html_part)
        msg_str = msg.as_string()
        return msg_str
Ejemplo n.º 11
0
    def format_message(self):
        msg = MIMEMultipart('alternative')
        msg['From'] = self.from_email
        msg['To'] = self.to_emails
        msg['subject'] = self.subject

        if self.template_name is not None:
            template_obj = Template(self.template_name, self.context)
            text_part = MIMEText(template_obj.render(), 'plain')
            msg.attach(text_part)
        elif self.template_html is not None:
            template_obj = Template(self.template_html, self.context)
            html_part = MIMEText(template_obj.render(), 'html')
            msg.attach(html_part)
        else:
            pass

        msg_str = msg.as_string()
        return msg_str
Ejemplo n.º 12
0
    def format_msg(self):
        message = MIMEMultipart("alternative")
        message["Subject"] = self.subject
        message["From"] = self.from_to
        message["To"] = ', '.join(self.send_to)

        if self.template_name is not None:
            tmpl_str = Template(self.template_name, self.context)
            txt_part = MIMEText(tmpl_str.render(), 'plain')
            print(txt_part)
            message.attach(txt_part)

        if self.template_html is not None:
            tmpl_str = Template(self.template_html, self.context)
            html_part = MIMEText(tmpl_str.render(), 'html')
            print(html_part)
            message.attach(html_part)

        message = message.as_string()
        return message
Ejemplo n.º 13
0
                new_template_name = st.text_input(
                    "Create a New Template",
                    key="new_template",
                    value="",
                    help="Enter name and hit enter to create a new template.",
                )
                new_template_submitted = st.form_submit_button("Create")
                if new_template_submitted:
                    if new_template_name in dataset_templates.all_template_names:
                        st.error(
                            f"A template with the name {new_template_name} already exists "
                            f"for dataset {state.templates_key}.")
                    elif new_template_name == "":
                        st.error("Need to provide a template name.")
                    else:
                        template = Template(new_template_name, "", "")
                        dataset_templates.add_template(template)
                        reset_template_state()
                        state.template_name = new_template_name
                        # Keep the current working dataset in priority list
                        if priority_filter:
                            state.working_priority_ds = dataset_key
                else:
                    state.new_template_name = None

            with col1b, st.beta_expander("or Select Template", expanded=True):
                dataset_templates = template_collection.get_dataset(
                    *state.templates_key)
                template_list = dataset_templates.all_template_names
                if state.template_name:
                    index = template_list.index(state.template_name)
Ejemplo n.º 14
0
    col1, _, col2 = st.beta_columns([18, 1, 6])

    with col1:
        with st.beta_expander("Select Template", expanded=True):
            with st.form("new_template_form"):
                new_template_input = st.text_input("New Template Name", key="new_template_key", value="",
                                                   help="Enter name and hit enter to create a new template.")
                new_template_submitted = st.form_submit_button("Create")
                if new_template_submitted:
                    new_template_name = new_template_input
                    if new_template_name in templates.get_templates(dataset_key):
                        st.error(f"A template with the name {new_template_name} already exists "
                                 f"for dataset {dataset_key}.")
                    else:
                        template = Template(new_template_name, 'return ""', 'return ""', 'return ""', "")
                        templates.add_template(dataset_key, template)
                        save_data()
                else:
                    new_template_name = None

            dataset_templates = templates.get_templates(dataset_key)
            template_list = list(dataset_templates.keys())
            if new_template_name:
                index = template_list.index(new_template_name)
            else:
                index = 0
            template_name = st.selectbox('', template_list, key='template_select',
                                          index=index, help='Select the template to work on.')

            if st.button("Delete Template", key="delete_template"):
Ejemplo n.º 15
0
    def process(self):
        super().process()
        """
        if config file has a matching template file just expand it, write it to compiled-folder
        if config file has a default template, rename it, expand it, write copy to compiled-folder
        :return:
        """
        self.getData()
        # get folders

        conf_folder = self.appSettings.getFolder('expanded-folder')
        tmpl_folder = self.appSettings.getFolder('expanded-folder')
        expd_folder = self.appSettings.getFolder('expanded-folder')
        merge_folder = self.appSettings.getFolder('merged-folder')
        # list of config files
        file_name_list = Util().getFileList(conf_folder, ext='.json')

        # Project Template Compile

        for file_name in file_name_list:
            #print('filename', file_name)
            confFile = ConfigurationDict(conf_folder, file_name).read()

            if 'api-name' in confFile:
                #print('* api_name', confFile['api-name'])
                #print('* naem', self.appSettings.to_cmpl(file_name))
                #have register-user.interface-upsert.pg
                #print('* conffile', confFile)
                #print('* tmpl_folder', tmpl_folder, 'to_cmpl', self.appSettings.to_cmpl(file_name))
                tmplFile = Template(confFile, tmpl_folder,
                                    self.appSettings.to_cmpl(file_name))
                merge_file_name = self.appSettings.to_merged(file_name)
                print('merged', merge_file_name)

                #print('template ', tmplFile.toString())
                #print('template ',  tmplFile)
                tmplFile.copy(merge_folder, merge_file_name)
                #pprint(tmplFile)
            else:
                tmplFile = Template(confFile, tmpl_folder,
                                    self.appSettings.to_cmpl(file_name))
                merge_file_name = self.appSettings.to_merged(file_name)
                print('merged', merge_file_name)

                # print('template ', tmplFile.toString())
                # print('template ',  tmplFile)
                tmplFile.copy(merge_folder, merge_file_name)
            #print('to_tmpl',self.appSettings.to_tmpl(file_name, source_key='merged-folder'))
            #tmplFile = Template(confFile, tmpl_folder,self.appSettings.to_api(file_name,))
            #print('Results')
            #pprint(tmplFile)
            """
            #print('template name', self.appSettings.to_tmpl(file_name))
            #print('templ', tmplFile.toString())
            #print('confFile', confFile)
            #if confFile['type'] == 'interface-upsert':
                print('* table interface')
                print('confFile', confFile)

                # loop interfaces

                #confFile = InterfaceConfiguration(conf_folder, file_name)
                #print('conf filename', file_name, 'confFile', confFile)
                #print('tmpl filename', self.appSettings.to_tmpl(file_name, source_key='expanded-folder'))
                #print('handle table aux template files')
                tmpl = Template(confFile,)
            #else:
                print('')
                #print('straight template {}'.format(file_name))
                # tmplFile = Template(confFile, tmpl_folder,
                #                    self.appSettings.to_tmpl(file_name, source_key='expanded-folder'))
            """
            """
            expdResourceName = ResourceName(expd_folder, file_name)

            self.setConfigFile(ConfigurationDict(expdResourceName.getFolder(),
                                                 expdResourceName.getFileName()).read())

            cmplFile = self.expand(expdResourceName)

            if cmplFile == None:
                raise Exception('Compiled file cannot be None')

            cmplFile.write()
            """
        return self
Ejemplo n.º 16
0
def home():

    return Template.home()
Ejemplo n.º 17
0
async def login_get(request):
    return Template('login.html')
Ejemplo n.º 18
0
 print(pointer0)
 print("Template test")
 from templates import Template
 template0_pins = dict()
 template0_pins['in'] = {
     'xy': [[0, 0], [10, 10]],
     'netname': 'in',
     'layer': ['M1', 'drawing']
 }
 template0_pins['out'] = {
     'xy': [[90, 90], [100, 100]],
     'netname': 'out',
     'layer': ['M1', 'drawing']
 }
 template0 = Template(name='my_template0',
                      xy=[[0, 0], [100, 100]],
                      pins=template0_pins)
 print(template0)
 print("Instance test")
 inst0 = Instance(name='I0',
                  xy=[100, 100],
                  template=template0,
                  shape=[3, 2],
                  pitch=[100, 100],
                  transform='R0')
 print(inst0)
 print(inst0.shape)
 for idx, it in inst0.ndenumerate():
     print(idx, it.pins['in'])
 for idx, it in inst0.pins['in'].ndenumerate():
     print(idx, it)
Ejemplo n.º 19
0
 def _get_d_matcher(self, d_instance: Optional[List[Particle], None], phonemes: Optional[List[Sound], None],
                    size_limit: Optional[int, None], feature_to_sounds: Dict[str, List[Sound]]) -> List[Word]:
     return Template(d_instance).generate_word_list(phonemes, size_limit, feature_to_sounds, None)
Ejemplo n.º 20
0
 def __init__(self, file, **kwargs):
     highlight = file.split("/")[0]
     master = Template.from_file(Utilities.getAppPrefix('gui', 'tpl', 'global', 'master.html'))
     content = open(Utilities.getAppPrefix('gui', 'tpl', file)).read()
     merged = master.render(content=content, highlight=highlight)
     super(HTMLTemplate, self).__init__(merged, **kwargs)