示例#1
0
	def __add_all_templates__(self) :
		#nominal
		if self.name.find('DATA')!=-1 or self.name.find('JES') != -1 or self.name.find('JER') != -1 :
			self.all_templates.append(template(self.name,self.formatted_name))
		else :
			self.all_templates.append(template(self.name,self.formatted_name+', nominal'))
		if self.name.find('JES') == -1 and self.name.find('JER') == -1 :
			if self.step == 'initial' :
				#simple systematics up/down
				for i in range(len(self.simple_systematic_reweights_arrays)/3) :
					sysname = simple_systematics_dists[i]
					self.all_templates.append(template(self.name+'__'+sysname+'__up',self.formatted_name+', '+sysname+' up'))
					self.all_templates.append(template(self.name+'__'+sysname+'__down',self.formatted_name+', '+sysname+' down'))
				#PDF systematics up/down
				for i in range(1,(len(self.pdf_reweight_array)-1)/2) :
					self.all_templates.append(template(self.name+'__pdf_lambda_'+str(i)+'__up',self.formatted_name+', PDF lambda'+str(i)+' up'))
					self.all_templates.append(template(self.name+'__pdf_lambda_'+str(i)+'__down',self.formatted_name+', PDF lambda'+str(i)+' down'))
			if self.step != 'final' :
				#fit parameters up/down
				for i in range(len(self.fit_parameter_names)) :
					self.all_templates.append(template(self.name+'__par_'+self.fit_parameter_names[i]+'__up',self.formatted_name+', '+self.fit_parameter_names[i]+' up'))
					self.all_templates.append(template(self.name+'__par_'+self.fit_parameter_names[i]+'__down',self.formatted_name+', '+self.fit_parameter_names[i]+' down'))
				#NTMJ fit parameters up/down
				if self.name.find('ntmj')!=-1 :
					self.all_templates.append(template(self.name+'__fit__up',self.formatted_name+', NTMJ fit error up'))
					self.all_templates.append(template(self.name+'__fit__down',self.formatted_name+', NTMJ fit error down'))
示例#2
0
def run():
    defaultmech = "%s/mapping/cb05cl_ae6_aq.csv" % os.path.dirname(__file__)
    parser = ArgumentParser(description = "Usage: %prog [-tq] \n"+(" "*16)+" [-i <init name>] [-f <final name>] <yamlfile>")
    parser.add_argument("-t", "--template", dest = "template", action = "store_true", default = False, help="Output template on standard out (configurable with -m and -c")

    parser.add_argument("-v", "--verbose", dest = "verbose", action = "count", default = 0, help = "extra output for debugging")
    
    paths = glob(os.path.join(os.path.dirname(__file__), 'mapping', '*_*.csv'))
    mechanisms = ', '.join(['_'.join(path.split('/')[-1].split('_')[:])[:-4] for path in paths])
    parser.add_argument("-c", "--configuration", dest="configuration", default = None,
                        help = "Chemical mechanisms: %s (for use with -t)" % mechanisms)
    parser.add_argument('configfile')
    options = parser.parse_args()
    args = [options.configfile]
    if options.template:
        from template import template
        if options.configuration is None:
            warn("Using default mechanism: %s" % defaultmech)
            options.configuration = defaultmech
        else:
            if os.path.exists(options.configuration):
                pass
            else:
                options.configuration = "%s/mapping/%s.csv" % (os.path.dirname(__file__), options.configuration)
                if not os.path.exists(options.configuration):
                    raise IOError('Cannot find file %s; must be either you own file or in %s' % (options.configuration, mechanisms))
        print template(options.configuration)
        parser.exit()
    if len(args)<1:
        parser.error(msg="Requires a yaml file as an argument.  For a template use the -t option.  The template will be output to the stdout.")
    else:
        yamlpath=args[0]
        from load import loader
        from process import process
        outf = process(config = loader(yamlpath), verbose = options.verbose)
示例#3
0
 def post(self):
     keys = [
         'name', 'role', 'email', 'phone', 'availability', 'tags', 'details'
     ]
     try:
         mentor = Mentor()
         for key in keys:
             val = self.request.get(key)
             if key == 'tags':
                 val = [tag.strip().lower() for tag in val.split(',')]
             setattr(mentor, key, val)
         mentor.put()
         first_name = mentor.name.split(' ')[0] if mentor.name else 'mentor'
         self.response.write(
             template("mentor_signup.html", {
                 "show_confirmation": True,
                 "first_name": first_name
             }))
     except datastore_errors.BadValueError as e:
         print "MENTOR SIGNUP ERROR: {0}".format(e)
         self.response.write(
             template("mentor_signup.html", {
                 "error":
                 "There's an invalid or missing field on your form!"
             }))
示例#4
0
	def get(self, tab='info'):
		params = {}

		params['bigboard'] = self.request.get('bigboard')
		
		if tab == 'info':
			feed = []
			for msg in Message.query(Message.show_in_day_of == True).order(-Message.added).fetch(limit=20):
				feed.append({"date": msg.added, "type": "message", "message": msg})
			for post in Post.query(Post.feed == 'twitter/user/HackAtBrown', Post.is_reply == False).order(-Post.date).fetch(limit=20):
				feed.append({"date": post.date, "type": "tweet", "tweet": post})
			feed.sort(key=lambda x: x['date'], reverse=True)
			params['feed'] = feed[:min(len(feed), 20)]
		elif tab == 'requests':
			def request_to_dict(req):
				return {
				"name": req.requester.get().name if req.requester else None,
				"issue": req.issue,
				"tags": req.tags,
				"location": req.location,
				"time": req.created
				}
			params['requests'] = map(request_to_dict, MentorRequest.query().order(-MentorRequest.created).fetch(limit=100))

		content = template("day_of/{0}.html".format(tab), params) # TODO: security-ish stuff
		
		if self.request.get('ajax'):
			self.response.write(content)
		else:
			index_params = {
				"tab": tab,
				"tab_content": content,
				"bigboard": self.request.get('bigboard')
			}
			self.response.write(template("day_of/index.html", index_params))
