Пример #1
0
    def render(self, renderer, form, renderable, out, **kwargs):

        """ render Input to HTML """

        fmtmap = renderer.createFormatMap(form, renderable, **kwargs)

        # the input renderer is also used for date + datetime classes
        # in that case we can use the html capable browser to set the 
        # input type to 'date' or 'datetime'
        fmtmap['input_type'] = 'text'
        if fmtmap['type'] in ('date', 'datetime', 'month'):
            fmtmap['input_type'] = fmtmap['type']

        try:
            value = form.getFieldValue(renderable.bind, lexical=True)
            # TODO: not sure about this string conversion..
            # leave unicode values intact.
            if not isinstance(value, unicode):
                value = str(value)
            if isinstance(value, str):
                value = value.decode('utf-8')
        except:
            value = u''

        if renderable.rows > 1:

            tpl = get_template("textarea")
        else:
            tpl = get_template("input")

        print >> out, tpl(
            control=renderable,
            value=value,
            fmtmap=fmtmap
            )
Пример #2
0
def send_the_email(old_list, old_num_clients, new_list, new_num_clients, added, removed):
	# try:
	email_conn = smtplib.SMTP(host, port)
	email_conn.ehlo()
	email_conn.starttls()
	email_conn.login(username, password)
	the_msg = MIMEMultipart('alternative')
	the_msg['Subject'] = "Kaiser client update"
	the_msg['From'] = from_email

	file_ = 'templates/email_message.txt'
	file_html = 'templates/email_message.html'
	template = get_template(file_)
	template_html = get_template(file_html)
	context = {
		"old_num_clients": old_num_clients,
	    "old_list": old_list,
	    "new_num_clients": new_num_clients,
	    "new_list": new_list,
	    "added": added,
	    "removed": removed,
	}
	rendered_text = render_context(template, context)
	rendered_html = render_context(template_html, context)
	part_1 = MIMEText(rendered_text, 'plain')
	part_2 = MIMEText(rendered_html, "html")
	the_msg.attach(part_1)
	the_msg.attach(part_2)
	email_conn.sendmail(from_email, to_list, the_msg.as_string())
	email_conn.quit()
	# except smtplib.SMTPException:
	#     print("error sending message")
Пример #3
0
 def render_message(self, user_data):
     file_ = 'hungry/templates/abc.txt'
     file_html = 'hungry/templates/abc.html'
     template = get_template(file_)
     template_html = get_template(file_html)
     context = user_data
     plain_ = render_context(template, context)
     html_ = render_context(template_html, context)
     return (plain_, html_)
Пример #4
0
def reset_and_fill_all_indices():
    all_orgs = [
        'explaain',
        'Matthew_Rusk_62352643',
        'yc',
        'Andrew_Davies_29862274',
        'financialtimes',
    ]
    all_index_names = [org.lower() + '__cards' for org in all_orgs] + [
        org.lower() + '__files' for org in all_orgs
    ] + ['organisations', 'sources', 'users']

    all_card_indices = [db.Cards(org) for org in all_orgs]
    all_file_indices = [db.Files(org) for org in all_orgs]
    # all_indices = all_card_indices + all_file_indices + [db.Organisations(), db.Sources(), db.Users()]
    all_indices = all_file_indices + [
        db.Organisations(), db.Sources(),
        db.Users()
    ]

    template_type = 'cards'
    template = templates.get_template(template_type)
    pp.pprint(
        es_client.IndicesClient(es).put_template(name=template_type,
                                                 body=template))
    # for org in all_orgs:
    #   index_name = org.lower() + '__cards'
    #   print(index_name)
    # print(json.dumps(es_client.IndicesClient(es).get_mapping(index=index_name, doc_type='card'), indent=2))
    # es_client.IndicesClient(es).close(index=index_name)
    # try:
    #   es_client.IndicesClient(es).put_mapping(index=index_name, doc_type='card', body=cards_template['mappings']['card'])
    #   es_client.IndicesClient(es).put_settings(index=index_name, body=cards_template['settings'])
    # except Exception as e:
    #   print(e)
    # es_client.IndicesClient(es).open(index=index_name)

    template_type = 'files'
    template = templates.get_template(template_type)
    pp.pprint(
        es_client.IndicesClient(es).put_template(name=template_type,
                                                 body=template))
    # for org in all_orgs:
    #   index_name = org.lower() + '__files'
    #   print(index_name)
    # es_client.IndicesClient(es).put_mapping(index=index_name, doc_type='file', body=files_template['mappings']['file'])

    # for index_name in all_index_names:
    #   print(index_name)
    #   if es_client.IndicesClient(es).exists(index=index_name):
    #     es_client.IndicesClient(es).delete(index=index_name)
    #   es_client.IndicesClient(es).create(index=index_name)
    for index in all_indices:
        copy_docs_from_algolia(index=index)
