def main():

	pygame.init()
	globals.pygame = pygame # assign global pygame for other modules to reference
	globals.inputs = Inputs(pygame) # assign global inputs for other modules to reference
	update_display_mode() # now that the global display properties have been set up, update the display
	clock = pygame.time.Clock() # clock to tick / manage delta

	entities = [] # contains every object that will be drawn in the game

	entities.append(Entity()) # our testing entity will be the default entity

	loop = True # for controlling the game loop

	while(loop):
		clock.tick(60) # tick the clock with a target 60 fps
		globals.window.fill((255, 255, 255))

		globals.inputs.update() # refresh inputs

		update(entities) # update all entities
		render(entities) # draw all entities

		if(globals.inputs.isKeyDown("space")): toggle_fullscreen() # space bar toggles fullscreen
		if(globals.inputs.isKeyDown("escape")): loop = False # escape key exits game
		if(globals.inputs.isQuitPressed()): loop = False # red 'x' button exits game

		pygame.display.flip() # flip the display, which finally shows our render

	pygame.quit() # unload pygame modules
Пример #2
0
    def render_GET(self, request):
        dinamic_rouds_dict = {
            b"/": MojSajt.home,
            b"/get_posts": MojSajt.get_posts,
            b"/post_added": MojSajt.render_POST,
            b"/view_post": MojSajt.view_post
        }

        static_rouds_dict = {
            b"/new_post": ('templates/new_post.html', "text/html"),
        }

        if request.path in static_rouds_dict:
            try:
                request.setHeader("Content-Type",
                                  static_rouds_dict[request.path][1])
                with open(static_rouds_dict[request.path][0], 'r') as file:
                    template_content = file.read()
                return Post.read_base_template(template_content)
            except MySQLError as err:
                template, data = InputError.raise_error(str(err))
                template_content = render(template, data)
                return Post.read_base_template(template_content)

        elif request.path in dinamic_rouds_dict:
            return dinamic_rouds_dict[request.path](request)

        template, data = InputError.raise_error('Unknown rout')
        template_content = render(template, data)
        return Post.read_base_template(template_content)
Пример #3
0
def makeRequest(template, context):
    return {
        'method': template['method'],
        'target': render(template['target'], context),
        'headers': {k.lower():render(v, context) for k, v in template['headers'].items()},
        'body': deepRender(template['body'], context) if 'body' in template else None
    }
def visualize(wordEmbeddings):
    """
    Visualize a set of examples using t-SNE.
    """
    PERPLEXITY = 30

    titles = wordEmbeddings.keys()
    titlesStr = ["_".join(y.strip().split()) for y in titles]
    x = numpy.vstack(wordEmbeddings.values())

    filename = "./embeddings.png"
    try:
        #from textSNE.calc_tsne import tsne
        from tsne import tsne
        out = tsne(x, no_dims=2, perplexity=PERPLEXITY)
        import render
        render.render([(title, point[0], point[1])
                       for title, point in zip(titles, out)], filename)
    except IOError:
        print "ERROR visualizing", filename

    data = numpy.column_stack((titlesStr, out))
    numpy.savetxt(
        "/home/bhanu/workspace/RNTN/scripts/embeddings2d_phrase_vis.txt", data,
        "%s")
Пример #5
0
 def implement_search(self):
     CN = self.ui.line_case.text()
     pair = self.ui.checkBox_2.isChecked()
     if CN != '':
         if CN.isdigit() == False:
             print("Case Number must be a digit")
             return
         if pair:
             render.render('CNPair', CN)
         else:
             render.render('CN', CN)
         return
     beat = self.ui.line_beat.text()
     ward = self.ui.line_ward.text()
     block = self.ui.line_block.text()
     date = self.ui.dateEdit.date().getDate()
     input = str(date[1]) + "/" + str(date[2]) + "/" + str(date[0])
     if beat and ward and block:
         if beat.isdigit() and ward.isdigit() and block.isdigit() == False:
             pass
         else:
             print(
                 "This parameters are invalid. Beat and Ward are digits while block is a string"
             )
             return
         if self.ui.checkBox.isChecked():
             input_loc = [beat, ward, block, input]
             render.render('DateLocation', input_loc)
         else:
             input_loc = [beat, ward, block]
             render.render('Location', input_loc)
         return
     if self.ui.checkBox and date:
         render.render('Date', input)
Пример #6
0
def main(args):
    argp = _argparse().parse_args(args[1:])

    # Read the data
    data = []
    titles = []
    #gzipFile = gzip.open("data/english-embeddings.turian.txt.gz")

    #for line in gzipFile:
    #    tokens = string.split(line)
    #    titles.append(tokens[0])
    #    data.append([float(f) for f in tokens[1:]])
    #data = numpy.array(data)
    print "Reading Data"    
    lensingJson = featureExtraction.readData('data/fullData.json')
     
    #ExtractBagOfWord features
    print "Extracting Features"
    data = featureExtraction.extBagOfWordFeatures(lensingJson)
    
    for i in range(0,len(lensingJson)):
        titles.append(str(i))
    
    #Call PCA
    #data = PCA(data,30)
    #print "PCA Complete"

    #call bh_tsne and get the results. Zip the titles and results for writing
    result = bh_tsne(data, perplexity=argp.perplexity, theta=argp.theta, 
        verbose=argp.verbose)
    
    #render image
    if argp.render:
        print "Rendering Image"
        import render
        render.render([(title, point[0], point[1]) for title, point in zip(titles, result)], "output/lensing500p30-data.rendered.png", width=3000, height=1800) 
    

    #convert result into json and write it
    if argp.write:
        print "Writing data to file"
        resData = {}
        minx = 0
        maxx = 0
        miny = 0
        maxy = 0
        for (title,result) in zip(titles,[[res[0],res[1]] for res in result]):
            resData[title] = {'x':result[0], 'y':result[1]}
            if minx > result[0]: minx = result[0]
            if maxx < result[0]: maxx = result[0]
            if miny > result[1]: miny = result[1]
            if maxy < result[1]: maxy = result[1]
        
        print "creating json" 
        print len(resData)
        jsonStr = json.dumps(resData)
        print "MinX - %s MaxX - %s MinY - %s MaxY - %s" % (minx, maxx, miny, maxy)
        with open('output/coordinateslensing-full-srl-p40.json','w') as outFile:
            outFile.write("jsonstr = ");
            outFile.write(jsonStr+'\n')