示例#5
0
    def creatConfig(self):
        values = {
                'memory'     : str(self.memory),
                # 'memory'     : str(self.memory * 1024),
                'num_cpu'    : str(self.num_cpu),
                'name'       : self.vm_name,
                'image_path' : self.vm_path + self.image_name
                }

        config_path = self.vm_path+self.vm_name+'.cfg'
        template('ubuntu_xen.mustache', values, config_path)
	def send_to_email(self, email, template_args={}):
		# does the actual work of sending
		emails = [email]
		assert self.email_subject, "No email subject provided. Is email unchecked?"
		if self.email_from_template:
			html = template("emails/" + self.email_html + ".html", template_args)
		else:
			html = template_string(self.email_html, template_args)
			html = template("emails/generic.html", dict({"content": html}.items() + template_args.items()))
		subject = template_string(self.email_subject, template_args)
		send_email(html, subject, emails)
	def post(self):
		keys = ['name', 'role', 'email', 'phone', 'availability', 'tags', 'details']
		try:
			mentor = Mentor()
			for key in keys:
				val = self.request.get(key)
				if key == 'tags':
					val = [tag.strip().lower() for tag in val.split(',')]
				setattr(mentor, key, val)
			mentor.put()
			first_name = mentor.name.split(' ')[0] if mentor.name else 'mentor'
			self.response.write(template("mentor_signup.html", {"show_confirmation": True, "first_name": first_name}))
		except datastore_errors.BadValueError as e:
			print "MENTOR SIGNUP ERROR: {0}".format(e)
			self.response.write(template("mentor_signup.html", {"error": "There's an invalid or missing field on your form!"}))
		def post(self):
			hacker = Hacker()
			hacker.ip = self.request.remote_addr
			for key in hacker_keys:
				vals = self.request.get_all(key)
				val =','.join(vals)
				try:
					setattr(hacker, key, val)
				except datastore_errors.BadValueError as err:
					return self.response.write(json.dumps({"success":False, "msg" : "Register", "field" : str(err.args[0]), "newURL" : blobstore.create_upload_url('/register')}))

			if Hacker.query(Hacker.email == hacker.email).count() > 0:
				return self.response.write(json.dumps({"success":False, "msg": "Email Already Registered!"}))

			resume_files = self.get_uploads('resume')
			if len(resume_files) > 0:
					hacker.resume = resume_files[0].key()
			hacker.secret = generate_secret_for_hacker_with_email(hacker.email)
			# try:
			#		email_html = template("emails/confirm_registration.html", {"name": hacker.name.split(" ")[0], "hacker": hacker})
			#		send_email(recipients=[hacker.email], subject="You've applied to Hack@Brown!", html=email_html)
			#		hacker.post_registration_email_sent_date = datetime.datetime.now()
			# except Exception, e:
			#		pass
			hacker.put()
			name = hacker.name.title().split(" ")[0] # TODO: make it better
			confirmation_html = template("post_registration_splash.html", {"name": name, "secret": hacker.secret})
			self.response.write(json.dumps({"success": True, "replace_splash_with_html": confirmation_html}))
  def create_template(self, height, width):
    #Initialiser les minima et maxima
    min_x = height
    min_y = width
    max_x = 0
    max_y = 0
    color = ''
    for b in self.xbubbles:
      color = b['color']
      if min_x > b['x']:
        min_x = b['x']
      if min_y > b['y']:
        min_y = b['y']
      if max_x < b['x']:
        max_x = b['x']
      if max_y < b['y']:
        max_y = b['y']

    # Projection 
    for b in self.xbubbles:
      b['x'] -= min_x
      b['y'] -= min_y
    temp = template(False, width, height, '', 'blue')

    # Ecriture du template
    for b in self.xbubbles:
      w = bubble()
      w.color = 'blue'
      temp[b['x']][b['y']] = w
    return temp
示例#10
0
def play():
    cap = cv2.VideoCapture("sep/25_68351.avi")
    ms = pickle.load(open("sep/25_68351.ms", "rb"))
    nms = rollingMean(ms)
    # vis(ms, nms)
    fn = 0
    ret, iframe = cap.read()
    H, W, _ = iframe.shape
    tpl = template()
    while cap.isOpened():
        ret, frame = cap.read()
        if not ret:
            break
        fn += 1
        res, mtxR, mtxQ, Qx, Qy, Qz = cv2.RQDecomp3x3(ms[fn])
        # print mtxR
        # print mtxQ
        import ipdb

        ipdb.set_trace()
        crotMean = cv2.warpPerspective(tpl, nms[fn], (W, H))
        frame[..., 1] = cv2.bitwise_or(crotMean, frame[..., 1])
        cv2.imshow("frame", frame)
        key = cv2.waitKey(5) & 0xFF
        if key == ord("q"):
            return
	def post(self):
		if not isAdmin(): return self.redirect('/')
		audience = None if self.request.get('audience') == '' else self.request.get('audience')
		message = Message(audience=audience)
		if self.request.get('email'):
			message.email_subject = self.request.get('email-subject')
			if self.request.get('email-name'):
				message.email_from_template = True
				message.email_html = self.request.get('email-name')
			else:
				message.email_html = self.request.get('email-html')
		if self.request.get('sms'):
			message.sms_text = self.request.get('sms-text')
		if self.request.get('show-in-day-of'):
			message.day_of_html = self.request.get('day-of-html')
			message.show_in_day_of = True
		if self.request.get('test'):
			recip = self.request.get('test-recipient')
			if '@' in recip:
				message.send_to_email(recip)
				self.response.write("Sent email")
			elif len(recip) > 0:
				message.send_to_phone(recip)
				self.response.write("Sent SMS")
		else:
			message.put()
			message.kick_off()
			self.response.write(template("messages_dashboard.html", {"status": "Sent!"}))