Пример #5
0
def extract_metadata_tar(manifest,
                         image_name,
                         include_env=True,
                         include_labels=True,
                         runscript=None):

    '''extract_metadata_tar will write a tarfile with the environment,
    labels, and runscript. include_env and include_labels should be booleans,
    and runscript should be None or a string to write to the runscript.
    '''
    tar_file = None
    files = []
    if include_env or include_labels:

        # Extract and add environment
        if include_env:
            environ = extract_env(manifest)
            if environ not in [None, ""]:
                bot.verbose3('Adding Docker environment to metadata tar')
                template = get_template('tarinfo')
                template['name'] = './%s/env/%s-%s.sh' % (METADATA_FOLDER_NAME,
                                                          DOCKER_NUMBER,
                                                          DOCKER_PREFIX)
                template['content'] = environ
                files.append(template)

        # Extract and add labels
        if include_labels:
            labels = extract_labels(manifest)
            if labels is not None:
                if isinstance(labels, dict):
                    labels = print_json(labels)
                bot.verbose3('Adding Docker labels to metadata tar')
                template = get_template('tarinfo')
                template['name'] = "./%s/labels.json" % METADATA_FOLDER_NAME
                template['content'] = labels
                files.append(template)

        if runscript is not None:
            bot.verbose3('Adding Docker runscript to metadata tar')
            template = get_template('tarinfo')
            template['name'] = "./%s/runscript" % METADATA_FOLDER_NAME
            template['content'] = runscript
            files.append(template)

    if len(files) > 0:
        output_folder = get_cache(subfolder="metadata", quiet=True)
        tar_file = create_tar(files, output_folder)
    else:
        bot.warning("No metadata will be included.")
    return tar_file
Пример #6
0
def extract_metadata_tar(manifest,
                         image_name,
                         include_env=True,
                         include_labels=True,
                         runscript=None):
    '''extract_metadata_tar will write a tarfile with the environment,
    labels, and runscript. include_env and include_labels should be booleans,
    and runscript should be None or a string to write to the runscript.
    '''
    tar_file = None
    files = []
    if include_env or include_labels:

        # Extract and add environment
        if include_env:
            environ = extract_env(manifest)
            if environ not in [None, ""]:
                bot.verbose3('Adding Docker environment to metadata tar')
                template = get_template('tarinfo')
                template['name'] = './%s/env/%s-%s.sh' % (
                    METADATA_FOLDER_NAME, DOCKER_NUMBER, DOCKER_PREFIX)
                template['content'] = environ
                files.append(template)

        # Extract and add labels
        if include_labels:
            labels = extract_labels(manifest)
            if labels is not None:
                if isinstance(labels, dict):
                    labels = print_json(labels)
                bot.verbose3('Adding Docker labels to metadata tar')
                template = get_template('tarinfo')
                template['name'] = "./%s/labels.json" % METADATA_FOLDER_NAME
                template['content'] = labels
                files.append(template)

        if runscript is not None:
            bot.verbose3('Adding Docker runscript to metadata tar')
            template = get_template('tarinfo')
            template['name'] = "./%s/runscript" % METADATA_FOLDER_NAME
            template['content'] = runscript
            files.append(template)

    if len(files) > 0:
        output_folder = get_cache(subfolder="metadata", quiet=True)
        tar_file = create_tar(files, output_folder)
    else:
        bot.warning("No metadata will be included.")
    return tar_file
Пример #7
0
	def get(self):
		settings = Settings.get() #Force email address update...
		posts = Post.query().order(-Post.date).fetch(1)
		is_newest = True
		if posts:
			post = posts[0]
			is_oldest = post.date == Post.min_date()
		else:
			post = None
			is_oldest = True


		#See if this is the very first time we've been here. In that case
		#send an email immediately to get people started...
		first_time = False
		
		if not Slug.query().get() and not Post.query().get():
			first_time = True
			DailyMail().send(True)

		self.response.write(get_template('frontpage.html').render(
			{
				"page":"frontpage", 
				"post":post, 
				"is_oldest" : is_oldest,
				"is_newest" : is_newest,
				"first_time" : first_time,
				"email" : settings.email_address
			}))
Пример #8
0
    def render(self, renderer, form, renderable, out, **kwargs):

        fmtmap = renderer.createFormatMap(form, renderable, **kwargs)

        if renderable.bind:
            # only change text if a value was calculated
            calculate_found = False
            for props in form.model.getFieldProperties(renderable.bind):
                if props.getCalculate():
                    calculate_found = True
                    break

            if calculate_found:
                try:
                    value = form.getFieldValue(renderable.bind, lexical=True)
                    # TODO: not sure about this string conversion..
                    # leave unicode values intact.
                    if not isinstance(value, unicode):
                        value = str(value)
                    if isinstance(value, str):
                        value = value.decode('utf-8')
                    fmtmap['text'] = value
                except:
                    pass

        print >> out, get_template("text")(control=renderable,
                                           text=fmtmap['text'],
                                           fmtmap=fmtmap)