Пример #7
0
 def run(self):
     pygame.init()
     self.clock = pygame.time.Clock()
     aspect = self.map['width'] * 1.0 / self.map['height']
     self.w = 700
     self.h = int(self.w / aspect)
     self.surface = pygame.display.set_mode((self.w, self.h))
     self.planes = []
     self.planes.append(plane.Plane(self))
     while True:
         dt = 1.0 / FRAME_RATE
         # handle events:
         for event in pygame.event.get():
             if event.type == pygame.QUIT:
                 break
         # make new planes:
         if random.random() < dt * NEW_PLANES_PER_SECOND:
             self.planes.append(plane.Plane(self))
         # update existing planes:
         for p in self.planes:
             p.advance(dt)
         # render graphics:
         render.render(self)
         pygame.display.update()
         self.clock.tick(FRAME_RATE)
     pygame.quit()
Пример #8
0
	def run(self):
		pygame.init()
		self.clock = pygame.time.Clock()
		aspect = self.map['width']*1.0/self.map['height']
		self.w = 700
		self.h = int(self.w/aspect)
		self.surface = pygame.display.set_mode((self.w, self.h))
		self.planes = []
		self.planes.append(plane.Plane(self))
		while True:
			dt = 1.0/FRAME_RATE
			# handle events:
			for event in pygame.event.get():
				if event.type == pygame.QUIT:
					break
			# make new planes:
			if random.random() < dt * NEW_PLANES_PER_SECOND:
				self.planes.append(plane.Plane(self))
			# update existing planes:
			for p in self.planes:
				p.advance(dt)
			# render graphics:
			render.render(self)
			pygame.display.update()
			self.clock.tick(FRAME_RATE)
		pygame.quit()
Пример #9
0
def display(text):
    from data import data
    from render import render

    s = data['santa']
    print text
    render(text, s)
Пример #10
0
def test_render():
    bar = Bar(completed=11, width=50)
    bar_render = render(bar)
    assert bar_render == expected[0]
    bar.update(completed=12)
    bar_render = render(bar)
    assert bar_render == expected[1]
def write_projection_render(pfp, v, f, map):

    CAM2WORLD = np.array([[0.85408425, 0.31617427, -0.375678, 0.56351697 * 2],
                          [0., -0.72227067, -0.60786998, 0.91180497 * 2],
                          [-0.52013469, 0.51917219, -0.61688, 0.92532003 * 2],
                          [0., 0., 0., 1.]],
                         dtype=np.float32)

    # rotate the mesh elevation by 30 degrees
    Rx = np.array(
        [[1, 0, 0, 0], [0., np.cos(np.pi / 6), -np.sin(np.pi / 6), 0],
         [0, np.sin(np.pi / 6), np.cos(np.pi / 6), 0], [0., 0., 0., 1.]],
        dtype=np.float32)

    CAM2WORLD = np.matmul(Rx, CAM2WORLD)

    RENDER_INFO = {
        'Height': 480,
        'Width': 640,
        'fx': 575,
        'fy': 575,
        'cx': 319.5,
        'cy': 239.5
    }
    # TODO ---------- Render Stub -----------#
    context = render.SetMesh(v, f)
    for i_ang, _ in enumerate(np.linspace(0, 2 * np.pi, map.num_angs)):
        render.render(context, map.world2cam_mats[i_ang])
        # depth = render.getDepth(RENDER_INFO)
        vindices, _, _ = render.getVMap(context, RENDER_INFO)
        mask = np.unique(vindices)

        # Only kept the mask option
        np.savez(f"{pfp}_mask_{i_ang:03d}", mask=mask)
Пример #12
0
def deploy_single(path):
    """
    Deploy a single project to S3 and, if configured, to our servers.
    """
    require('settings', provided_by=[production, staging])
    slug, abspath = utils.parse_path(path)
    graphic_root = '%s/%s' % (abspath, slug)
    s3_root = '%s/graphics/%s' % (app_config.PROJECT_SLUG, slug)
    graphic_assets = '%s/assets' % graphic_root
    s3_assets = '%s/assets' % s3_root
    graphic_node_modules = '%s/node_modules' % graphic_root

    graphic_config = load_graphic_config(graphic_root)

    use_assets = getattr(graphic_config, 'USE_ASSETS', True)
    default_max_age = getattr(graphic_config, 'DEFAULT_MAX_AGE',
                              None) or app_config.DEFAULT_MAX_AGE
    assets_max_age = getattr(graphic_config, 'ASSETS_MAX_AGE',
                             None) or app_config.ASSETS_MAX_AGE
    update_copy(path)
    if use_assets:
        error = assets.sync(path)
        if error:
            return

    render.render(path)
    flat.deploy_folder(
        graphic_root,
        s3_root,
        headers={'Cache-Control': 'max-age=%i' % default_max_age},
        ignore=[
            '%s/*' % graphic_assets,
            '%s/*' % graphic_node_modules,
            # Ignore files unused on static S3 server
            '*.xls',
            '*.xlsx',
            '*.pyc',
            '*.py',
            '*.less',
            '*.bak',
            '%s/base_template.html' % graphic_root,
            '%s/child_template.html' % graphic_root
        ])

    if use_assets:
        flat.deploy_folder(
            graphic_assets,
            s3_assets,
            headers={'Cache-Control': 'max-age=%i' % assets_max_age},
            ignore=['%s/private/*' % graphic_assets])

    # Need to explicitly point to index.html for the AWS staging link
    file_suffix = ''
    if env.settings == 'staging':
        file_suffix = 'index.html'

    print ''
    print '%s URL: %s/graphics/%s/%s' % (
        env.settings.capitalize(), app_config.S3_BASE_URL, slug, file_suffix)
Пример #13
0
def deploy(slug):
    """
    Deploy the latest app to S3 and, if configured, to our servers.
    """
    require('settings', provided_by=[production, staging])

    if not slug:
        print 'You must specify a project slug, like this: "deploy:slug"'
        return

    graphic_root = '%s/%s' % (app_config.GRAPHICS_PATH, slug)
    s3_root = '%s/graphics/%s' % (app_config.PROJECT_SLUG, slug)
    graphic_assets = '%s/assets' % graphic_root
    s3_assets = '%s/assets' % s3_root

    graphic_config = load_graphic_config(graphic_root)

    use_assets = getattr(graphic_config, 'USE_ASSETS', True)
    default_max_age = getattr(graphic_config, 'DEFAULT_MAX_AGE', None) or app_config.DEFAULT_MAX_AGE
    assets_max_age = getattr(graphic_config, 'ASSETS_MAX_AGE', None) or app_config.ASSETS_MAX_AGE

    update_copy(slug)

    if use_assets:
        assets.sync(slug)

    render.render(slug)

    flat.deploy_folder(
        graphic_root,
        s3_root,
        headers={
            'Cache-Control': 'max-age=%i' % default_max_age
        },
        ignore=['%s/*' % graphic_assets]
    )

    # Deploy parent assets
    flat.deploy_folder(
        'www',
        app_config.PROJECT_SLUG,
        headers={
            'Cache-Control': 'max-age=%i' % default_max_age
        }
    )

    if use_assets:
        flat.deploy_folder(
            graphic_assets,
            s3_assets,
            headers={
                'Cache-Control': 'max-age=%i' % assets_max_age
            }
        )

    print ''
    print '%s URL: %s/graphics/%s/' % (env.settings.capitalize(), app_config.S3_BASE_URL, slug)