示例#12
0
		def get(self):
			variables = {
				"registration_status": config.registration_status()
			}
			if config.registration_status() == config.REGISTRATION_OPEN:
				variables['registration_post_url'] = blobstore.create_upload_url('/register')
			self.response.write(template("index.html", variables))
    def get(self, secret):

        hacker = getHacker(secret)

        if hacker is None:
            self.redirect('/')
#            this shouldn't silently fail.  we should make a 404
            return

        status = hacker.computeStatus()
        resumeFileName = ""
        receiptsFileNames = ""

        if hacker.resume:
            resumeFileName = hackerFiles.getFileName(hacker.resume)

        if hacker.receipts and hacker.receipts[0] != None:
            receiptsFileNames = hackerFiles.getFileNames(hacker.receipts)

        name = hacker.name.split(" ")[0] # TODO: make it better

        self.response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate, pre-check=0, post-check=0"
        self.response.headers["Pragma"] = "no-cache"
        self.response.headers["Expires"] = "0"
        deadline = 7
        deadlineFull = "2/07/2015"
        if hacker.deadline:
            deadline = (hacker.deadline - datetime.datetime.now()).days
            deadlineFull = hacker.deadline.strftime("%m.%d.%y")
        if hacker.rsvpd != True and deadline < 0:
            registration.expire_hacker(hacker)
            self.redirect('/')
            return
        self.response.write(template.template("hacker_page.html", {"hacker": hacker, "status": status, "name": name, "resumeFileName" : resumeFileName, "receiptsFileNames" : receiptsFileNames, "deadline": deadline, "deadlineFull": deadlineFull}))
示例#14
0
def put(servername, ip, method):
    newserverTemplate = template.template(state.game,
                                          state.language,
                                          servername,
                                          ip=ip)
    check = False
    for i in range(10):
        try:
            if method.strip() == "sql":
                newserverTemplate.updateServerSql()
                check = True
            if method.strip() == "common":
                newserverTemplate.updateServerLib()
                check = True
            if method.strip() == "gametemplate":
                newserverTemplate.updateServerConf()
                check = True
            if method.strip() == "properties":
                newserverTemplate.updateServerProperties()
                check = True
            if method.strip() == "www":
                newserverTemplate.updateServerWww()
                check = True
            if method.strip() == "nginx":
                newserverTemplate.updateServerNginxConf()
                check = True
            break
        except:
            pass
    if not check:
        errorAdd(servername, " %s模板生成失败! " % method)
示例#15
0
    def get(self):
        if not onTeam(): return self.redirect('/')

        user = users.get_current_user()
        if not user:
          self.redirect(users.create_login_url(self.request.uri))
          return

        def formatter(person):
            JSON = {}
            key = getattr(person, 'key')
            JSON['id'] = key.urlsafe()
            JSON['kind'] = key.kind()
            JSON.update(person.asDict(['email', 'name', 'checked_in']))
            return JSON

        from models import Volunteer, Rep

        source = map(formatter, Hacker.query(Hacker.checked_in == False).fetch())
        source += map(formatter, Rep.query(Rep.checked_in == False).fetch())
        source += map(formatter, Volunteer.query(Volunteer.checked_in == False).fetch())

        total_checked_in = getTotal()

        session = models.CheckInSession()
        session.user = user.email()

        session.put()
        token = channel.create_channel(session.key.urlsafe())

        self.response.write(template("checkin.html", {"source" : json.dumps(source), 'total_checked_in' : total_checked_in, 'token' : token}))
示例#16
0
def put(servername,ip,method):
    newserverTemplate = template.template(state.game,state.language,servername,ip=ip)
    check = False
    for i in range(10):
        try:
            if method.strip() == "sql":
                newserverTemplate.updateServerSql()
                check = True
            if method.strip() == "common":
                newserverTemplate.updateServerLib()
                check = True
            if method.strip() == "gametemplate":
                newserverTemplate.updateServerConf()
                check = True
            if method.strip() == "properties":
                newserverTemplate.updateServerProperties()
                check = True
            if method.strip() == "www":
                newserverTemplate.updateServerWww()
                check = True
            if method.strip() == "nginx":
                newserverTemplate.updateServerNginxConf()
                check = True
            break
        except:
            pass
    if not check:
        errorAdd(servername," %s模板生成失败! "%method)
示例#17
0
		def get(self):
			variables = {
				"registration_status": "registration_open"
			}

			variables['registration_post_url'] = blobstore.create_upload_url('/register')
			self.response.write(template("index.html", variables))
示例#18
0
def getTemplateObj(ip,servername):
    try:
        t = template.template(state.game,state.language,servername,ip=ip)
        allTemplateObj[servername] = t
        #print ip,servername
    except Exception,e1:
        error[servername] = str(e1)
示例#19
0
def getTemplateObj(ip, servername):
    try:
        t = template.template(state.game, state.language, servername, ip=ip)
        allTemplateObj[servername] = t
        #print ip,servername
    except Exception, e1:
        error[servername] = str(e1)
