Ejemplo n.º 1
0
    def _prime(self, app):
        _DocHTMLPage._prime(self, app)
        dt = self.findAttr("contentName")
        if not dt in self.namespace:
            if self.fileext is not None:
                filepath = os.path.splitext(os.path.join(
                    self.src))[0] + self.fileext
            else:
                filepath = self.src

            try:
                s = codecs.open(os.path.join(filepath), "r", "utf-8").read()
            except UnicodeDecodeError:
                s = codecs.open(os.path.join(filepath), "r", "latin-1").read()

            if self.fileext is not None and self.fileext.lower() in [
                    ".md", ".markdown", ".mdtext"
            ]:
                self.namespace[dt] = template.Template(markup.Markdown(), s)
            elif self.fileext is not None and (self.fileext).lower() in [
                    ".rst", ".rest", ".rstext"
            ]:
                self.namespace[dt] = template.Template(markup.RST(), s)
            else:
                self.namespace[dt] = template.Template(self.findAttr("markup"),
                                                       s)
            self.namespace[dt].name = self.src
Ejemplo n.º 2
0
def execute(action, parameters):
    """ wrapper for inline functions

    :param action: action object ( processhandler.Action type )
    :param parameters: parameter string
    :return: status ( string )
    """
    if action.command == 'template.reload':
        # generate template
        tmpl = template.Template(action.root_dir)
        conf = config.Config(action.config)
        tmpl.set_config(conf.get())
        # XXX backwards-compat for '.' syntax, remove post-17.1
        parameters = parameters.replace('.', '/')
        filenames = tmpl.generate(parameters)

        del conf
        del tmpl

        # send generated filenames to syslog
        if filenames is not None:
            for filename in filenames:
                syslog.syslog(syslog.LOG_DEBUG,
                              ' %s generated %s' % (parameters, filename))
            return 'OK'
        else:
            return 'ERR'
    elif action.command == 'template.list':
        # traverse all installed templates and return list
        # the number of registered targets is returned between []
        tmpl = template.Template(action.root_dir)
        all_templates = tmpl.list_modules()
        retval = []
        for tag in sorted(all_templates.keys()):
            template_name = '%s [%d]' % (tag,
                                         len(all_templates[tag]['+TARGETS']))
            retval.append(template_name)

        del tmpl

        return '\n'.join(retval)
    elif action.command == 'configd.actions':
        # list all available configd actions
        from processhandler import ActionHandler
        act_handler = ActionHandler()
        actions = act_handler.list_actions(['message', 'description'])

        if unicode(parameters).lower() == 'json':
            import json
            return json.dumps(actions)
        else:
            result = []
            for action in actions:
                result.append('%s [ %s ]' %
                              (action, actions[action]['description']))

            return '\n'.join(result)

    return 'ERR'
Ejemplo n.º 3
0
 def __call__(self, str):
     parts = self.parse(str)
     links = []
     for i in parts:
         links.append(
             dict(
                 title=template.Template(self.markup, i["title"]),
                 body=template.Template(self.markup, i["body"])
                 if i["body"] else None,
                 link=i["link"],
             ))
     t = template.Template(
         self.markup,
         file(utils.data.path("resources/links.html")).read(),
         links=links)
     return unicode(t)
Ejemplo n.º 4
0
def loginerror(ctx, resp):
	ctx.unrel_time()
	to = ctx.model.get_template("login-error.tmpl", False)
	if not to:
		resp.error("Your login attempt was unsuccessful. Please try again. (We apologize for the terseness here, but our normal friendly login failure page is broken.)")
	else:
		resp.html(template.Template(to).render(ctx))