Пример #9
0
    def get(self, year, month, day, type):
        date = datetime.date(int(year), int(month), int(day))
        min_date, max_date = Post.min_date(), Post.max_date()
        if type == 'prev':
            posts = Post.query(Post.date < date).order(-Post.date).fetch(1)
        elif type == 'next':
            posts = Post.query(Post.date > date).order(Post.date).fetch(1)
        elif type == 'random':
            count = PostCounter.get().count
            posts = Post.query().fetch(1, offset=random.randint(0, count - 1))

        post = None
        if posts:
            post = posts[0]

        self.response.write(
            get_template('frontpagepost.html').render({
                "page":
                "frontpage",
                "post":
                post,
                "is_newest":
                post.date == max_date,
                "is_oldest":
                post.date == min_date
            }))
Пример #10
0
    def render(self, renderer, form, renderable, out, **kwargs):

        currentpage = kwargs.get('currentpage', None)

        str_out = StringIO()
        sub_out = codecs.getwriter('utf-8')(str_out)

        for sub_renderable in renderable.getRenderables():
            stepgroup_classes = "step"

            item = sub_renderable

            if currentpage and item.id == currentpage:
                stepgroup_classes += " active"

            renderer.render(form, item, sub_out,
                    stepgroup_classes=stepgroup_classes, **kwargs)

        steps = [{'id': step.id, "class": "", 'label': step.label} for step in \
                 renderable.getRenderables()]

        steps[0]['class'] = "first"
        steps[-1]['class'] = "last"

        fmtmap = renderer.createFormatMap(form, renderable, **kwargs)

        print >> out, get_template('stepgroup')(
            group=renderable,
            steps=steps,
            content=str_out.getvalue().decode("utf-8"),
            fmtmap=fmtmap
            )
Пример #11
0
    def renderFrontMatter(self, form, out, errors=None, **kwargs):

        """ Render whatever needs to be rendered before the actual
        form components"""

        kwargs['action'] = getattr(form.submission, 'action',
                                   kwargs.get('action', ''))

        form_class = kwargs.get('form_class', '')
        form_class += " " + self.opts.get('class', '')
        kwargs['form_class'] = form_class.strip()
        kwargs['page_id'] = kwargs.get('page_id', '')
        kwargs['status_message'] = ''

        if kwargs['status'] in ["completed", "error"]:
            kwargs['status_message'] = getattr(form.submission,
                                               "status_" + kwargs.get('status',
                                                                      ''),
                                               kwargs.get('status', '')
                                               )

        print >> out, get_template('frontmatter')(
            form_id=form.id,
            **kwargs
            )
Пример #12
0
    def render(self, renderer, form, renderable, out, **kwargs):

        currentpage = kwargs.get('currentpage', None)

        str_out = StringIO()
        sub_out = codecs.getwriter('utf-8')(str_out)

        for sub_renderable in renderable.getRenderables():
            stepgroup_classes = "step"

            item = sub_renderable

            if currentpage and item.id == currentpage:
                stepgroup_classes += " active"

            renderer.render(form,
                            item,
                            sub_out,
                            stepgroup_classes=stepgroup_classes,
                            **kwargs)

        steps = [{'id': step.id, "class": "", 'label': step.label} for step in \
                 renderable.getRenderables()]

        steps[0]['class'] = "first"
        steps[-1]['class'] = "last"

        fmtmap = renderer.createFormatMap(form, renderable, **kwargs)

        print >> out, get_template('stepgroup')(
            group=renderable,
            steps=steps,
            content=str_out.getvalue().decode("utf-8"),
            fmtmap=fmtmap)
Пример #13
0
    def render(self, renderer, form, renderable, out, **kwargs):

        fmtmap = renderer.createFormatMap(form, renderable, **kwargs)

        if renderable.bind:
            # only change text if a value was calculated
            calculate_found = False
            for props in form.model.getFieldProperties(renderable.bind):
                if props.getCalculate():
                    calculate_found = True
                    break

            if calculate_found:
                try:
                    value = form.getFieldValue(renderable.bind, lexical=True)
                    # TODO: not sure about this string conversion..
                    # leave unicode values intact.
                    if not isinstance(value, unicode):
                        value = str(value)
                    if isinstance(value, str):
                        value = value.decode('utf-8')
                    fmtmap['text'] = value
                except:
                    pass

        print >> out, get_template("text")(
            control=renderable,
            text=fmtmap['text'],
            fmtmap=fmtmap
            )
Пример #14
0
    def get(self):
        settings = Settings.get()  #Force email address update...
        posts = Post.query().order(-Post.date).fetch(1)
        is_newest = True
        if posts:
            post = posts[0]
            is_oldest = post.date == Post.min_date()
        else:
            post = None
            is_oldest = True

        #See if this is the very first time we've been here. In that case
        #send an email immediately to get people started...
        first_time = False

        if not Slug.query().get() and not Post.query().get():
            first_time = True
            DailyMail().send(True)

        self.response.write(
            get_template('frontpage.html').render({
                "page":
                "frontpage",
                "post":
                post,
                "is_oldest":
                is_oldest,
                "is_newest":
                is_newest,
                "first_time":
                first_time,
                "email":
                settings.email_address
            }))
Пример #15
0
    def render(self, renderer, form, renderable, out, **kwargs):

        fmtmap = renderer.createFormatMap(form, renderable, **kwargs)

        print >> out, get_template('cancel')(
            control=renderable,
            extra_classes=fmtmap['extra_classes'],
            fmtmap=fmtmap)