Пример #14
0
def update_from_template(slug, template):
    require('settings', provided_by=[production, staging])

    if not slug:
        print 'You must specify a project slug and template, like this: "update_from_template:slug,template=template"'
        return

    recopy_templates(slug, template)
    render.render(slug)
Пример #15
0
def push_cfgs(args):

    redirect = []
    ext = '.jinja2'
    commands = initialize.configuration
    auditcreeper_flag = False
    output = False
    argument_node = args.node
    remediation = True
    with_remediation = True

    if (args.file is None):
        #		print("ARGS.FILE IS NONE")
        template_list = []
        auditcreeper_flag = True
    else:
        #		print("ARGS.FILE IS VALID")
        template = args.file + ext
        template_list = []
        template_list.append(template)

    ### NODE_OBJECT IS A LIST OF ALL THE NODES IN THE DATABASE WITH ALL ATTRIBUTES
    node_object = process_nodes()

    ### NODE_TEMPLATE IS A LIST OF ALL THE TEMPLATES BASED ON PLATFORMS AND DEVICE TYPE
    node_template = process_templates()

    ### MATCH_NODE IS A LIST OF NODES THAT MATCHES THE ARGUEMENTS PASSED IN BY USER
    match_node = search_node(argument_node, node_object)

    ### MATCH_TEMPLATE IS A LIST OF 'MATCH' AND/OR 'NO MATCH' IT WILL USE THE MATCH_NODE
    ### RESULT, RUN IT AGAINST THE NODE_OBJECT AND COMPARES IT WITH NODE_TEMPLATE DATABASE
    ### TO SEE IF THERE IS A TEMPLATE FOR THE SPECIFIC PLATFORM AND TYPE.
    match_template = search_template(template_list, match_node, node_template,
                                     node_object, auditcreeper_flag)

    ### THIS WILL PARSE OUT THE GENERATED CONFIGS FROM THE *.JINJA2 FILE TO A LIST

    if (len(match_node) == 0):
        print("+ [NO MATCHING NODES AGAINST DATABASE]")
        print("")

    elif ('NO MATCH' in match_template):
        print("+ [NO MATCHING TEMPLATE AGAINST DATABASE]")
        print("")

    else:

        node_create(match_node, node_object)
        render(template_list, node_object, auditcreeper_flag, output,
               with_remediation)

        for index in initialize.element:
            redirect.append('push_cfgs')

        confirm_push(redirect, commands)
        print("")
Пример #16
0
 def do_render(self, pieces):
     out = {}
     for style in ["pep440", "pep440-pre", "pep440-post", "pep440-old",
                   "git-describe", "git-describe-long"]:
         out[style] = render(pieces, style)["version"]
     DEFAULT = "pep440"
     self.assertEqual(render(pieces, ""), render(pieces, DEFAULT))
     self.assertEqual(render(pieces, "default"), render(pieces, DEFAULT))
     return out
Пример #17
0
 def do_render(self, pieces):
     out = {}
     for style in ["pep440", "pep440-pre", "pep440-post", "pep440-old",
                   "pep440-bare", "git-describe", "git-describe-long"]:
         out[style] = render(pieces, style)["version"]
     DEFAULT = "pep440"
     self.assertEqual(render(pieces, ""), render(pieces, DEFAULT))
     self.assertEqual(render(pieces, "default"), render(pieces, DEFAULT))
     return out
Пример #18
0
def update_from_template(slug, template):
    require('settings', provided_by=[production, staging])

    if not slug:
        print 'You must specify a project slug and template, like this: "update_from_template:slug,template=template"'
        return

    recopy_templates(slug, template)
    render.render(slug)
Пример #19
0
def update_from_content(slug):
    require('settings', provided_by=[production, staging])

    if not slug:
        print 'You must specify a project slug, like this: "update_from_content:slug"'
        return

    update_copy(slug)
    render.render(slug)
    write_meta_json(slug, 'content')
Пример #20
0
	def update(self, data) :
		surface = pygame.Surface((self.width, self.height))
		surface.fill(self.back_color)
		for i in range(len(data)) :
			col = i % self.cols
			row = int(i / self.cols)
			surface.blit(data[i]["image"], data[i]["image"].get_rect(top = (row * self.item_height) + self.gap_y, left = (col * self.item_width)))
			render.render(data[i]["data"], self.font, surface, self.front_color, (col * self.item_width) + data[i]["image"].get_width() + self.gap_x, (row * self.item_height) + self.gap_y, self.item_width - data[i]["image"].get_width() - (2*self.gap_x), self.item_height - self.gap_y) 

		self.background.blit(surface, pygame.Rect(self.left, self.top, self.width, self.height))
Пример #21
0
def update_from_content(slug):
    require('settings', provided_by=[production, staging])

    if not slug:
        print 'You must specify a project slug, like this: "update_from_content:slug"'
        return

    update_copy(slug)
    render.render(slug)
    write_meta_json(slug, 'content')