Ejemplo n.º 5
0
def friend(fname):
    name = request.COOKIES.get('name', '')
    password = request.COOKIES.get('password', '')
    (status, message) = DB_SERVER.listFriends(name, password)
    if status == 'failure':
        redirect('/loginscreen')
    (status2, message2) = DB_SERVER.listStatusUser(name, password, fname, 25)
    if status2 == 'failure':
        redirect('/loginscreen')
    friends = []
    for i in message:
        lst = {'href': 'http://localhost:8080/friend/' + i, 'name': i}
        friends.append(lst)
    status = []
    for i in message2:
        lst = {'status': i}
        status.append(lst)
    f = open('friend-page.template', 'r')
    lines = f.read()
    t = template.Template(lines)
    data = {
        'title': title,
        'subtitle': subtitle,
        'friend': fname,
        'updates': status,
        'friends': friends,
        'links': links
    }
    return t.render(data)
Ejemplo n.º 6
0
def synd_gen(context, tmpl):
    to = context.model.get_template(tmpl)
    res = []
    sz = 0
    maxsz = get_feedmax(context)
    rootpath = context.page.me().path
    if rootpath == '':
        rprefl = 0
    else:
        rprefl = len(rootpath) + 1
    for ts, path in _fillpages(context):
        np = context.model.get_page(path)
        nc = context.clone_to_page(np)
        nc.setvar('relname', path[rprefl:])
        rdir = np.curdir().path[rprefl:]
        if rdir:
            nc.setvar('reldir', rdir)
        t = template.Template(to).render(nc)
        sz += len(t)
        res.append(t)
        context.newtime(nc.modtime)
        # Update for directory parent timestamp too.
        pdir = np.parent()
        context.newtime(pdir.modstamp)
        # And look for size limits. Note that we may go over
        # them, because we allow one entry's worth of slop;
        # this simplifies some cases.
        if maxsz and sz >= maxsz:
            break
    return ''.join(res)
Ejemplo n.º 7
0
def execute(action, parameters):
    """ wrapper for inline functions

    :param action: action object ( processhandler.Action type )
    :param parameters: parameter string
    :return: status ( string )
    """
    if action.command == 'template.reload':
        import template
        import config
        tmpl = template.Template(action.root_dir)
        conf = config.Config(action.config)
        tmpl.setConfig(conf.get())
        filenames = tmpl.generate(parameters)

        # send generated filenames to syslog
        for filename in filenames:
            syslog.syslog(syslog.LOG_DEBUG, ' %s generated %s' % (parameters, filename))

        del conf
        del tmpl

        return 'OK'

    return 'ERR'
Ejemplo n.º 8
0
def showcomments(context):
    """Display all of the comments for the current page (if any), using the
	template _comment/comment.tmpl_ for each in succession."""
    if not context.model.comments_on():
        return ''
    # Have I mentioned recently that if you can't see a page you can't
    # see its comments either?
    if not context.page.access_ok(context):
        return ''
    cl = context.model.get_commentlist(context.page)
    if not cl:
        return ''
    # We don't really care too much about the *name* of the comments.
    coms = [context.model.get_comment(context.page, z) for z in cl]
    coms = [z for z in coms if z]
    if not coms:
        return ''
    # Sort into time order.
    coms.sort(key=lambda x: x.time)

    # We display using a method similar to blogdir; clone context,
    # set magic variable, render new template.
    to = context.model.get_template("comment/comment.tmpl")
    context.newtime(to.timestamp())
    res = []
    for c in coms:
        nc = context.clone()
        context.newtime(c.time)
        set_com_vars(nc, c)

        res.append(template.Template(to).render(nc))
        context.newtime(nc.modtime)
    return ''.join(res)
Ejemplo n.º 9
0
def loginscreen():
    ##    return 'Hello'
    f = open('login-page.template', 'r')
    lines = f.read()
    t = template.Template(lines)
    data = {'title': title, 'subtitle': subtitle, 'links': links}
    return t.render(data)