Пример #16
0
    def render(self, renderer, form, renderable, out, **kwargs):

        fmtmap = renderer.createFormatMap(form, renderable, **kwargs)

        if 'name' not in fmtmap:
            fmtmap['name'] = 'submit'  # default name

        print >> out, get_template("submit")(control=renderable, fmtmap=fmtmap)
Пример #17
0
    def render(self, renderer, form, renderable, out, **kwargs):

        fmtmap = renderer.createFormatMap(form, renderable, **kwargs)

        print >> out, get_template('cancel')(
            control=renderable,
            extra_classes=fmtmap['extra_classes'],
            fmtmap=fmtmap
            )
Пример #18
0
 def create_migration_file(self):
     directory = config.get_migrations_dir()
     f = self.migration_file_exists()
     if f:
         print "migration file already exists [%s]" % f
     else:
         print "creating migration file[%s]" % self.filename
         fileData = templates.get_template(self.TEMPLATE) % self.version
         files.create_file(directory, self.filename, fileData)
Пример #19
0
 def create_rollback_file(self):
     directory = config.get_rollbacks_dir()
     f = self.rollback_file_exists()
     if f:
         print "migration rollback file already exists [%s]" % f
     else:
         rbName = self.rollback_filename()
         fileData = templates.get_template("rollback") % self.version
         files.create_file(directory, rbName, fileData)
Пример #20
0
 def create_seed_file(self):
     directory = config.get_seeds_dir()
     f = files.check_sql_file_exists(config.get_seeds_dir(), self.name)
     if f:
         print "seed file already exists [%s]" % f
     else:
         filename = self.name + ".sql"
         print "creating seed file[%s]" % filename
         fileData = templates.get_template(self.TEMPLATE)
         files.create_file(directory, self.filename, fileData)
Пример #21
0
    def render(self, renderer, form, renderable, out, **kwargs):
        """ render File to HTML """

        fmtmap = renderer.createFormatMap(form, renderable, **kwargs)

        fmtmap['value'] = renderable.lexVal(form.data[renderable.bind])

        print >> out, get_template("file")(control=renderable,
                                           fmtmap=fmtmap,
                                           form_id=form.id)
Пример #22
0
    def render(self, renderer, form, renderable, out, **kwargs):

        fmtmap = renderer.createFormatMap(form, renderable, **kwargs)

        opts = []

        if renderable.vocab:

            vocab = Registry.get_vocab(renderable.vocab)

            if callable(vocab):

                args = []
                if renderable.vocab_args:
                    args = renderable.vocab_args.split(",")

                opts = vocab(*args, **kwargs)

        opts.extend(renderable.options)

        value = form.data[renderable.bind]

        # some hacking for multiple type. sometimes the saved data is just a
        # plain old type (int) and we expect a list of strings in the template
        if fmtmap['multiple'] and fmtmap['multiple'].lower() == 'true':
            value = form.getFieldValue(renderable.id, lexical=False)
            if type(value) == ListType:  # just to be sure?
                value = [str(val) for val in value]

        if renderable.format == "full":

            print >> out, get_template('select_full')(control=renderable,
                                                      value=value,
                                                      options=opts,
                                                      fmtmap=fmtmap)

        else:

            print >> out, get_template('select')(control=renderable,
                                                 value=value,
                                                 options=opts,
                                                 multiple=fmtmap['multiple'],
                                                 fmtmap=fmtmap)
Пример #23
0
    def render(self, renderer, form, renderable, out, **kwargs):

        fmtmap = renderer.createFormatMap(form, renderable, **kwargs)

        if 'name' not in fmtmap:
            fmtmap['name'] = 'submit'  # default name

        print >> out, get_template("submit")(
            control=renderable,
            fmtmap=fmtmap
            )
Пример #24
0
    def ChangeSet(self,arch,source_version,target_version):
        out = ''
        arches = self.request.get('arches')
        if arches:
            oarch,narch = (int(_) for _ in arches.split('|')[:2])
        else:
            oarch = version_arch(source_version)
            narch = version_arch(target_version)

        if oarch is None: oarch = arch
        if narch is None: narch = arch

        omanifest = fetcher.fetch(oarch,source_version,'manifest.xml')
        nmanifest = fetcher.fetch(narch,target_version,'manifest.xml')


        if omanifest is not None:
            #Version(value=source_version,key_name=source_version).put()
            version_ok(oarch,source_version)
        if nmanifest is not None:
            #Version(value=target_version,key_name=target_version).put()
            version_ok(narch,target_version)            
        if omanifest is None:
            out += ('Sorry, could not fetch manifest for %s' % source_version)
        elif nmanifest is None:
            out += ('Sorry, could not fetch manifest for %s' % target_version)
        else:
            omanifest = Manifest(omanifest)
            nmanifest = Manifest(nmanifest)

            changeset = Changeset(omanifest,nmanifest)

            changes = ( {'path' : f, 'old_version' : omanifest.files[f]['version'], \
                    'new_version' : nmanifest.files[f]['version'] } for f in changeset.changes )
            adds = ( {'path' : f,  \
                    'new_version' : nmanifest.files[f]['version'] } for f in changeset.adds )
            dels = ( {'path' : f, 'old_version' : omanifest.files[f]['version']\
                     } for f in changeset.dels )

            template_values = {
                    'source_version': source_version,
                    'target_version': target_version,
                    'changes': changes,
                    'adds' : adds,
                    'dels' : dels,
                    'base_url' : fetcher.get_base_url(arch),
                    'base_url2' : fetcher.get_base_url(arch, 1),
                    'arches' : '|'.join([str(_) for _ in [oarch,narch]]),
                    }
            template = templates.get_template('changeset.html')
            return template.render(template_values)
        self.response.out.write(out)
        return None