示例#20
0
def get_keyserver_yaml() -> str:
    config = Config.load_from_project()

    nodes = [{
        "HOSTNAME": node.hostname,
        "DOMAIN": config.external_domain,
        "IP": node.ip,
        "KIND": node.kind,
        "SCHEDULE": "true" if node.kind == "worker" else "false"
    } for node in config.nodes]

    accounts = template.template_all("""
  - principal: {{HOSTNAME}}.{{DOMAIN}}
    group: {{KIND}}-nodes
    limit-ip: true
    metadata:
      ip: {{IP}}
      hostname: {{HOSTNAME}}
      schedule: {{SCHEDULE}}
      kind: {{KIND}}
        """.strip("\n"),
                                     nodes,
                                     load=False)

    admins = [{"PRINCIPAL": root_admin} for root_admin in config.root_admins]
    admins += [{
        "PRINCIPAL": "*****@*****.**"
    }]  # used by homeworld-ssh-checker

    accounts += template.template_all("""
  - principal: {{PRINCIPAL}}
    disable-direct-auth: true
    group: root-admins
        """.strip("\n"),
                                      admins,
                                      load=False)

    ssh_metric_nodes = [{
        "HOSTNAME": node.hostname,
        "DOMAIN": config.external_domain,
        "REALM": config.realm,
    } for node in config.nodes if node.kind == "supervisor"]

    accounts += template.template_all("""
  - principal: host/{{HOSTNAME}}.{{DOMAIN}}@{{REALM}}
    disable-direct-auth: true
    group: kerberos-accounts
        """.strip("\n"),
                                      ssh_metric_nodes,
                                      load=False)

    ksrv = {
        "SERVICEAPI": config.service_api,
        "ACCOUNTS": "".join(accounts),
        "DOMAIN": config.external_domain,
        "INTERNAL-DOMAIN": config.internal_domain
    }

    return template.template("keyserver.yaml", ksrv)
示例#21
0
def template_response(templatename, status='200 Ok',
                      header=[('Content-Type', 'text/html')],
                      **kwargs):
    """
    Return a template as HTML.
    """
    return html_response(template(templatename, **kwargs),
                         status=status,
                         header=header)
示例#22
0
def get_local_kubeconfig() -> str:
    key_path, cert_path, ca_path = access.get_kube_cert_paths()
    kconf = {
        "APISERVER": get_apiserver_default(),
        "AUTHORITY-PATH": ca_path,
        "CERT-PATH": cert_path,
        "KEY-PATH": key_path
    }
    return template.template("kubeconfig-local.yaml", kconf)
示例#23
0
文件: main.py 项目: engy98/ASW_2
 def makeTemplate(self,idTemp,subject,content,languageNum):
     from  template import template
     from  template import languageEnum
     templateLogin = template()
     templateLogin.id = idTemp
     templateLogin.subject = subject
     templateLogin.content = content
     templateLogin.language = languageEnum(languageNum)
     return templateLogin
def expire_hacker(hacker):
	if hacker.rsvpd == True or hacker.admitted_email_sent_date == None:
			#hacker has rsvp'd or was never accepted
			return
	print "Expiring " + hacker.email + " with admit date: " + str(hacker.admitted_email_sent_date)
	email = template("emails/admittance_expired.html", {"name":hacker.name.split(" ")[0]})
	send_email(recipients=[hacker.email], html=email, subject="You didn't RSVP to Hack@Brown in time...")
	deletedHacker.createDeletedHacker(hacker, "expired")
	hacker.key.delete()
示例#25
0
def addwhiteip(iplist, yx):
    if not check.checkIpList(iplist):
        raise Exception("iplist 格式不正确:%s" % iplist)
    backstageDB = gameOption("backstage_db")
    headTag = gameOption("backstage_tag")
    ismobile = gameOption("is_mobile", type='bool')
    lyWhiteIpKey = gameOption("lyWhiteIpKey")
    if ismobile:
        partnersType = 2
    else:
        partnersType = 1
    backstageIp = gameOption("backstage")
    mixservers = serverlist.serverRange(backstageDB,
                                        headTag,
                                        partnersType,
                                        "mix",
                                        backstageIp,
                                        serverlist="%s_.*" % yx)
    resultStatus = True
    if len(mixservers) == 0:
        raise Exception("没有获取到游戏列表,请确认!")
    state.servers = mixservers
    state.ignoreErrorHost = True
    ccthread.run(updateProperties, iplist, yx, lyWhiteIpKey)
    proxy_pay1_ip = gameOption("proxy_pay1_ip", default="")
    proxy_pay2_ip = gameOption("proxy_pay2_ip", default="")
    proxy_pay1 = gameOption("proxy_pay1", default="")
    proxy_pay2 = gameOption("proxy_pay2", default="")
    if proxy_pay1.strip() != "":
        proxy_pay1_ssh = ssh.ssh(proxy_pay1_ip)
        updateProxy(proxy_pay1_ssh, proxy_pay1_ip, proxy_pay1, iplist, yx,
                    lyWhiteIpKey)
    if proxy_pay2.strip() != "":
        proxy_pay2_ssh = ssh.ssh(proxy_pay2_ip)
        updateProxy(proxy_pay2_ssh, proxy_pay2_ip, proxy_pay2, iplist, yx,
                    lyWhiteIpKey)
    if len(state.errorResult) > 0:
        resultStatus = False
        print "\n", "*" * 50
        for i in state.errorResult:
            print "[%s] %s" % (i, state.errorResult[i])
    print "\n", "*" * 50
    print "更新服务器数:%d" % len(mixservers)
    print "更新失败数:%d" % len(state.errorResult)
    print "连接失败服务器数量:%d" % len(state.errorHost)
    try:
        import template
        templateObj = template.template(state.game,
                                        state.language,
                                        mixservers[0][0],
                                        ip=mixservers[0][1])
        templateObj.updateServerProperties()
        print "更新模板成功!"
    except Exception, e1:
        resultStatus = False
        print "ERROR:模板更新失败!msg:%s" % str(e1)