Ejemplo n.º 10
0
def blogview(context):
    """Generate a Blog rendering of the current directory: all
	descendant real pages, from most recent to oldest, possibly
	truncated at a day boundary if there's 'too many', and sets
	up information for blog navigation renderers. Each
	displayed page is rendered with the _blog/blogentry.tmpl_
	template. Supports VirtualDirectory restrictions."""
    if context.page.type != "dir":
        return ''
    if not context.page.displayable():
        raise derrors.IntErr("undisplayable directory page")

    # This automatically applies restrictions.
    dl = context.cache_page_children(context.page)
    if not dl:
        return ''
    dl = clipDown(context, dl)

    # For each file, clone the context, set the current page to
    # it (!), and render it with the blogentry template.
    to = context.model.get_template("blog/blogentry.tmpl")

    # Set up our rolling storage. We can't hook directly onto
    # the context, because we drop the context after every
    # entry. So we write our own dictionary into the context.
    context.setvar(rollvar, {})
    res = []
    rootpath = context.page.me().path
    dupDict = {}
    for ts, path in dl:
        # Skip redirects and other magic files.
        # We go whole hog and drop anything that is not a real page,
        # which subsumes both redirect pages and non-displayable
        # pages. Since attempting to render a non-displayable page
        # is a fatal internal error, we must drop them before we
        # go to the template.
        np = context.model.get_page(path)
        if not np.realpage() or np.is_util():
            continue
        # Suppress multiple occurrences of the same page as
        # may happen with, eg, hardlinks. Note that this is
        # slightly questionable; macros mean that a file's
        # rendering output may depend on not just its contents
        # but its position in the file hierarchy. We don't
        # care.
        pageid = np.identity()
        if pageid in dupDict:
            continue
        else:
            dupDict[pageid] = True
        # Note: we do not reset the view type, because we do
        # not render through the interface that cares; we go
        # straight to template.
        nc = context.clone_to_page(np)
        nc.setvar('relname', path[len(rootpath) + 1:])
        res.append(template.Template(to).render(nc))
        context.newtime(nc.modtime)
    return ''.join(res)
    def feature_extraction_longitudinal(self, img_file):
        block_size = 16

        img = io.imread(img_file)
        #print img.shape
        img = preprocessing.adjust_image_size(img, block_size)
        h, w = img.shape
        texture_img = preprocessing.FastCartoonTexture(img,
                                                       sigma=2.5,
                                                       show=False)

        contrast_img_guassian = preprocessing.local_constrast_enhancement_gaussian(
            img)

        mask = get_maps.get_quality_map_intensity(img)
        #show.show_mask(mask, img, fname=None, block=True)
        quality_map, dir_map, fre_map = get_maps.get_quality_map_dict(
            texture_img,
            self.dict_all,
            self.dict_ori,
            self.dict_spacing,
            block_size=16,
            process=False)

        enh_constrast_img = filtering.gabor_filtering_pixel(
            contrast_img_guassian,
            dir_map + math.pi / 2,
            fre_map,
            mask=np.ones((h, w), np.int),
            block_size=16,
            angle_inc=3)

        mnt = self.minu_model.run(img, minu_thr=0.2)

        #show.show_minutiae(img,mnt)
        des = descriptor.minutiae_descriptor_extraction(img,
                                                        mnt,
                                                        self.patch_types,
                                                        self.des_models,
                                                        self.patchIndexV,
                                                        batch_size=128)

        blkH, blkW = dir_map.shape

        minu_template = template.MinuTemplate(h=h,
                                              w=w,
                                              blkH=blkH,
                                              blkW=blkW,
                                              minutiae=mnt,
                                              des=des,
                                              oimg=dir_map,
                                              mask=mask)

        rolled_template = template.Template()
        rolled_template.add_minu_template(minu_template)

        return rolled_template, texture_img, enh_constrast_img