Пример #22
0
def deploy_single(path):
    """
    Deploy a single project to S3 and, if configured, to our servers.
    """
    require('settings', provided_by=[production, staging])
    slug, abspath = utils.parse_path(path)
    graphic_root = '%s/%s' % (abspath, slug)
    s3_root = '%s/graphics/%s' % (app_config.PROJECT_SLUG, slug)
    graphic_assets = '%s/assets' % graphic_root
    s3_assets = '%s/assets' % s3_root
    graphic_node_modules = '%s/node_modules' % graphic_root

    graphic_config = load_graphic_config(graphic_root)

    use_assets = getattr(graphic_config, 'USE_ASSETS', True)
    default_max_age = getattr(graphic_config, 'DEFAULT_MAX_AGE', None) or app_config.DEFAULT_MAX_AGE
    assets_max_age = getattr(graphic_config, 'ASSETS_MAX_AGE', None) or app_config.ASSETS_MAX_AGE
    update_copy(path)
    if use_assets:
        error = assets.sync(path)
        if error:
            return

    render.render(path)
    flat.deploy_folder(
        graphic_root,
        s3_root,
        headers={
            'Cache-Control': 'max-age=%i' % default_max_age
        },
        ignore=['%s/*' % graphic_assets, '%s/*' % graphic_node_modules,
                # Ignore files unused on static S3 server
                '*.xls', '*.xlsx', '*.pyc', '*.py', '*.less', '*.bak',
                '%s/base_template.html' % graphic_root,
                '%s/child_template.html' % graphic_root,
                '%s/README.md' % graphic_root]
    )

    if use_assets:
        flat.deploy_folder(
            graphic_assets,
            s3_assets,
            headers={
                'Cache-Control': 'max-age=%i' % assets_max_age
            },
            ignore=['%s/private/*' % graphic_assets]
        )

    # Need to explicitly point to index.html for the AWS staging link
    file_suffix = ''
    if env.settings == 'staging':
        file_suffix = 'index.html'

    print ''
    print '%s URL: %s/graphics/%s/%s' % (env.settings.capitalize(), app_config.S3_BASE_URL, slug, file_suffix)
Пример #23
0
def push_config(args):

	ext = '.jinja2'
	controller = 'push_config'
	commands = initialize.configuration
	auditcreeper_flag = False
	argument_node = args.node

	if(args.file is None):
#		print("ARGS.FILE IS NONE")
		template_list = []
		auditcreeper_flag = True
	else:
#		print("ARGS.FILE IS VALID")
		template = args.file + ext
		template_list = []
		template_list.append(template)

	### NODE_OBJECT IS A LIST OF ALL THE NODES IN THE DATABASE WITH ALL ATTRIBUTES
	node_object = process_nodes()

	### NODE_TEMPLATE IS A LIST OF ALL THE TEMPLATES BASED ON PLATFORMS AND DEVICE TYPE
	node_template = process_templates()

	### MATCH_NODE IS A LIST OF NODES THAT MATCHES THE ARGUEMENTS PASSED IN BY USER
	match_node = search_node(argument_node,node_object)

	### MATCH_TEMPLATE IS A LIST OF 'MATCH' AND/OR 'NO MATCH' IT WILL USE THE MATCH_NODE
	### RESULT, RUN IT AGAINST THE NODE_OBJECT AND COMPARES IT WITH NODE_TEMPLATE DATABASE
	### TO SEE IF THERE IS A TEMPLATE FOR THE SPECIFIC PLATFORM AND TYPE.
	match_template = search_template(template_list,match_node,node_template,node_object,auditcreeper_flag)

	### THIS WILL PARSE OUT THE GENERATED CONFIGS FROM THE *.JINJA2 FILE TO A LIST

	if(len(match_node) == 0):
		print("+ [NO MATCHING NODES AGAINST DATABASE]")
		print("")

	elif('NO MATCH' in match_template):
		print("+ [NO MATCHING TEMPLATE AGAINST DATABASE]")
		print("")

	else:
		render(template_list,node_object,auditcreeper_flag)
		node_create(match_node,node_object)
		print("")
		proceed = raw_input("PROCEED? [Y/N]: ")
	
		if(proceed == 'y' or proceed == 'Y'):
			print("")
			print("PUSHING CODE...")
			multithread_engine(initialize.ntw_device,controller,commands)
	
		elif(proceed == 'n' or proceed == 'N'):
			print("ABORT...")
Пример #24
0
def debug_deploy(slug, template):
    require('settings', provided_by=[production, staging])

    if not slug:
        print 'You must specify a project slug and template, like this: "debug_deploy:slug,template=template"'
        return

    recopy_templates(slug, template)
    # update_copy(slug)
    # write_meta_json(slug, 'content')
    render.render(slug)
Пример #25
0
def urlencoded_html(form):
# query_string = environ['QUERY_STRING']

    if 'firstname' not in form or 'lastname' not in form:
        html = render.render('error.html').encode('latin-1', 'replace')
    else:
        vars_dict = {'firstname': form['firstname'].value,\
            'lastname': form['lastname'].value}
        html = render.render('urlencoded.html', vars_dict).encode('latin-1', 'replace')

    return html
Пример #26
0
def clone_graphic(old_slug, slug=None):
    """
    Clone an existing graphic creating a new spreadsheet
    """

    if not slug:
        slug = _create_slug(old_slug)

    if slug == old_slug:
        print "%(slug)s already has today's date, please specify a new slug to clone into, i.e.: fab clone_graphic:%(slug)s,NEW_SLUG" % {
            'slug': old_slug
        }
        return

    # Add today's date to end of slug if not present or invalid
    slug = _add_date_slug(slug)

    graphic_path = '%s/%s' % (app_config.GRAPHICS_PATH, slug)
    if _check_slug(slug):
        return

    # First search over the graphics repo
    clone_path, old_graphic_warning = _search_graphic_slug(old_slug)
    if not clone_path:
        print 'Did not find %s on graphics repos...skipping' % (old_slug)
        return

    local('cp -r %s %s' % (clone_path, graphic_path))

    config_path = os.path.join(graphic_path, 'graphic_config.py')

    if os.path.isfile(config_path):
        print 'Creating spreadsheet...'

        success = copy_spreadsheet(slug)

        if success:
            download_copy(slug)
        else:
            local('rm -r %s' % (graphic_path))
            print 'Failed to copy spreadsheet! Try again!'
            return
    else:
        print 'No graphic_config.py found, not creating spreadsheet'

    # Force render to clean up old graphic generated files
    render.render(slug)

    print 'Run `fab app` and visit http://127.0.0.1:8000/graphics/%s to view' % slug

    if old_graphic_warning:
        print "WARNING: %s was found in old & dusty graphic archives\n"\
              "WARNING: Please ensure that graphic is up-to-date"\
              " with your current graphic libs & best-practices" % (old_slug)
Пример #27
0
def debug_deploy(slug, template):
    require('settings', provided_by=[production, staging])

    if not slug:
        print 'You must specify a project slug and template, like this: "debug_deploy:slug,template=template"'
        return

    recopy_templates(slug, template)
    # update_copy(slug)
    # write_meta_json(slug, 'content')
    render.render(slug)
Пример #28
0
def renderEvaluation(s, exportTo=None):
    parse = evaluate(eval(s))
    x0 = min([x for l in parse.lines for x in l.usedXCoordinates()])
    y0 = min([y for l in parse.lines for y in l.usedYCoordinates()])
    x1 = max([x for l in parse.lines for x in l.usedXCoordinates()])
    y1 = max([y for l in parse.lines for y in l.usedYCoordinates()])

    render([parse.TikZ()],
           showImage=exportTo == None,
           exportTo=exportTo,
           canvas=(x1 + 1, y1 + 1),
           x0y0=(x0 - 1, y0 - 1))