示例#26
0
def route_index(request):
    """
    主页的处理函数, 返回主页的响应
    """
    header = 'HTTP/1.x 210 VERY OK\r\nContent-Type: text/html\r\n'
    body = template('index.html')
    u = current_user(request)
    body = body.replace('{{username}}', u.username)
    r = header + '\r\n' + body
    return r.encode()
    def get(self):

        if not onTeam():
            logging.info("Not authorized")
            return self.redirect('/')

        isQA = envIsQA()
        isDev = envIsDev()

        self.response.write(template("dashboard.html", {"envIsDev" : isDev, "isQA" : isQA, "admin" : isAdmin(), "onTeam" : onTeam(), "logout" : users.create_logout_url('/')}))
示例#28
0
    def creatConfig(self):
        values = {
                'name'       : self.vm_name,
                'kernel'     : PATH_DOMU_KERNEL,
                'memory'     : str(self.memory * 1024),
                'num_cpu'    : str(self.num_cpu),
                'image_path' : self.vm_path + self.image_name
                }

        self.config_xml = template('apache.xml.mustache', values)
示例#29
0
    def creatConfig(self):
        values = {
            'name': self.vm_name,
            'kernel': PATH_DOMU_KERNEL,
            'memory': str(self.memory * 1024),
            'num_cpu': str(self.num_cpu),
            'image_path': self.vm_path + self.image_name
        }

        self.config_xml = template('apache.xml.mustache', values)
示例#30
0
 def post(self):
     t = self.request.get('type')
     result = None
     
     if t == 'unfetched_sources':
         result = unfetched_sources()
     elif t == 'unrefreshed_feeds':
         result = unrefreshed_feeds()
     
     self.response.write(template.template("health.html", {"result": result, "result_type": t}))
def accept_hacker(hacker):
	#print "actually accepting hacker"
	hacker.deadline = (datetime.datetime.now() + datetime.timedelta(seconds=admission_expiration_seconds()))
	if hacker.deadline > datetime.datetime(2015, 2, 7):
		hacker.deadline = datetime.datetime(2015, 2, 7)
	email = template("emails/admitted.html", {"hacker": hacker, "deadline": hacker.deadline.strftime("%m/%d/%y"), "name":hacker.name.split(" ")[0]})
	send_email(recipients=[hacker.email], html=email, subject="You got off the Waitlist for Hack@Brown!")

	hacker.admitted_email_sent_date = datetime.datetime.now()
	hacker.put()
	memcache.add("admitted:{0}".format(hacker.secret), "1", memcache_expiry)
示例#32
0
    def render_text(self,
                    text,
                    vars=None,
                    env=None,
                    dirs=None,
                    default_template=None):
        vars = vars or {}
        env = env or self.get_view_env()
        dirs = dirs or self.template_dirs

        return template.template(text, vars, env, dirs, default_template)
示例#33
0
def gen_kube_specs(output_dir: str) -> None:
    if not os.path.isdir(output_dir):
        os.mkdir(output_dir)
    clustered, = keycheck(yaml.safe_load(
        resource.get_resource("clustered/list.yaml")),
                          "clustered",
                          validator=lambda _, x: type(x) == list)
    vars = get_kube_spec_vars()
    for configname in clustered:
        templated = template.template("clustered/%s" % configname, vars)
        util.writefile(os.path.join(output_dir, configname),
                       templated.encode())
示例#34
0
	def post(self):
		service = self.request.get('service')
		params = {"result": True, "service": service}
		if service == 'twitter':
			post = draw_post('twitter/search/#hackatbrown')
			params['url'] = 'http://twitter.com/{0}/status/{1}'.format(post.poster, post.id)
			params['text'] = post.text
		else:
			post = draw_post('instagram/tag/hackatbrown')
			params['url'] = post.instagram_link
		params['name'] = post.poster
		self.response.write(template("raffle.html", params))
示例#35
0
def get_keyclient_yaml(variant: str) -> str:
    if variant not in KEYCLIENT_VARIANTS:
        command.fail("invalid variant %s; expected one of %s" %
                     (variant, KEYCLIENT_VARIANTS))
    config = Config.load_from_project()
    kcli = {
        "KEYSERVER": config.keyserver.hostname + "." + config.external_domain,
        "MASTER": variant == "master",
        "WORKER": variant in ("worker", "master"),
        "BASE": variant == "base"
    }
    return template.template("keyclient.yaml", kcli)
示例#36
0
文件: js.py 项目: kiwifb/sagenb
def javascript():
    """
    Return javascript library for the Sage Notebook.  This is done by
    reading the template ``notebook_lib.js`` where all of the
    javascript code is contained and replacing a few of the values
    specific to the running session.

    Before the code is returned (as a string), it is run through a
    JavascriptCompressor to minimize the amount of data needed to be
    sent to the browser.

    The code and a hash of the code is returned.

    .. note::

       This the output of this function is cached so that it only
       needs to be generated once.

    EXAMPLES::

        sage: from sagenb.notebook.js import javascript
        sage: s = javascript()
        sage: s[0][:30]
        '/* JavaScriptCompressor 0.1 [w'

    """
    global _cache_javascript, debug_mode
    if _cache_javascript is not None:
        return _cache_javascript

    s = template(
        os.path.join("js", "notebook_dynamic.js"),
        SAGE_URL=SAGE_URL,
        KEY_CODES=keyhandler.all_tests(),
        debug_mode=debug_mode,
    )

    if debug_mode:
        # TODO: maybe we should return a random hash so that the code
        # is reloaded on every refresh
        return s, sha1(s).hexdigest()

    # TODO: use minify here, which is more standard (and usually safer
    # and with gzip compression, smaller); But first inquire about the
    # propriety of the "This software shall be used for Good, not
    # Evil" clause in the license.  Does that prevent us from
    # distributing it (i.e., it adds an extra condition to the
    # software)?  See http://www.crockford.com/javascript/jsmin.py.txt
    s = JavaScriptCompressor().getPacked(s.encode("utf-8"))
    _cache_javascript = (s, sha1(s).hexdigest())

    return _cache_javascript