Ejemplo n.º 12
0
    def feature_extraction_single_rolled(self, img_file):
        block_size = 16

        if not os.path.exists(img_file):
            return None
        img = io.imread(img_file)
        h, w = img.shape
        mask = get_maps.get_quality_map_intensity(img)
        #if np.max(mask) == 0:
        #    print img_file
        #return None
        start = timeit.default_timer()
        mnt = self.minu_model.run_whole_image(img, minu_thr=0.2)
        stop = timeit.default_timer()
        minu_time = stop - start
        # show.show_minutiae(img, mnt, mask=mask, block=True, fname=None)
        # show.show_minutiae(img,mnt)

        # start = timeit.default_timer()
        des = descriptor.minutiae_descriptor_extraction(
            img,
            mnt,
            self.patch_types,
            self.des_models,
            self.patchIndexV,
            batch_size=256,
            patch_size=self.patch_size)
        # stop = timeit.default_timer()
        # des_time = stop - start
        print minu_time  #, des_time
        #texture_img = preprocessing.FastCartoonTexture(img, sigma=2.5, show=False)

        dir_map, _ = get_maps.get_maps_STFT(img,
                                            patch_size=64,
                                            block_size=block_size,
                                            preprocess=True)
        #stop = timeit.default_timer()

        blkH = h // block_size
        blkW = w // block_size
        # dir_map = np.zeros((blkH,blkW))
        # print stop - start
        #blkH, blkW = dir_map.shape

        minu_template = template.MinuTemplate(h=h,
                                              w=w,
                                              blkH=blkH,
                                              blkW=blkW,
                                              minutiae=mnt,
                                              des=des,
                                              oimg=dir_map,
                                              mask=mask)

        rolled_template = template.Template()
        rolled_template.add_minu_template(minu_template)

        return rolled_template
Ejemplo n.º 13
0
 def render(self, *args, **kwargs):
     pages = []
     for i in state.application.root.preOrder():
         if i.structural and not i.internal:
             pages.append(i)
     t = template.Template(
         None,
         file(utils.data.path("resources/sitemap.xml")).read(),
         pages=pages)
     return unicode(t)
Ejemplo n.º 14
0
def errortitle(context):
    """Generate the title for an error from a template in _errors/_,
	if the template exists; otherwise uses a default. Only usable
	during generation of an error page."""
    if ":error:error" not in context:
        return ''
    (etype, to) = errorTemplate(context, "title")
    if to:
        return template.Template(to).render(context)
    elif etype in title_map:
        return title_map[etype] % context[":error:code"]
    else:
        return default_title % context[":error:code"]
Ejemplo n.º 15
0
    def __unicode__(self):
        with utils.InDir(os.path.dirname(self.src)):
            if self.post.url:
                title = html.A(self.post.title, href=self.post.url)
            else:
                title = model.LinkTo(self.post)
            posttime = self.post.time.strftime("%d %B %Y")
            links = Links(self.post.findAttr("markup"))
            postbody = template.Template(self.post.findAttr("markup"),
                                         self.post.data,
                                         links=links)
            postfixes = self.postfixes
            t = template.Template(
                None,
                file(utils.data.path("resources/post.html")).read(),
                title=title,
                posttime=posttime,
                postdata=postbody,
                by=self.post.by,
                postfixes=[i() for i in postfixes])

            return unicode(t)
Ejemplo n.º 16
0
 def _getLayoutComponent(self, attr):
     if attr in self.namespace:
         r = self.namespace[attr]
     else:
         r = model.HTMLPage._getLayoutComponent(self, attr)
     base = None
     if self.src:
         base = os.path.dirname(self.src)
     with utils.InDir(base or "."):
         if utils.isStringLike(r) and (attr
                                       not in self._verbatimComponents):
             return template.Template(self.findAttr("markup"), unicode(r))
         else:
             return r
Ejemplo n.º 17
0
    def training(self):
        name = self.training_name_input.text()
        text = "Trained.."

        for x in self.recognition.templates:
            if x.name == name:
                text = "Already trained.."
                break

        points = self.draw_widget.points

        temp = template.Template(name, points)
        self.recognition.addTemplate(temp)
        self.trained_label.setText(text)