Пример #29
0
def deploy_single(slug):
    """
    Deploy a single project to S3 and, if configured, to our servers.
    """
    require('settings', provided_by=[production, staging])

    graphic_root = '%s/%s' % (app_config.GRAPHICS_PATH, slug)
    s3_root = '%s/graphics/%s' % (app_config.PROJECT_SLUG, slug)
    graphic_assets = '%s/assets' % graphic_root
    s3_assets = '%s/assets' % s3_root

    graphic_config = load_graphic_config(graphic_root)

    use_assets = getattr(graphic_config, 'USE_ASSETS', True)
    default_max_age = getattr(graphic_config, 'DEFAULT_MAX_AGE', None) or app_config.DEFAULT_MAX_AGE
    assets_max_age = getattr(graphic_config, 'ASSETS_MAX_AGE', None) or app_config.ASSETS_MAX_AGE

    update_copy(slug)

    if use_assets:
        assets.sync(slug)

    render.render(slug)

    flat.deploy_folder(
        graphic_root,
        s3_root,
        headers={
            'Cache-Control': 'max-age=%i' % default_max_age
        },
        ignore=['%s/*' % graphic_assets]
    )

    # Deploy parent assets
    flat.deploy_folder(
        'www',
        app_config.PROJECT_SLUG,
        headers={
            'Cache-Control': 'max-age=%i' % default_max_age
        }
    )

    if use_assets:
        flat.deploy_folder(
            graphic_assets,
            s3_assets,
            headers={
                'Cache-Control': 'max-age=%i' % assets_max_age
            }
        )

    print ''
    print '%s URL: %s/graphics/%s/' % (env.settings.capitalize(), app_config.S3_BASE_URL, slug)
Пример #30
0
def render_html(c):
    """Render HTML but do not update data from Amazon"""
    sitemap = []
    sitemap.extend(
        render("www/instances.json", "in/index.html.mako", "www/index.html"))
    sitemap.extend(
        render("www/rds/instances.json", "in/rds.html.mako",
               "www/rds/index.html"))
    sitemap.extend(
        render("www/cache/instances.json", "in/cache.html.mako",
               "www/cache/index.html"))
    build_sitemap(sitemap)
Пример #31
0
    def get_posts_from_to(request, page, page_size):
        if page < 1 or page_size < 1:
            template, data = InputError.raise_error(
                'Page must be positive nuber')
            template_content = render(template, data)
            return Post.read_base_template(template_content)

        page_previous_num = page - 1

        link_next_template = '<a href="/get_posts?page={}&page_size={}"> Next </a>'
        link_next = link_next_template.format(str(page + 1), str(page_size))

        link_prev_template = '<a href="/get_posts?page={}&page_size={}"> Previous </a>'
        link_previous = link_prev_template.format(str(page_previous_num),
                                                  str(page_size))

        post_len = Storage.post_len()

        if page * page_size >= post_len:
            link_next = ''

        if page == 1:
            link_previous = ''

        all_posts = Storage.select_posts((page - 1) * page_size, page_size)

        if not all_posts:
            template, data = InputError.raise_error('No more posts to show')
            template_content = render(template, data)
            return Post.read_base_template(template_content)

        all_posts_list = []
        for post in all_posts:
            post_dict = {
                'title': post[0],
                'post': post[3],
                'date': str(post[1]),
                'id': str(post[2])
            }
            all_posts_list.append(post_dict)

        data_small = {
            'posts': all_posts_list,
            'next': link_next,
            'previous': link_previous
        }

        with open('templates/home.html', 'r') as file:
            template_small = file.read()
            template_content = render(template_small, data_small)

        return Post.read_base_template(template_content)
Пример #32
0
def clone_graphic(old_slug, slug=None):
    """
    Clone an existing graphic creating a new spreadsheet
    """

    if not slug:
        slug = _create_slug(old_slug)

    if slug == old_slug:
        print "%(slug)s already has today's date, please specify a new slug to clone into, i.e.: fab clone_graphic:%(slug)s,NEW_SLUG" % {'slug': old_slug}
        return

    # Add today's date to end of slug if not present or invalid
    slug = _add_date_slug(slug)

    graphic_path = '%s/%s' % (app_config.GRAPHICS_PATH, slug)
    if _check_slug(slug):
        return

    # First search over the graphics repo
    clone_path, old_graphic_warning = _search_graphic_slug(old_slug)
    if not clone_path:
        print 'Did not find %s on graphics repos...skipping' % (old_slug)
        return

    local('cp -r %s %s' % (clone_path, graphic_path))

    config_path = os.path.join(graphic_path, 'graphic_config.py')

    if os.path.isfile(config_path):
        print 'Creating spreadsheet...'

        success = copy_spreadsheet(slug)

        if success:
            download_copy(slug)
        else:
            local('rm -r %s' % (graphic_path))
            print 'Failed to copy spreadsheet! Try again!'
            return
    else:
        print 'No graphic_config.py found, not creating spreadsheet'

    # Force render to clean up old graphic generated files
    render.render(slug)

    print 'Run `fab app` and visit http://127.0.0.1:8000/graphics/%s to view' % slug

    if old_graphic_warning:
        print "WARNING: %s was found in old & dusty graphic archives\n"\
              "WARNING: Please ensure that graphic is up-to-date"\
              " with your current graphic libs & best-practices" % (old_slug)
Пример #33
0
 def draw(self):
     font = pygame.font.Font(self.fontname, 72)
     pygame.draw.rect(self.surface, (0, 0, 0), Rect((100, 100),
                                                    (1720, 880)))
     pygame.draw.lines(self.surface, (255, 255, 255), True, [(100, 100),
                                                             (1820, 100),
                                                             (1820, 980),
                                                             (100, 980)], 5)
     render(font, text['prompt0'], surface=self.surface, topleft=(100, 100))
     render(font,
            text['prompt9'],
            surface=self.surface,
            bottomleft=(100, 980))
Пример #34
0
def submit_html(environ):
    query = environ['QUERY_STRING']

    html = ''
    res = urlparse.parse_qs(query)
    if len(res) < 2: # check if the input was valid
        html = render.render('error.html').encode('latin-1', 'replace')
    else:
        vars_dict = {'firstname': res['firstname'][0], 
            'lastname': res['lastname'][0]}
        html = render.render('submit.html', vars_dict).encode('latin-1', 'replace')

    return html