Пример #25
0
    def render(self, renderer, form, renderable, out, **kwargs):

        """ render Input to HTML """

        fmtmap = renderer.createFormatMap(form, renderable, **kwargs)

        fmtmap['value'] = "*****"

        print >> out, get_template('password')(
            control=renderable,
            fmtmap=fmtmap
            )
Пример #26
0
    def render(self, renderer, form, renderable, out, **kwargs):
        """ render Hidden to HTML """

        fmtmap = renderer.createFormatMap(form, renderable, **kwargs)

        try:
            value = form.getFieldValue(renderable.bind)
        except:
            value = ""

        print >> out, get_template('hidden')(control=renderable,
                                             value=value,
                                             fmtmap=fmtmap)
Пример #27
0
    def render(self, renderer, form, renderable, out, **kwargs):

        """ render File to HTML """

        fmtmap = renderer.createFormatMap(form, renderable, **kwargs)

        fmtmap['value'] = renderable.lexVal(form.data[renderable.bind])

        print >> out, get_template("file")(
            control=renderable,
            fmtmap=fmtmap,
            form_id=form.id
            )
Пример #28
0
    def render(self, renderer, form, renderable, out, **kwargs):

        fmtmap = renderer.createFormatMap(form, renderable, **kwargs)

        opts = []

        if renderable.vocab:

            vocab = Registry.get_vocab(renderable.vocab)

            if callable(vocab):

                args = []
                if renderable.vocab_args:
                    args = renderable.vocab_args.split(",")

                opts = vocab(*args, **kwargs)

        opts.extend(renderable.options)

        value = form.data[renderable.bind]

        # some hacking for multiple type. sometimes the saved data is just a
        # plain old type (int) and we expect a list of strings in the template
        if fmtmap["multiple"] and fmtmap["multiple"].lower() == "true":
            value = form.getFieldValue(renderable.id, lexical=False)
            if type(value) == ListType:  # just to be sure?
                value = [str(val) for val in value]

        if renderable.format == "full":

            print >> out, get_template("select_full")(control=renderable, value=value, options=opts, fmtmap=fmtmap)

        else:

            print >> out, get_template("select")(
                control=renderable, value=value, options=opts, multiple=fmtmap["multiple"], fmtmap=fmtmap
            )
Пример #29
0
def manualTestPageContent(environ):
    deviceList = functions.DeviceDB.query_all_devices()
    if os.path.exists(UploadPath):
        filelist = os.listdir(UploadPath)
    else:
        filelist = []
        os.mkdir(UploadPath)
    template = templates.get_template( 'ManualTestPage.html' )

    templateVars = {
        'devicelist': deviceList,
        'filelist':filelist
                   }
    return templates.render_template(template, templateVars)
Пример #30
0
    def render(self, renderer, form, renderable, out, **kwargs):

        """ render Hidden to HTML """

        fmtmap = renderer.createFormatMap(form, renderable, **kwargs)

        try:
            value = form.getFieldValue(renderable.bind)
        except:
            value = ""

        print >> out, get_template('hidden')(
            control=renderable,
            value=value,
            fmtmap=fmtmap)
Пример #31
0
    def render(self, renderer, form, renderable, out, **kwargs):
        """ Render flow group that flows horizontally or vertically """

        fmtmap = renderer.createFormatMap(form, renderable, **kwargs)

        str_out = StringIO()
        sub_out = codecs.getwriter('utf-8')(str_out)

        for sub_renderable in renderable.getRenderables():
            renderer.render(form, sub_renderable, sub_out, **kwargs)

        print >> out, get_template('flowgroup')(
            group=renderable,
            content=str_out.getvalue().decode("utf-8"),
            fmtmap=fmtmap)