def expire_hacker(hacker):
    if hacker.rsvpd == True or hacker.admitted_email_sent_date == None:
        #hacker has rsvp'd or was never accepted
        return
    print "Expiring " + hacker.email + " with admit date: " + str(
        hacker.admitted_email_sent_date)
    email = template("emails/admittance_expired.html",
                     {"name": hacker.name.split(" ")[0]})
    send_email(recipients=[hacker.email],
               html=email,
               subject="You didn't RSVP to Hack@Brown in time...")
    deletedHacker.createDeletedHacker(hacker, "expired")
    hacker.key.delete()
示例#38
0
 def get(self, id):
     source = ndb.Key(urlsafe=id).get()
     fields = copy.deepcopy(source_fields)
     for field in fields:
         val = getattr(source, field['name'])
         if val:
             if field.get('split'): val = field.get('split').join(val)
             field['value'] = val
     vars = {
         "source": source,
         "fields": fields
     }
     self.response.write(template('source.html', vars))
示例#39
0
    def gerar(self, anuncios):
        temp = ""
        for i in anuncios:
            temp = "•" + i["desc"] + "\n    " + temp

        arq = ''
        for i in anuncios:
            arq = str(
                template(i['desc'], temp, i['sku'], i['pos'], i['comp'],
                         i['larg'], i['alt'])
            ) + "\n\n ======================================= \n\n" + str(arq)
            with open(self.nome, 'w') as file:
                file.write(arq)
示例#40
0
 def _page_not_found(self, description=None, **kwargs):
     description = 'The requested URL "{{=url}}" was not found on the server.'
     text = """<h1>Page Not Found</h1>
 <p>%s</p>
 <h3>Current URL Mapping is</h3>
 <table border="1">
 <tr><th>URL</th><th>View Functions</th></tr>
 {{for url, methods, endpoint in urls:}}
 <tr><td>{{=url}} {{=methods}}</td><td>{{=endpoint}}</td></tr>
 {{pass}}
 </table>
 """ % description
     return Response(template.template(text, kwargs), status=404, content_type='text/html')
示例#41
0
 def _page_not_found(self, description=None, **kwargs):
     description = 'The requested URL "{{=url}}" was not found on the server.'
     text = """<h1>Page Not Found</h1>
 <p>%s</p>
 <h3>Current URL Mapping is</h3>
 <table border="1">
 <tr><th>#</th><th>URL</th><th>View Functions</th></tr>
 {{for i, (url, methods, endpoint) in enumerate(urls):}}
 <tr><td>{{=i+1}}</td><td>{{=url}} {{=methods}}</td><td>{{=endpoint}}</td></tr>
 {{pass}}
 </table>
 """ % description
     return Response(template.template(text, kwargs), status=404, content_type='text/html')
示例#42
0
def javascript():
    """
    Return javascript library for the Sage Notebook.  This is done by
    reading the template ``notebook_lib.js`` where all of the
    javascript code is contained and replacing a few of the values
    specific to the running session.

    Before the code is returned (as a string), it is run through a
    JavascriptCompressor to minimize the amount of data needed to be
    sent to the browser.

    The code and a hash of the code is returned.

    .. note::

       This the output of this function is cached so that it only
       needs to be generated once.

    EXAMPLES::

        sage: from sagenb.notebook.js import javascript
        sage: s = javascript()
        sage: s[0][:30]
        '/* JavaScriptCompressor 0.1 [w'

    """
    global _cache_javascript, debug_mode
    if _cache_javascript is not None:
        return _cache_javascript

    s = template(os.path.join('js', 'notebook_dynamic.js'),
                 SAGE_URL=SAGE_URL,
                 KEY_CODES=keyhandler.all_tests(),
                 debug_mode=debug_mode)

    if debug_mode:
        # TODO: maybe we should return a random hash so that the code
        # is reloaded on every refresh
        return s, sha1(s).hexdigest()

    # TODO: use minify here, which is more standard (and usually safer
    # and with gzip compression, smaller); But first inquire about the
    # propriety of the "This software shall be used for Good, not
    # Evil" clause in the license.  Does that prevent us from
    # distributing it (i.e., it adds an extra condition to the
    # software)?  See http://www.crockford.com/javascript/jsmin.py.txt
    s = JavaScriptCompressor().getPacked(s.encode('utf-8'))
    _cache_javascript = (s, sha1(s).hexdigest())

    return _cache_javascript
    def post(self):
        hacker = Hacker()
        hacker.ip = self.request.remote_addr
        for key in hacker_keys:
            vals = self.request.get_all(key)
            val = ','.join(vals)
            try:
                setattr(hacker, key, val)
            except datastore_errors.BadValueError as err:
                return self.response.write(
                    json.dumps({
                        "success":
                        False,
                        "msg":
                        "Register",
                        "field":
                        str(err.args[0]),
                        "newURL":
                        blobstore.create_upload_url('/register')
                    }))

        if Hacker.query(Hacker.email == hacker.email).count() > 0:
            return self.response.write(
                json.dumps({
                    "success": False,
                    "msg": "Email Already Registered!"
                }))

        resume_files = self.get_uploads('resume')
        if len(resume_files) > 0:
            hacker.resume = resume_files[0].key()
        hacker.secret = generate_secret_for_hacker_with_email(hacker.email)
        # try:
        #		email_html = template("emails/confirm_registration.html", {"name": hacker.name.split(" ")[0], "hacker": hacker})
        #		send_email(recipients=[hacker.email], subject="You've applied to Hack@Brown!", html=email_html)
        #		hacker.post_registration_email_sent_date = datetime.datetime.now()
        # except Exception, e:
        #		pass
        hacker.put()
        name = hacker.name.title().split(" ")[0]  # TODO: make it better
        confirmation_html = template("post_registration_splash.html", {
            "name": name,
            "secret": hacker.secret
        })
        self.response.write(
            json.dumps({
                "success": True,
                "replace_splash_with_html": confirmation_html
            }))