Пример #35
0
def main(args):
    parser = argparse.ArgumentParser()
    parser.add_argument('--outfile', help="Render to here", required=True)
    parser.add_argument('--infile',
                        help="Use objects from here",
                        required=True)
    parser.add_argument('--resolution_percent',
                        help="Resolution percent as an int",
                        type=int,
                        required=True)
    parser.add_argument('--render_device',
                        help="use the string: 'CPU' or 'GPU'",
                        type=str,
                        required=True)
    parser.add_argument('--project_name',
                        help="The name of the project",
                        type=str,
                        required=True)
    parser.add_argument('--part_name',
                        help="The name of the part",
                        type=str,
                        required=True)
    parser.add_argument('--part_version',
                        help="The version number",
                        type=str,
                        required=True)
    config = parser.parse_args(args)
    full_outpath = os.getcwd() + '../' + config.outfile
    full_inpath = os.getcwd() + '../' + config.infile

    # Link in the collection from the other blend
    with bpy.data.libraries.load(full_inpath, True) as (data_from, data_to):
        data_to.collections = data_from.collections

    #link object to current scene
    if len(data_to.collections) != 1:
        raise Exception("Expected exactly one collection")

    collection = data_to.collections[0]

    # Replace objects in this blend
    for obj in bpy.data.objects:
        if obj.name.startswith("REPLACE"):
            obj.instance_type = "COLLECTION"
            obj.instance_collection = collection
    bpy.data.objects["Project"].data.body = config.project_name
    bpy.data.objects["DrawingName"].data.body = config.part_name
    bpy.data.objects["VersionHash"].data.body = config.part_version

    render.render(full_outpath, config.resolution_percent,
                  config.render_device)
Пример #36
0
def generate_tile(patches, scale, offset_x, offset_y, tile_filename):
    geometry_patches = []

    for name, raw_patch in patches.items():
        patch = raw_patch.copy()
        # Set uniforms
        patch['scale'] = scale
        patch['offset'] = (offset_x, offset_y)
        del patch['inner']
        del patch['outer']
        chunk = np.load(generate_chunk_filename(name))
        geometry_patches.append((chunk, patch))

    render.render(geometry_patches, tile_filename)
Пример #37
0
def file_op_servlet():
    global TEST_EMAIL
    if debug:
        print("Arguments:", request.args)
        print("Headers:", request.headers)

    # TODO: validate
    open('temp.jpg', mode='wb').write(request.files["jpegData"].read())
    render.render('temp.jpg', 'Page{}.jpg')
    sender.digicam_sender('Page0.jpg', TEST_EMAIL)
    return {
        "errorItems_1": 0,
        "message": "a",
        "imageID": 1,
    }
Пример #38
0
def generate():
    # Create the root element
    page = et.Element('RootElement')
    # Create the element tree
    doc = et.ElementTree(page)
    # Call the render method
    render(elmts, page)
    # Open the homemade.xml file on write mode
    file = open('output.xml', 'w')
    # Write the doc content into the file
    doc.write(file, pretty_print=True)
    # Optional import os module to open the file with the default
    # application for the give file extension if there is any
    import os
    os.startfile('output.xml')
Пример #39
0
def fix_order_information(_):
    current_order.complete = True
    db.session.commit()

    try:
        render(current_order.order_schema, current_order.order_id)
    except Exception as e:
        app.logger.exception(e)
        return ""

    password = generate_zip_password(10)

    os.system(
        f"cd orders/{current_order.order_id}; zip --password {password} {current_order.order_id}.zip -r *.png"
    )

    digicam_sender(
        f"orders/{current_order.order_id}/{current_order.order_id}.zip",
        current_order.email,
        password,
    )

    eventual_response = {
        "available": 1,
        "itemCode": current_item.itemCode,
        "itemPriceCode": current_item.itemCode,
        "orderID": current_order.order_id,
        "orderDate": "today",
        "commodityCount": [1],
        "commodityPrice": [100000000],
        "taxOffAmt": [210000],
        "tax": [210000],
        "taxInAmt": [210000],
        "totalAmt": 0,
        "deliveryFee": 0,
        "daibikiFee": 0,
        "totalTax": 0,
        "otherFee": 0,
        "amountTotal": 0,
        "totalItemPrice": 0,
        "totalShipping": 0,
        "totalHandling": 0,
    }

    # Add our item data.
    eventual_response |= current_item.map_list()

    return eventual_response
Пример #40
0
def interactive( animation, size = 320 ):
	basedir = mkdtemp()
	basename = join( basedir, 'graph' )
	steps = [ Image( path ) for path in render( animation.graphs(), basename, 'png', size ) ]
	rmtree( basedir )
	slider = widgets.IntSlider( min = 0, max = len( steps ) - 1, step = 1, value = 0 )
	return widgets.interactive( lambda n: steps[ n ], n = slider )
Пример #41
0
 def save(self, *args, **kwargs):
     if not self.slug:
         from pytils.translit import slugify
         self.slug = slugify(self.name)
     self.text = self.text.strip()
     self.html = render(self.text, self.render_method, unsafe=True)
     super(Post, self).save(*args, **kwargs)
Пример #42
0
def image_html():
    fp = open('./images/justin_eli.jpg', 'rb')
    data = fp.read()
    fp.close()

    html = render.render('image.html').encode('latin-1', 'replace')
    return data 
Пример #43
0
def markdown_to_plain_text(markup, safe_mode='escape'):
    html = render(markup, substitutions=False, safe_mode=safe_mode)
    try:
        return fragment_fromstring(html, create_parent=True).text_content()
    except Exception, e:
        log.exception(e)
        return markup
Пример #44
0
def logout(req):
    sid = req.cookies.get('session_id')
    if sid:
        session = session_store.get(sid)
        if 'user_id' in session: del (session['user_id'])
        session_store.save(session)
    return Response(render('signin.j2', next_url="/", login_form=True), mimetype='text/html')
Пример #45
0
def main(args):
    parser = argparse.ArgumentParser()
    parser.add_argument('--outfile', help="Render to here", required=True)
    parser.add_argument('--resolution_percent',
                        help="Resolution percent as an int",
                        type=int,
                        required=True)
    parser.add_argument('--render_device',
                        help="use the string: 'CPU' or 'GPU'",
                        type=str,
                        required=True)
    config = parser.parse_args(args)
    full_outpath = bpy.path.abspath('//' + config.outfile)

    render.render(full_outpath, config.resolution_percent,
                  config.render_device)