Ejemplo n.º 18
0
def errorbody(context):
    """Generates the body for an error page from a template in
	_errors/_, if the template exists; otherwise uses a default.
	Only usable during generation of an error page."""
    if ":error:error" not in context:
        return ''
    (etype, to) = errorTemplate(context)
    if to:
        return template.Template(to).render(context)
    elif etype in body_map:
        return default_body % (context[":error:code"], body_map[etype])
    else:
        # Should we try to generate a better message?
        return default_body % (context[":error:code"],
                               'An internal error has occurred.')
Ejemplo n.º 19
0
def error(error, context, resp, code=404):
    context.setvar(":error:error", error)
    context.setvar(":error:code", "%d" % code)
    context.unrel_time()
    to = context.model.get_template("error.tmpl", False)
    if to:
        res = template.Template(to).render(context)
    else:
        etitle = errortitle(context)
        ebody = errorbody(context)
        res = default_error % (etitle, ebody)
    # helpful reminder to cks at 2am: we really must call error,
    # not html.
    resp.error(res, code)
    return resp
Ejemplo n.º 20
0
 def __init__(self, tabs, args, db):
     self.tabs = tabs
     self.args = args
     self.db = db
     self.lastDirection = None
     self.nextLastOffset = None
     self.lastOffset = None
     self.lastElapsed = None
     self.lastAmplitude = None
     self.lastSamplesSinceBoot = None
     self.nextLastSamplesSinceBoot = None
     self.mostRecentTemplateTimestamp = None
     # we use python arrays here since we do not know the final size in advance
     # and they are more time efficient for appending than numpy arrays (but
     # less space efficient)
     self.periods = []
     self.swings = []
     # initialize plot display if requested
     if self.args.show_plots:
         self.fig = plt.figure(figsize=(8, 8))
         plt.ion()
         plt.show()
         self.plotx = numpy.arange(self.args.nsamples)
     # load template if requested
     if self.args.load_template is not None:
         if self.args.physical:
             raise RuntimeError(
                 'Options --physical and --load-template cannot be combined'
             )
         if self.args.load_template == "db":
             # Load from database
             templateTuple = self.db.loadTemplate()
             templateData = templateTuple[0]
             self.mostRecentTemplateTimestamp = templateTuple[1]
         else:
             #load from file specified
             templateData = numpy.transpose(
                 numpy.loadtxt(self.args.load_template))
         try:
             self.template = template.Template(
                 templateData, self.mostRecentTemplateTimestamp)
         except IndexError:
             self.template = None
             # Output zeroes
     else:
         self.template = None
Ejemplo n.º 21
0
def post(context, resp):
    # Not even an empty 'comment' data-field supplied means that
    # this is a hand-crafted bogus request.
    comdata = context.getviewvar("comment")
    if comdata is None:
        return False
    whois = context.getviewvar("whois")
    whourl = context.getviewvar("whourl")

    # We immediately disallow empty comments.
    #comdata = comtrim(comdata)
    if not comdata:
        context.setvar(":comment:post", "nocomment")
    elif context.getviewvar("name"):
        context.set_error("name field set in comment post: name %s, post %s" %
                          (repr(context.getviewvar("name")), repr(comdata)))
        context.setvar(":comment:post", "bad")
    elif hasbadchars(comdata):
        context.set_error("bad characters in comment post: %s" % repr(comdata))
        context.setvar(":comment:post", "badchars")
    elif bannedcontent(comdata):
        # this is currently deliberately uninformative.
        context.set_error("banned content in comment post: %s" % repr(comdata))
        context.setvar(":comment:post", "bad")
    # disabled, misfired.
    #elif check_dnsbl(context):
    #	# this is also deliberately uninformative.
    #	context.set_error("comment POST from a zen.spamhaus.org-listed IP. Content is: %s" % repr(comdata))
    #	context.setvar(":comment:post", "bad")
    else:
        # post_comment() does permissions checking itself,
        # and the caller has already done it too, so we don't
        # do it a *third* time; we just go straight.
        res = context.model.post_comment(comdata, context, whois, whourl)
        if res:
            context.setvar(":comment:post", "good")
        else:
            context.setvar(":comment:post", "bad")
        comment_posted(context)

    # :comment:post now holds what happened, so we let the top
    # level template dispatch off it to figure out what to do.
    to = context.model.get_template("comment/posting.tmpl")
    resp.html(template.Template(to).render(context))
    context.unrel_time()
    return True