Пример #32
0
    def get_page(self,arch,version,path,fpath):
        manifest = fetcher.fetch(arch,version,'manifest.xml')
        if manifest is not None:
            #Version(value=version,key_name=version).put()
            version_ok(arch,version)
        else:
            self.response.out.write("Sorry, could not fetch manifest for {0} version".format(version))
            return
        manifest = Manifest(manifest)
        path = path[1:]
        if fpath != '':
            print 'file requested!'
        else:
            if path == '':
                nodes = manifest.files.keys()
            else:
                l = len(path)
                nodes = [f[l:] for f in manifest.files.keys() if f.startswith(path)]
            dirs = []
            files = []
            for x in nodes:
                n = x.split('/')
                if len(n) == 1:
                    x = path + x
                    f = { 'path' : n[0] , 'version' : fetcher.normalize_ver(manifest.files[x]['version']), 'size' : manifest.files[x]['size'] }
                    f['lang'] = get_lang(n[0])
                    f['fullpath'] = x
                    files.append(f)
                else:
                    dirs.append(n[0])
            dirs = frozenset(dirs)

            if path != '':
                up_url = '..'
            else:
                up_url = ''

            template_values = {
                    'version': version,
                    'path': path,
                    'dirs': sorted(list(dirs)),
                    'files' : files,
                    'up_url' : up_url,
                    'base_url' : fetcher.get_base_url(arch),
                    'base_url2' : fetcher.get_base_url(arch, 1),
                    }
            template = templates.get_template('folder.html')
            return template.render(template_values)
Пример #33
0
	def _render(self, settings, saved=False):
		data = {
			"page" : "settings",
			"email_address" : settings.email_address,
			"dropbox_access_token" : settings.dropbox_access_token or "",
			"timezone" : settings.timezone,
			"timezones" : timezones,
			"email_hour" : settings.email_hour,
			"include_old_post_in_entry" : settings.include_old_post_in_entry,
			"upload_url" : filestore.create_upload_url('/upload-finished'),
			"saved" : saved,
			"can_migrate_images" : not settings.blobstore_migration_done,
			"bucket_exists" : filestore.bucket_exists(),
			"version" : open('VERSION').read()
		}
		self.response.write(get_template('settings.html').render(data))
Пример #34
0
    def render(self, renderer, form, renderable, out, **kwargs):

        fmtmap = renderer.createFormatMap(form, renderable, **kwargs)

        def render_subs(sub):
            """ render the sub renderable """
            str_out = StringIO()
            out = codecs.getwriter('utf-8')(str_out)
            sub.extra_classes = (sub.extra_classes or "") + " card"
            renderer.render(form, sub, out, **kwargs)
            return out.getvalue().decode('utf-8')

        print >> out, get_template('cardgroup')(
            group=renderable,
            fmtmap=fmtmap,
            render_subs = render_subs
            )
Пример #35
0
    def render(self, renderer, form, renderable, out, **kwargs):
        """ render Input to HTML """

        fmtmap = renderer.createFormatMap(form, renderable, **kwargs)

        fmtmap['value'] = form.data[renderable.bind] or ""
        fmtmap['richconfig'] = renderer.opts.get('richconfig', '')
        fmtmap['richclass'] = 'wysiwyg'
        fmtmap['cols'] = renderable.cols or 80
        fmtmap['rows'] = renderable.rows or 3

        # added to guarantee backwards compatibilty (WGH)
        if not 'cols' in fmtmap:
            fmtmap['cols'] = '30'

        print >> out, get_template('richtext')(control=renderable,
                                               fmtmap=fmtmap)
Пример #36
0
    def render(self, renderer, form, renderable, out, **kwargs):

        """ Render flow group that flows horizontally or vertically """

        fmtmap = renderer.createFormatMap(form, renderable, **kwargs)

        str_out = StringIO()
        sub_out = codecs.getwriter('utf-8')(str_out)

        for sub_renderable in renderable.getRenderables():
            renderer.render(form, sub_renderable, sub_out, **kwargs)

        print >> out, get_template('flowgroup')(
            group=renderable,
            content=str_out.getvalue().decode("utf-8"),
            fmtmap=fmtmap
            )
Пример #37
0
    def renderFrontMatter(self, form, out, errors=None, **kwargs):
        """ Render whatever needs to be rendered before the actual
        form components"""

        kwargs['action'] = getattr(form.submission, 'action',
                                   kwargs.get('action', ''))

        form_class = kwargs.get('form_class', '')
        form_class += " " + self.opts.get('class', '')
        kwargs['form_class'] = form_class.strip()
        kwargs['page_id'] = kwargs.get('page_id', '')
        kwargs['status_message'] = ''

        if kwargs['status'] in ["completed", "error"]:
            kwargs['status_message'] = getattr(
                form.submission, "status_" + kwargs.get('status', ''),
                kwargs.get('status', ''))

        print >> out, get_template('frontmatter')(form_id=form.id, **kwargs)
Пример #38
0
    def render(self, renderer, form, renderable, out, **kwargs):

        """ render Input to HTML """

        fmtmap = renderer.createFormatMap(form, renderable, **kwargs)

        fmtmap['value'] = form.data[renderable.bind] or ""
        fmtmap['richconfig'] = renderer.opts.get('richconfig', '')
        fmtmap['richclass'] = 'wysiwyg'
        fmtmap['cols'] = renderable.cols or 80
        fmtmap['rows'] = renderable.rows or 3

        # added to guarantee backwards compatibilty (WGH)
        if not 'cols' in fmtmap:
            fmtmap['cols'] = '30'

        print >> out, get_template('richtext')(
            control=renderable,
            fmtmap=fmtmap)