示例#44
0
	def get(self):
		# on /, we implement a simple auth system
		secret = 'TBTCUdWMdlqmXI20amAE_tnTqbuniB4PPkAGQY7388PXxZM3eFDW3gE9xKCPNWv-m1LrOzLuFY3MDyCRdj3gWiNAtgT6gJ3AgE-JgasdLfTpUbbylHXTSPFK7MxlxTNt4Y7OARLCucNFmRuNqoIViKvwb9tjggcK7NqZQprzLgM='
		public = '18c2d2ba4c7f41df9587fa0188d26959'

		token = self.request.get('jwt')
		if len(token):
			self.response.set_cookie("jwt", token)
		elif 'jwt' in self.request.cookies:
			token = self.request.cookies['jwt']
		if len(token):
			identity = jwt.decode(token, secret)['d']['uid']
		else:
			identity = None
		self.response.write(template("index.html", {"identity": identity, "auth_url": "/login?callback=%2F&public_token="+public}))
示例#45
0
def get_prometheus_yaml() -> str:
    config = Config.load_from_project()
    kcli = {
        "APISERVER":
        get_apiserver_default_as_node().ip,
        "NODE-TARGETS":
        "[%s]" % ",".join("'%s.%s:9100'" %
                          (node.hostname, config.external_domain)
                          for node in config.nodes),
        "ETCD-TARGETS":
        "[%s]" % ",".join("'%s.%s:9101'" %
                          (node.hostname, config.external_domain)
                          for node in config.nodes if node.kind == "master")
    }
    return template.template("prometheus.yaml", kcli)
示例#46
0
def route_register(request):
    if request.method == 'POST':
        form = request.form()
        u = User.new(form)
        if u.validate_register():
            u.save()
            result = '注册成功<br> <pre>{}</pre>'.format(User.all())
        else:
            result = '用户名或者密码长度必须大于2'
    else:
        result = ''
    body = template('register.html')
    body = body.replace('{{result}}', result)
    header = 'HTTP/1.1 210 VERY OK\r\nContent-Type: text/html\r\n'
    r = header + '\r\n' + body
    return r.encode()
示例#47
0
def addwhiteip(iplist,yx):
    if not check.checkIpList(iplist):
        raise Exception("iplist 格式不正确:%s"%iplist)
    backstageDB = gameOption("backstage_db")
    headTag = gameOption("backstage_tag")
    ismobile = gameOption("is_mobile",type='bool')
    lyWhiteIpKey = gameOption("lyWhiteIpKey")
    if ismobile:
        partnersType = 2
    else:
        partnersType = 1
    backstageIp = gameOption("backstage")
    mixservers = serverlist.serverRange(backstageDB,headTag,partnersType,"mix",backstageIp,serverlist="%s_.*"%yx)
    resultStatus = True
    if len(mixservers) == 0:
        raise Exception("没有获取到游戏列表,请确认!")
    state.servers = mixservers
    state.ignoreErrorHost = True
    ccthread.run(updateProperties,iplist,yx,lyWhiteIpKey)
    proxy_pay1_ip = gameOption("proxy_pay1_ip",default="")
    proxy_pay2_ip = gameOption("proxy_pay2_ip",default="")
    proxy_pay1 = gameOption("proxy_pay1",default="")
    proxy_pay2 = gameOption("proxy_pay2",default="")
    if proxy_pay1.strip() != "":
        proxy_pay1_ssh = ssh.ssh(proxy_pay1_ip)
        updateProxy(proxy_pay1_ssh,proxy_pay1_ip,proxy_pay1,iplist,yx,lyWhiteIpKey)
    if proxy_pay2.strip() != "":
        proxy_pay2_ssh = ssh.ssh(proxy_pay2_ip)
        updateProxy(proxy_pay2_ssh,proxy_pay2_ip,proxy_pay2,iplist,yx,lyWhiteIpKey)
    if len(state.errorResult) > 0:
        resultStatus = False
        print "\n","*" * 50
        for i  in state.errorResult:
            print "[%s] %s"%(i,state.errorResult[i])
    print "\n","*" * 50
    print "更新服务器数:%d"%len(mixservers)
    print "更新失败数:%d"%len(state.errorResult)
    print "连接失败服务器数量:%d"%len(state.errorHost)
    try:
        import template
        templateObj = template.template(state.game,state.language,mixservers[0][0],ip=mixservers[0][1])
        templateObj.updateServerProperties()
        print "更新模板成功!"
    except Exception,e1:
        resultStatus = False
        print "ERROR:模板更新失败!msg:%s"%str(e1)
    def get(self, secret):

        hacker = getHacker(secret)

        if hacker is None:
            self.redirect('/')
            #            this shouldn't silently fail.  we should make a 404
            return

        status = hacker.computeStatus()
        resumeFileName = ""
        receiptsFileNames = ""

        if hacker.resume:
            resumeFileName = hackerFiles.getFileName(hacker.resume)

        if hacker.receipts and hacker.receipts[0] != None:
            receiptsFileNames = hackerFiles.getFileNames(hacker.receipts)

        name = hacker.name.split(" ")[0]  # TODO: make it better

        self.response.headers[
            "Cache-Control"] = "no-cache, no-store, must-revalidate, pre-check=0, post-check=0"
        self.response.headers["Pragma"] = "no-cache"
        self.response.headers["Expires"] = "0"
        deadline = 7
        deadlineFull = "2/07/2015"
        if hacker.deadline:
            deadline = (hacker.deadline - datetime.datetime.now()).days
            deadlineFull = hacker.deadline.strftime("%m.%d.%y")
        if hacker.rsvpd != True and deadline < 0:
            registration.expire_hacker(hacker)
            self.redirect('/')
            return
        self.response.write(
            template.template(
                "hacker_page.html", {
                    "hacker": hacker,
                    "status": status,
                    "name": name,
                    "resumeFileName": resumeFileName,
                    "receiptsFileNames": receiptsFileNames,
                    "deadline": deadline,
                    "deadlineFull": deadlineFull
                }))