Ejemplo n.º 22
0
 def __init__(self):
     self.template = template.Template(template)
     arg_parser = ArgumentParser()
     arg_parser.add_argument("-u", "--url", dest="url")
     args = arg_parser.parse_args()
     if args.url is None:
         print("Вы забыли ввести URL")
     else:
         page = url.Url(args.url)
         data = page.get_content()
         path = page.parse_url()
         current_template = self.template.get_template()
         html_parser = MyHTMLParser(current_template)
         html_parser.feed(data)
         self.content = content.Content(current_template, html_parser.content)
         write_data = self.content.format_data()
         self.save_data(path, write_data)
Ejemplo n.º 23
0
  def build(self, wait_time=60):
    # Setup and build all the templates
    for tmpl in self.start_order:          
      if not self.config['templates'][tmpl]:
        sys.stderr.write('Error: no configuration found for template: ' + tmpl + '\n')
        exit(1)

      config = self.config['templates'][tmpl]
      
      # Create the template. The service name and version will be dynamic once the new config format is implemented
      utils.status('Building template %s' % (tmpl))
      tmpl_instance = template.Template(tmpl, config, 'service', '0.1')
      tmpl_instance.build()


      self.templates[tmpl] = tmpl_instance

      # We'll store the running instances as a dict under the template
      self.containers[tmpl] = {}

    # Start the envrionment
    for tmpl in self.start_order:            
      self._handleRequire(tmpl, wait_time)

      tmpl_instance = self.templates[tmpl]
      config = self.config['templates'][tmpl]
      
      # If count is defined in the config then we're launching multiple instances of the same thing
      # and they'll need to be tagged accordingly. Count only applies on build.
      count = tag_name = 1
      if 'count' in config:
        count = tag_name = config['count']  
      
      while count > 0:      
        name = tmpl
        if tag_name > 1:
          name = name + '__' + str(count)

        utils.status('Launching instance of template %s named %s' % (tmpl, name))      
        instance = tmpl_instance.instantiate(name)
        instance.run()

        self.containers[tmpl][name] = instance
        
        count = count - 1
Ejemplo n.º 24
0
def blogdir(context):
    """Generate a BlogDir rendering of the current directory:
	display all real pages in the current directory from most
	recent to oldest, rendering each with the template
	_blog/blogdirpage.tmpl_. Supports VirtualDirectory restrictions."""
    if context.page.type != "dir":
        return ''
    if not context.page.displayable():
        raise derrors.IntErr("undisplayable directory page")
    dl = context.page.children("file")
    if not dl:
        return ''
    # Boil it down to just files, in modtime order.
    # (Technically this is real files: displayable, non-redirect.)
    dl = [z for z in dl if z.realpage() and not z.is_util()]
    # This directory might have nothing.
    if not dl:
        return ''

    # Apply restrictions, backwardly.
    # Because restrictions are designed to be hugely scalable, they
    # want the output we'd get from page.descendants().
    if pageranges.is_restriction(context):
        tl = pageranges.filter_files(context,
                                     [(z.timestamp, z.path) for z in dl])
        if not tl:
            return ''
        dl = [context.model.get_page(z[1]) for z in tl]
    else:
        dl.sort(key=lambda x: x.timestamp, reverse=True)

    # For each file, clone the context, set the current page to
    # it (!), and render it with the blogentry template.
    to = context.model.get_template("blog/blogdirpage.tmpl")
    context.setvar(rollvar, {})
    res = []
    for page in dl:
        # Note: we do not reset the view type, because we do
        # not render through the interface that cares; we go
        # straight to template.
        nc = context.clone_to_page(page)
        res.append(template.Template(to).render(nc))
        context.newtime(nc.modtime)
    return ''.join(res)