Пример #39
0
    def render(self, renderer, form, renderable, out, **kwargs):
        """ render Input to HTML """

        value = form.data[renderable.bind]
        fmtmap = renderer.createFormatMap(form, renderable, **kwargs)

        checked = None

        if value:
            checked = "checked"

        value = "1"

        print >> out, get_template("checkbox")(
            control=renderable,
            value=value,
            checked=checked,
            fmtmap=fmtmap,
        )
Пример #40
0
    def get_page(self,arch,accountid):
        try:
            count = int(self.request.query_string)
        except:
            count = 50

        accountid = int(accountid)
        if count == 0:
            count = 50
        base_url = 'http://s3.amazonaws.com/naeu-icb/icons/%d/%d/%d/' % \
                ( accountid / 1000000, (accountid % 1000000 ) / 1000, accountid )

        base_url += '%d.cai'

        template_values = {
                'base_url' : base_url,
                'count' : count,
                }
        template = templates.get_template('cai.html')
        return template.render(template_values)
Пример #41
0
    def render(self, renderer, form, renderable, out, **kwargs):

        """ render Input to HTML """

        value = form.data[renderable.bind]
        fmtmap = renderer.createFormatMap(form, renderable, **kwargs)

        checked = None

        if value:
            checked = "checked"

        value = "1"

        print >> out, get_template("checkbox")(
            control=renderable,
            value=value,
            checked=checked,
            fmtmap=fmtmap,
            )
Пример #42
0
    def get_page(self, arch, version, path):
        lang = self.request.query_string
        if lang == "":
            lang = "text"
        if not is_diffable(path):
            return "Sorry, viewing this types of files is not allowed"
        data = fetcher.fetch(arch, version, path)
        if data is None:
            self.response.out.write("Sorry, could not fetch file %s for version %s.<br>" % (version, path))
            return None
        else:
            data = data.read()
            try:
                data = data.decode("utf8")
            except:
                data = data.decode("cp1251")

            template_values = {"data": pygmentize(lang, data)}

            template = get_template("highlight.html")
            return template.render(template_values)
Пример #43
0
 def get(self):
     arch = ARCHS.LINUX_RETAIL
     arches = self.request.get('arches')
     if arches :
         arch = sorted([int(_) for _ in arches.split('|')])[-1]
     elif self.request.headers['Host'].split('.')[0] == 'rct':
         arch = ARCHS.LINUX_RCT
     elif self.request.headers['Host'].split('.')[0] == 'sbt':
         arch = ARCHS.LINUX_SBT
     #self.response.out.write('Hello world!')
     versions = get_versions(arch)
     versions.sort(key = lambda x: [int(y) for y in x.split('.')])
     version = versions[-1]
     prevversion = versions[-2]
     template_values = {
         'versions' : get_versions(),
         'latest' : version,
         'previous' : prevversion,
         }
     template = templates.get_template('index.html')        
     self.response.out.write(template.render(template_values))
Пример #44
0
	def get(self, year, month, day, type):
		date = datetime.date(int(year), int(month), int(day))
		min_date, max_date = Post.min_date(), Post.max_date()
		if type == 'prev':
			posts = Post.query(Post.date < date).order(-Post.date).fetch(1)
		elif type == 'next':
			posts = Post.query(Post.date > date).order(Post.date).fetch(1)
		elif type == 'random':
			count = PostCounter.get().count
			posts = Post.query().fetch(1, offset=random.randint(0, count-1))

		post = None
		if posts:
			post = posts[0]

		self.response.write(get_template('frontpagepost.html').render(
			{
				"page":"frontpage", 
				"post":post,
				"is_newest":post.date == max_date,
				"is_oldest":post.date == min_date
			}))
Пример #45
0
	def get(self, kind, year, month, day):
		date = datetime.datetime(int(year),int(month),int(day)).date()
		
		post = Post.query(Post.date == date).get()
		if kind == 'write' and post:
			return self.redirect('/edit/%s' % date.strftime('%Y-%m-%d'))
		if kind == 'edit' and not post:
			return self.redirect('/write/%s' % date.strftime('%Y-%m-%d'))
		
		data = { 
			"date" : date,
			"text" : "",
			"page" : "write",
			"kind" : kind
		}
		if post:
			data["page"] = "edit"
			data["text"] = post.text
			data["images"] = post.images
		else:
			data["images"] = [u.filename for u in UserImage.query(UserImage.date == date).fetch()]

		self.response.write(get_template('edit.html').render(data))
Пример #46
0
	def get(self, kind, year, month, day):
		date = datetime.datetime(int(year),int(month),int(day)).date()
		
		post = Post.query(Post.date == date).get()
		if kind == 'write' and post:
			return self.redirect('/edit/%s' % date.strftime('%Y-%m-%d'))
		if kind == 'edit' and not post:
			return self.redirect('/write/%s' % date.strftime('%Y-%m-%d'))
		
		data = { 
			"date" : date,
			"text" : "",
			"page" : "write",
			"kind" : kind
		}
		if post:
			data["page"] = "edit"
			data["text"] = post.text
			data["images"] = post.images
		else:
			data["images"] = [u.filename for u in UserImage.query(UserImage.date == date).fetch()]

		self.response.write(get_template('edit.html').render(data))