示例#49
0
    def get(self):

        if not onTeam():
            logging.info("Not authorized")
            return self.redirect('/')

        isQA = envIsQA()
        isDev = envIsDev()

        self.response.write(
            template(
                "dashboard.html", {
                    "envIsDev": isDev,
                    "isQA": isQA,
                    "admin": isAdmin(),
                    "onTeam": onTeam(),
                    "logout": users.create_logout_url('/')
                }))
示例#50
0
def edit(request):
    """
    todo 首页的路由函数
    """
    # 课5作业2:由于权限判断都放在了装饰器,所以这里直接写edit逻辑
    # 替换模板文件中的标记字符串
    todo_id = int(request.query['id'])
    t = Todo.find_by(id=todo_id)
    body = template('todo_edit.html')
    body = body.replace('{{todo_id}}', str(todo_id))
    body = body.replace('{{todo_title}}', str(t.title))
    # 下面 3 行可以改写为一条函数, 还把 headers 也放进函数中
    headers = {
        'Content-Type': 'text/html',
    }
    header = response_with_headers(headers)
    r = header + '\r\n' + body
    return r.encode()
示例#51
0
	def get(self):
		if self.request.host == 'hey-there-its.me':
			return self.redirect('http://hey-there-its-me.appspot.com' + self.request.path_qs)
		query_args = {}
		query_args['data'] = json.dumps(
			{"public_token": self.request.get('public_token'), 
			"callback": self.request.get('callback'), 
			"referrer": self.request.referrer})
		providers = []
		for name, openid_url, font_awesome in [
					("Google", "https://www.google.com/accounts/o8/id", "fa-google"), 
					("Yahoo", "yahoo.com", "fa-yahoo"), 
					("Stack Exchange", "openid.stackexchange.com", "fa-stack-exchange")]:
			providers.append({"name": name, "font_awesome": font_awesome, "url": users.create_login_url("/openid_auth_response?" + urllib.urlencode(query_args), federated_identity=openid_url)})
		template_args = {
			"providers": providers
		}
		self.response.write(template("login.html", template_args))
示例#52
0
def index(request):
    """
    todo 首页的路由函数
    """
    u = current_user(request)
    # todos = Todo.all()
    todos = Todo.find_all(user_id=u.id)

    # 下面这行生成一个 html 字符串
    # 课5作业4,添加了时间的显示
    todo_html = """
        <h3>
            添加时间: {}, 更新时间:{}
            <br>
            {} : {}
            <a href="/todo/edit?id={}">编辑</a>
            <a href="/todo/delete?id={}">删除</a>
        </h3>

    """

    # 课5作业4,添加了时间的显示
    import datetime

    def dt(t):
        return datetime.datetime.fromtimestamp(t).strftime('%Y-%m-%d %H:%M:%S')

    todo_html = ''.join([
        todo_html.format(
            dt(t.created_time), dt(t.updated_time), t.id, t.title, t.id, t.id
        ) for t in todos
    ])

    # 替换模板文件中的标记字符串
    body = template('todo_index.html')
    body = body.replace('{{todos}}', todo_html)

    # 下面 3 行可以改写为一条函数, 还把 headers 也放进函数中
    headers = {
        'Content-Type': 'text/html',
    }
    header = response_with_headers(headers)
    r = header + '\r\n' + body
    return r.encode()
示例#53
0
def main():
	cv2.namedWindow('image')
	cv2.createTrackbar('X','image',0,4000,nothing)
	cv2.createTrackbar('Y','image',0,4000,nothing)
	cv2.createTrackbar('F','image',0,200,nothing)

	cap = cv2.VideoCapture('sep/0_0.avi')
	fn = 0
	ret, iframe = cap.read()
	H, W, _ = iframe.shape
	tpl = template()
	m = initM()

	print m
	while(cap.isOpened()):
		ret, frame = cap.read()
		if not ret: break
		fn += 1
		while True:
			img = frame.copy()
			x = cv2.getTrackbarPos('X','image')
			y = cv2.getTrackbarPos('Y','image')
			f = cv2.getTrackbarPos('F','image')

			x -= 2000
			y -= 2000
			f = f/100.0

			translate = np.array([[1,0,x], [0,1,y], [0,0,1]])
			scale = np.array([[f,0,0], [0,f,0], [0,0,1]])
			
			mm = np.dot(translate, scale)

			visTpl = cv2.warpPerspective(tpl, np.dot(mm, m), (1280, 720))
			mask_inv = cv2.bitwise_not(visTpl)
			img[..., 1] = visTpl
			cv2.imshow('image', img)
			key = cv2.waitKey(5) & 0xFF
			if key == ord('q'):
				return
			if key == ord('c'):
				break