Ejemplo n.º 25
0
  def load(self, filename='envrionment.yml'):
    self.log.info('Loading environment from: %s', filename)      
    
    with open(filename, 'r') as input_file:
      self.config = yaml.load(input_file)

      self.state = self.config['state']
      
      for tmpl in self.config['templates']:
        # TODO fix hardcoded service name and version
        self.templates[tmpl] = template.Template(tmpl, self.config['templates'][tmpl], 'service', '0.1')
        self.containers[tmpl] = {}

      self.start_order = utils.order(self.config['templates'])
      for container in self.config['containers']:
        tmpl = self.config['containers'][container]['template']
      
        self.containers[tmpl][container] = Container(container, self.config['containers'][container], 
          self.config['templates'][tmpl]['config'])
Ejemplo n.º 26
0
def execute(action, parameters):
    """ wrapper for inline functions

    :param action: action object ( processhandler.Action type )
    :param parameters: parameter string
    :return: status ( string )
    """
    if action.command == 'template.reload':
        import template
        import config
        tmpl = template.Template(action.root_dir)
        conf = config.Config(action.config)
        tmpl.setConfig(conf.get())
        filenames = tmpl.generate(parameters)

        # send generated filenames to syslog
        for filename in filenames:
            syslog.syslog(syslog.LOG_DEBUG,
                          ' %s generated %s' % (parameters, filename))

        del conf
        del tmpl

        return 'OK'
    elif action.command == 'configd.actions':
        # list all available configd actions
        from processhandler import ActionHandler

        actHandler = ActionHandler()
        actions = actHandler.listActions(['message', 'description'])

        if unicode(parameters).lower() == 'json':
            import json
            return json.dumps(actions)
        else:
            result = []
            for action in actions:
                result.append('%s [ %s ]' %
                              (action, actions[action]['description']))

            return '\n'.join(result)

    return 'ERR'
Ejemplo n.º 27
0
def convert(problem, options=None):
    if options == None:
        options = ConvertOptions()

    problem = os.path.realpath(problem)
    problembase = os.path.splitext(os.path.basename(problem))[0]
    destfile = Template(options.destfile).safe_substitute(problem=problembase)

    texfile = problem

    # Set up template if necessary
    templ = None
    if os.path.isdir(problem):
        templ = template.Template(problem,
                                  language=options.language,
                                  title=options.title,
                                  solution=options.solution)
        texfile = templ.get_file_name()

    origcwd = os.getcwd()

    os.chdir(os.path.dirname(texfile))
    redirect = ''
    params = '-interaction=nonstopmode'
    if options.quiet:
        redirect = '> /dev/null'
    if options.nopdf:
        params = params + ' -draftmode'

    status = os.system('pdflatex %s %s %s' % (params, texfile, redirect))
    if os.WIFEXITED(status) and os.WEXITSTATUS(status) == 0:
        status = os.system('pdflatex %s %s %s' % (params, texfile, redirect))

    os.chdir(origcwd)

    if not options.nopdf:
        os.rename(os.path.splitext(texfile)[0] + '.pdf', destfile)

    if templ != None:
        templ.cleanup()

    return os.WIFEXITED(status) and os.WEXITSTATUS(status) == 0