Пример #46
0
def markdown_to_plain_text(markup, safe_mode='escape'):
    html = render(markup, substitutions=False, safe_mode=safe_mode)
    try:
        return fragment_fromstring(html, create_parent=True).text_content()
    except Exception, e:
        log.exception(e)
        return markup
Пример #47
0
def makeSyntheticData(filePrefix, sample, k=1000, offset=0):
    """sample should return a program"""
    programs = [sample() for _ in range(k)]
    print "Sampled %d programs." % k
    # remove all of the labels - we will render them separately
    noLabels = [
        Sequence([l for l in p.lines if not isinstance(l, Label)])
        for p in programs
    ]
    onlyLabels = [[l for l in p.lines if isinstance(l, Label)]
                  for p in programs]
    noisyTargets = [p.noisyTikZ() for p in noLabels]
    distinctPrograms = list(set(noisyTargets))
    pixels = render(distinctPrograms, yieldsPixels=True)
    print "Rendered %d images for %s." % (len(distinctPrograms), filePrefix)

    #pixels = [ Image.fromarray(ps*255).convert('L') for ps in pixels ]
    pixels = dict(zip(distinctPrograms, pixels))

    for j in range(len(programs)):
        pickle.dump(programs[j],
                    open("%s-%d.p" % (filePrefix, j + offset), 'wb'))
        unlabeledPixels = 1 - pixels[noisyTargets[j]]
        for l in onlyLabels[j]:
            blitCharacter(unlabeledPixels, l.p.x * 16, l.p.y * 16, l.c)
        unlabeledPixels[unlabeledPixels > 1] = 1
        unlabeledPixels = (1 - unlabeledPixels) * 255
        labeledPixels = Image.fromarray(unlabeledPixels).convert('L')
        labeledPixels.save("%s-%d-noisy.png" % (filePrefix, j + offset))

        if False:
            Image.fromarray(255 * programs[j].draw()).convert('L').save(
                "%s-%d-clean.png" % (filePrefix, j + offset))
Пример #48
0
 def save(self, *args, **kwargs):
     if not self.slug:
         from pytils.translit import slugify
         self.slug = slugify(self.name)
     self.text = self.text.strip()
     self.html = render(self.text, self.render_method, unsafe=True)
     super(Post, self).save(*args, **kwargs)
Пример #49
0
def create():
    template = os.path.join(templates_folder, "new.html.mako")
    
    if request.method.lower() == "get":
        return render(template=template)
        
    else:
        return method_not_supported_message(request.method.lower())
Пример #50
0
def login_view():
    username = request.form["username"]
    password = request.form["password"]
    user = authenticate(username, password)
    if user is None:
        abort(400)
    login(user)
    return render(user, status=200)
Пример #51
0
def dij(graph,src_id,tar_id):
    if src_id == tar_id:
        return 0
    dist = {src_id:0}
    c_dist = {src_id:1}
    # create a .png state
    #prev = {}

    Q = BinHeap()

    for v in graph.vertList:
        if v != src_id:
            dist[v] = INFINITE
            c_dist[v] = 0
            #prev[v] = None

        # create a .png state updating the vertex label
        Q.insert([v,dist[v]])

    #print Q.heapList
    #g = Graph()
    reng = render.render(graph,dist,c_dist)
    sleep(1.25)
    
    while not Q.isEmpty():
        u = Q.delMin()
        c_dist[u] = 1
        reng = render.render(graph,dist,c_dist)
        sleep(1.25)
        #try to color the deleted vertex
        #print u
        unb = graph.vertList[u].connectedTo
        for nb in unb:
            tup = [u,nb]
            #print type(unb[nb][0])
            alt = dist[u] + unb[nb][0]
            if Q.check(nb) :
                reng = render.render(graph,dist,c_dist,tup=tup)
            if alt < dist[nb]:
                #print 'altered',nb,dist[nb],'->',alt
                dist[nb] = alt
                sleep(1.25)
                #reng = render.render(graph,'0')
                #prev[nb] = u
                Q.editPriority([nb,alt])# changed Q.editPriority([v,alt]) --> ...([nb,alt] )
                reng = render.render(graph,dist,c_dist,tup=tup)
Пример #52
0
def view(owner_id):
    template = os.path.join(templates_folder, "index.html.mako")

    if owner_id:
        log.info("Getting all tasks for user %s."%owner_id)
        tasks = Task.query.filter_by(owner_id=owner_id).all()
    
        all_tasks = []
    
        for task in tasks:
            task_dict_repr = task.__dict__
            task_dict_repr = remove_unwanted_keyvalue(task_dict_repr)
            all_tasks.append(task_dict_repr)
        
        return render(result=dict(all_tasks=all_tasks), template=template)
    else:
        log.info("No owner id specified. Returning empty.")
        
        return render(result=[], template=template)
Пример #53
0
def deploy(slug):
    """
    Deploy the latest app to S3 and, if configured, to our servers.
    """
    require("settings", provided_by=[production, staging])

    if not slug:
        print 'You must specify a project slug, like this: "deploy:slug"'
        return

    graphic_root = "%s/%s" % (app_config.GRAPHICS_PATH, slug)
    s3_root = "%s/graphics/%s" % (app_config.PROJECT_SLUG, slug)
    graphic_assets = "%s/assets" % graphic_root
    s3_assets = "%s/assets" % s3_root

    graphic_config = _graphic_config(slug)

    use_assets = getattr(graphic_config, "USE_ASSETS", True)
    default_max_age = getattr(graphic_config, "DEFAULT_MAX_AGE", None) or app_config.DEFAULT_MAX_AGE
    assets_max_age = getattr(graphic_config, "ASSETS_MAX_AGE", None) or app_config.ASSETS_MAX_AGE

    update_copy(slug)

    if use_assets:
        assets.sync(slug)

    render.render(slug)

    flat.deploy_folder(
        graphic_root,
        s3_root,
        headers={"Cache-Control": "max-age=%i" % default_max_age},
        ignore=["%s/*" % graphic_assets],
    )

    # Deploy parent assets
    flat.deploy_folder("www", app_config.PROJECT_SLUG, headers={"Cache-Control": "max-age=%i" % default_max_age})

    if use_assets:
        flat.deploy_folder(graphic_assets, s3_assets, headers={"Cache-Control": "max-age=%i" % assets_max_age})

    print ""
    print "%s URL: %s/graphics/%s/" % (env.settings.capitalize(), app_config.S3_BASE_URL, slug)
Пример #54
0
def rendermail(template, to, subject, sender=None, sender_name=None, **kwds):
    html = render(
        template, to=to, sender=sender, sender_name=sender_name, **kwds
    )
    html = html.strip()
    if DEBUG:
        print to
        print subject
        print html
    sendmail(to, subject, None, sender, html, sender_name)