Пример #47
0
from qgis.core import (QgsExpression, QgsFeature, QgsMapLayer,
                       QgsFeatureRequest, QgsGeometry, NULL)

from roam import utils
from roam.popupdialogs import PickActionDialog
from roam.flickwidget import FlickCharm
from roam.htmlviewer import updateTemplate, clear_image_cache
from roam.ui.uifiles import (infodock_widget)
from roam.api import RoamEvents, GPS
from roam.dataaccess import database
from roam.api.utils import layer_by_name, values_from_feature

import templates

infotemplate = templates.get_template("info")
infoblocktemplate = templates.get_template("infoblock")
countblocktemplate = templates.get_template("countblock")


class NoFeature(Exception):
    pass


class FeatureCursor(object):
    """
    A feature cursor that keeps track of the current feature
    and handles wrapping to the start and end of the list

    HACK: This could be a lot nicer and cleaner but it works
    for now
Пример #48
0
    def render(self, renderer, form, renderable, out, **kwargs):

        fmtmap = renderer.createFormatMap(form, renderable, **kwargs)

        print >> out, get_template("reset")(control=renderable, fmtmap=fmtmap)
Пример #49
0
from qgis.core import (QgsExpression, QgsFeature,
                       QgsMapLayer, QgsFeatureRequest)

from roam import utils
from roam.flickwidget import FlickCharm
from roam.htmlviewer import updateTemplate, clear_image_cache
from roam.ui.uifiles import (infodock_widget)
from roam.api import RoamEvents
from roam.dataaccess import database
from roam.api.utils import layer_by_name, values_from_feature


import templates

infotemplate = templates.get_template("info")
infoblocktemplate = templates.get_template("infoblock")
countblocktemplate = templates.get_template("countblock")


class NoFeature(Exception):
    pass


class FeatureCursor(object):
    """
    A feature cursor that keeps track of the current feature
    and handles wrapping to the start and end of the list

    HACK: This could be a lot nicer and cleaner but it works
    for now
Пример #50
0
 def index(self):
   return templates.get_template("layout.haml").render()
Пример #51
0
	def get(self):
		data = { "page" : "write"}
		self.response.write(get_template('calendar.html').render(data))
Пример #52
0
 def staging(self):
   staging_files = staging.staging("/home/asafg/staging").list_files()
   thumbnails = map(self.make_thumbnail, staging_files)
   return templates.get_template("staging.haml").render(files=thumbnails)
Пример #53
0
 def send_page(self, template, page_dict):
     self.response.write(get_template(template).render(page_dict))
Пример #54
0
    def render(self, renderer, form, renderable, out, **kwargs):

        fmtmap = renderer.createFormatMap(form, renderable, **kwargs)

        print >> out, get_template('reset')(control=renderable, fmtmap=fmtmap)
Пример #55
0
 def get(self):
     data = {"page": "write"}
     self.response.write(get_template('calendar.html').render(data))
Пример #56
0
    def get(self, year, month):
        Settings.get()  #Force email address update...

        now = datetime.datetime.now()
        if not year:
            last_post = Post.query().order(-Post.date).get()
            if last_post:
                year, month = last_post.date.year, last_post.date.month
            else:
                year, month = now.year, now.month
        else:
            year, month = int(year), int(month)

        from_date = datetime.date(year, month, 1)

        to_month = month + 1
        to_year = year
        if to_month == 13:
            to_month = 1
            to_year += 1

        to_date = datetime.date(to_year, to_month, 1)
        posts = [
            p for p in Post.query(
                ndb.AND(Post.date >= from_date, Post.date < to_date)).order(
                    -Post.date).fetch()
        ]
        month_name = from_date.strftime('%B %Y')

        #Get month list
        months = PostCounter.get().months[:]

        def cmp_months(a, b):
            if a.year != b.year:
                return cmp(a.year, b.year)
            else:
                return cmp(a.month, b.month)

        months.sort(cmp_months)

        archive = []

        next_link, prev_link = None, None

        for i, m in enumerate(months):
            date = datetime.date(m.year, m.month, 1)
            descr = '%s, %s posts' % (date.strftime('%B %Y'), m.count)
            value = date.strftime('%Y-%m')
            archive.append((value, descr, m.year == year and m.month == month))
            if m.year == year and m.month == month:
                if i != 0:
                    prev_link = '/past/%s' % datetime.date(
                        months[i - 1].year, months[i - 1].month,
                        1).strftime('%Y-%m')

                if i < len(months) - 1:
                    next_link = '/past/%s' % datetime.date(
                        months[i + 1].year, months[i + 1].month,
                        1).strftime('%Y-%m')

        if not archive:
            archive.append(('', '%s, 0 posts' % now.strftime('%B %Y'), False))

        data = {
            "page": "past",
            "posts": posts,
            "month": month_name,
            "archive": archive,
            "next": next_link,
            "prev": prev_link
        }
        self.response.write(get_template('past.html').render(data))