Ejemplo n.º 28
0
  def POST(self):
      try:
          webData = web.data()
          print "Handle Post webdata is ", webData
 #后台打日志
          recMsg = receive.parse_xml(webData)
          if isinstance(recMsg, receive.Msg):
              toUser = recMsg.FromUserName
              fromUser = recMsg.ToUserName
              if recMsg.MsgType == 'text':
                  content = "test"
                  replyMsg = reply.TextMsg(toUser, fromUser, content)
                  return replyMsg.send()
              if recMsg.MsgType == 'image':
                  mediaId = recMsg.MediaId
                  replyMsg = reply.ImageMsg(toUser, fromUser, mediaId)
                  return replyMsg.send()
              else:
                  return reply.Msg().send()
          if isinstance(recMsg, receive.EventMsg):
              print("event")
              if recMsg.Event == 'CLICK':
                  if recMsg.Eventkey == 'mpGuide':
                      toUser = recMsg.FromUserName
                      data = """
                      {
                          "touser":"******",
                          "template_id":"GVnSlVUMHDAr6uNtd7dJhnUr_Y0qEopR7SGwzyGVpto",
                          "url":"http://www.mej.cn",         
                          "data":{
                          }
                      }
                      """ % toUser
                      token = basic.Basic().get_access_token()
                      reply_template = template.Template().send(data, token)
                      return data
          else:
              print "暂且不处理"
              return "success"
      except Exception, Argment:
          print(Argment)
          return Argment
Ejemplo n.º 29
0
def connector(plugin_path=None):

    # We load the HCLI template in memory to reduce disk io
    config.set_plugin_path(plugin_path)
    config.parse_template(template.Template())

    # We setup the HCLI Connector
    server = falcon.API()
    server.add_route(home.HomeController.route, api.HomeApi())
    server.add_route(document.DocumentController.route, api.DocumentApi())
    server.add_route(command.CommandController.route, api.CommandApi())
    server.add_route(option.OptionController.route, api.OptionApi())
    server.add_route(execution.ExecutionController.route, api.ExecutionApi())
    server.add_route(finalexecution.FinalGetExecutionController.route,
                     api.FinalExecutionApi())
    server.add_route(finalexecution.FinalPostExecutionController.route,
                     api.FinalExecutionApi())
    server.add_route(parameter.ParameterController.route, api.ParameterApi())

    return server
Ejemplo n.º 30
0
 def updateTemplate(self):
     """
     Checks the database for a newer version of the template.  If one exists, replace
     self.template with it and replace self.mostRecentTemplateTimestamp with its
     timestamp
     """
     if self.args.verbose:
         print "Attempting to Update Template"
     if self.args.load_template == "db":
         # Try and create a template if one doesn't exist
         if self.template is None:
             # Try and create one
             dataTuple = self.db.loadData()
             data = dataTuple[0]
             timestamp = dataTuple[1]
             if len(data.shape) != 1:
                 if self.args.verbose:
                     print "Bad data shape!"
                 return
             # loop over data frames
             nframe = len(data) / (1 + self.args.nsamples)
             if (nframe < self.args.fetch_limit):
                 if self.args.verbose:
                     print "Insufficient Data to update template!"
                 return
             if not (self.args.max_frames == 0
                     or nframe <= self.args.max_frames):
                 nframe = self.args.max_frames
             frames = data[:nframe * (1 + self.args.nsamples)].reshape(
                 (nframe, 1 + self.args.nsamples))
             templateSpline = buildSplineTemplate(frames, self.args)
             # Save to database as array of ordered pairs (arrays)
             self.db.saveTemplate(templateSpline, timestamp)
         # Look for newer template from database
         templateTuple = self.db.loadTemplate()
         templateData = templateTuple[0]
         templateTimestamp = templateTuple[1]
         if templateTimestamp != self.mostRecentTemplateTimestamp:
             self.template = template.Template(templateData,
                                               templateTimestamp)
             self.mostRecentTemplateTimestamp = templateTimestamp