Пример #55
0
def main():

	parser = ArgumentParser( prog = 'gvanim' )
	parser.add_argument( 'animation', nargs = '?', type = FileType( 'r' ), default = stdin, help = 'The file containing animation commands (default: stdin)' )
	parser.add_argument( '--delay', '-d', default = '100', help = 'The delay (in ticks per second, default: 100)' )
	parser.add_argument( 'basename', help = 'The basename of the generated file' )
	args = parser.parse_args()

	ga = animation.Animation()
	ga.parse( args.animation )
	render.gif( render.render( ga.graphs(), args.basename, 'png' ), args.basename, args.delay )
Пример #56
0
    def save(self):
        if self.body:
            self.body = self.body.strip()
            self.body_html = render(self.body, 'markdown')
            if not settings.COMMENTS_FOLLOW:
                self.body_html = nofollow(self.body_html)
        if not self.id:
            # Get the object being commented on
            comment_on = self.content_type.get_object_for_this_type(pk=self.object_id)

            if isinstance(comment_on, CommentNode):
                # This is a reply to another comment - adopt its content type
                # and object id so this comment is associated with the correct
                # object.
                self.reply_to_id = self.object_id
                self.content_type = comment_on.content_type
                self.object_id = comment_on.object_id

                # We need to update the whole tree to the right of the comment
                target_rght = comment_on.rght - 1
                cursor = connection.cursor()
                cursor.execute("""
                UPDATE comment_nodes
                SET rght = rght + 2
                WHERE content_type_id = %s
                  AND object_id = %s
                  AND rght > %s""" % (self.content_type.id, self.object_id, target_rght))
                cursor.execute("""
                UPDATE comment_nodes
                SET lft = lft + 2
                WHERE content_type_id = %s
                  AND object_id = %s
                  AND lft > %s""" % (self.content_type.id, self.object_id, target_rght))
                self.lft = target_rght + 1
                self.rght = target_rght + 2
            else:
                # This is a new root comment
                cursor = connection.cursor()
                cursor.execute("""
                SELECT MAX(rght)
                FROM comment_nodes
                WHERE content_type_id = %s
                  AND object_id = %s""", (self.content_type.id, self.object_id))
                row = cursor.fetchone()
                current_max_rght = row[0]
                if current_max_rght is None:
                    # There are no comments for the content object so far
                    self.lft = 1
                    self.rght = 2
                else:
                    # Put this comment at the top level
                    self.lft = current_max_rght + 1
                    self.rght = current_max_rght + 2
        super(CommentNode, self).save()
Пример #57
0
def app(env, start_response):
    content = render.render()
    content = content.encode('utf-8')
    L = len(content)

    start_response('200 OK',
            [
                ('Content-Length', str(L)),
                ('Content-Type', 'text/html; charset=utf-8'),
            ])
    return [content]
Пример #58
0
def cluster(args, points):
    cmds = []
    for algorithm in HYPERPARAMS:
        hyperparams = list(itertools.product(*HYPERPARAMS[algorithm].values()))
        for h in hyperparams:
            params = zip(HYPERPARAMS[algorithm].keys(), h)
            pstr = ""
            algparam = algorithm
            for k, v in params:
                pstr += " -%s %s" % (k, v)
                algparam+= "-%s" % v
            odir = os.path.join(args.outdir, algparam)
            cmd = "java -cp %s de.lmu.ifi.dbs.elki.application.KDDCLIApplication -dbc.in %s -algorithm %s %s %s -evaluator AutomaticEvaluation -resulthandler ResultWriter -out %s" % (args.elki, args.infile, algorithm, OVERALLPARAMS, pstr, odir)
            cmds.append((algparam, odir, cmd))
    
    random.shuffle(cmds)
    idre = re.compile("^ID=([0-9]+) ")
    for algparam, odir, cmd in cmds:
        print >> sys.stderr, cmd
        os.system("time %s" % cmd)

        idx_to_cluster = {}
        # Now, read the clusters and visualize them against the tSNE points.
        for f in glob.glob("%s/cluster_*" % odir) + glob.glob("%s/noise.txt" % odir):
            if f == "%s/noise.txt" % odir:
                cluster = -1
            else:
                cluster = int(re.search("cluster_([0-9]+).txt", f).group(1))
            for l in open(f):
                if l[0] == "#": continue
                idx = int(idre.search(l).group(1))-1
                idx_to_cluster[idx] = cluster
        if len(idx_to_cluster) == 0: continue
        if len(idx_to_cluster) != len(points):
            print >> sys.stderr, "WARNING: len(idx_to_cluster) %d != len(points) %d" % (len(idx_to_cluster), len(points))
            continue
        labels = []
        for i in range(len(points)):
            labels.append(idx_to_cluster[i])
        assert len(labels) == len(points)
        render(labels, points, filename="%s/%s.png" % (odir, algparam))
Пример #59
0
def main():
    ank_version = pkg_resources.get_distribution("AutoNetkit").version
    log.info("AutoNetkit %s" % ank_version)

    import optparse
    opt = optparse.OptionParser()
    opt.add_option('--file', '-f', default= None, help="Load topology from FILE")        
    opt.add_option('--monitor', '-m',  action="store_true", default= False, help="Monitor input file for changes")        
    options, arguments = opt.parse_args()

    input_filename = options.file
    if not options.file:
        input_filename = "ank.graphml"

    anm = build_network(input_filename)
    anm.save()
    nidb = compile_network(anm)
    render.render(nidb)
    #deploy_network()

    if options.monitor:
        try:
            log.info("Monitoring for updates...")
            while True:
                time.sleep(0.2)
                if change_monitor.check_for_change(input_filename, anm):
                    try:
                        log.info("Input graph updated, recompiling network")
                        anm = build_network(input_filename)
                        anm.save()
                        nidb = compile_network(anm)
                        render.render(nidb)
                        log.info("Monitoring for updates...")
                    except:
                        # TODO: remove this, add proper warning
                        log.warn("Unable to build network")
                        pass
        except KeyboardInterrupt:
            log.info("Exiting")
Пример #60
0
    def rendered_content(self):
        if self.is_dir:
            raise Exception("The path is a directory: " + self.path)

        if not self.mime_type:
            raise Exception("Cannot render the content: " + self.path)

        if self.mime_type == "text/x-markdown":
            return render("view_md.html", file=self, content=Markup(markdown.markdown(self.content)))
        elif self.ext == ".html":
            return render_string(self.content)
        else:
            return self.content