Esempio n. 1
0
def _create_template(data, key, keys):
    try:
        data = data[key]['properties']
    except:
        return

    properties, descriptions, are_links = [], [], []

    for k in data.keys():
        properties.append(k)

        try:
            descriptions.append(str(data[k]['description'].replace("\n", "")))
        except:
            descriptions.append('NA')

        keys = [i.lower() for i in keys]

        if k.lower() in keys:
            are_links.append('True')
        else:
            are_links.append('False')

    obj = {}
    obj['name'] = key
    obj['info'] = "Description not available at the moment."
    obj['properties'] = []

    for i, j, k in zip(properties, descriptions, are_links):
        obj['properties'].append({'name': i, 'info': j, 'islink': k})

    with open(curdir + '/Files/' + key + '.html', 'w') as file:
        file.write(get_template().render(obj=obj))
Esempio n. 2
0
 def generate_struct_code(self, prefix):
     TEMPLATE_FILE = "fc_layer_struct.c"
     _template = template.get_template(TEMPLATE_FILE)
     code = _template.render(prefix=prefix,
                             uuid=prefix,
                             input_size=self.input_size,
                             output_size=self.output_size)
     return code
Esempio n. 3
0
 def generate_comp_code(self, prefix, test_mode):
     TEMPLATE_FILE = "quan_layer_comp.c"
     _template = template.get_template(TEMPLATE_FILE)
     code = _template.render(prefix=prefix,
                             input_size=self.input_size,
                             output_size=self.output_size,
                             q_min=self.q_min,
                             q_max=self.q_max,
                             zero_point=self.zero_point,
                             test_mode=test_mode)
     return code
Esempio n. 4
0
File: page.py Progetto: ahernp/pmcm
def edit_page(name):
    template = get_template()
    try:
        page_content = escape(read_page(name))
    except IOError as e:
        page_content = ""
    context = populate_context(
        {
            "title": name,
            "content": EDIT_TEMPLATE.format(name=name, content=page_content),
            "mainmenu-extra": EDIT_MAINMENU_EXTRA.format(name=name),
        }
    )
    return template.format(**context)
Esempio n. 5
0
 def generate_comp_code(self, prefix, test_mode):
     TEMPLATE_FILE = "dequan_layer_comp.c"
     _template = template.get_template(TEMPLATE_FILE)
     scale_numerator, scale_denominator, scale_exponent = get_quan_multiplier(self.scale)
     code = _template.render(prefix=prefix,
                             input_size = self.input_size,
                             output_size = self.output_size,
                             zero_point = self.zero_point,
                             scale_numerator = scale_numerator,
                             scale_denominator = scale_denominator,
                             scale_exponent = scale_exponent,
                             scale = self.scale,
                             test_mode = test_mode)
     return code
Esempio n. 6
0
 def generate_comp_code(self, prefix, test_mode):
     TEMPLATE_FILE = "fc_layer_comp.c"
     _template = template.get_template(TEMPLATE_FILE)
     code = _template.render(prefix=prefix,
                             input_size=self.input_size,
                             output_size=self.output_size,
                             weights=self.weights,
                             bias=self.bias,
                             input_offset=self.input_offset,
                             weight_offset=self.weight_offset,
                             output_offset=self.output_offset,
                             mantissa_numerator=self.mantissa_numerator,
                             mantissa_denominator=self.mantissa_denominator,
                             exponent=self.exponent,
                             test_mode=test_mode)
     return code
Esempio n. 7
0
 def generate_comp_code(self, prefix, test_mode):
     TEMPLATE_FILE = "tanh_layer_comp.c"
     _template = template.get_template(TEMPLATE_FILE)
     input_scale_numerator, input_scale_denominator = fractionation(self.input_scale)
     output_scale_numerator, output_scale_denominator = fractionation(self.output_scale)
     code = _template.render(prefix=prefix,
                             input_size = self.input_size,
                             output_size = self.output_size,
                             input_offset = self.input_offset,
                             output_offset = self.output_offset,
                             input_scale_numerator = input_scale_numerator,
                             input_scale_denominator = input_scale_denominator,
                             output_scale_numerator = output_scale_numerator,
                             output_scale_denominator = output_scale_denominator,
                             test_mode = test_mode)
     return code
Esempio n. 8
0
def site_map():
    template = get_template()
    filenames = os.listdir(PAGES_PATH)
    filenames.sort()
    sitemap_rows = ""
    for filename in filenames:
        mtime = os.path.getmtime(os.path.join(PAGES_PATH, filename))
        modified_time = datetime.fromtimestamp(mtime).isoformat()
        sitemap_rows += SITEMAP_ROW.format(name=filename,
                                           modified_time=modified_time)
    context = populate_context({
        "title":
        "Sitemap",
        "content":
        SITEMAP_TEMPLATE.format(sitemap_rows=sitemap_rows),
    })
    return template.format(**context)
Esempio n. 9
0
File: page.py Progetto: ahernp/pmcm
def view_page(name):
    try:
        template = get_template()
        page_content = read_page(name)
        update_history(name)
        context = populate_context(
            {
                "title": name,
                "content": markdown_to_html("[TOC]\n\n" + page_content),
                "mainmenu-extra": VIEW_MAINMENU_EXTRA.format(name=name),
            }
        )
        html = template.format(**context)
        page_cache[name] = page_content
        return html
    except IOError as e:
        return edit_page(name)
Esempio n. 10
0
def view_uploads():
    template = get_template()
    upload_rows = ""
    for directory in UPLOAD_DIRS:
        directory_path = os.path.join(MEDIA_ROOT, directory)
        filenames = os.listdir(directory_path)
        filenames.sort()
        for filename in filenames:
            mtime = os.path.getmtime(os.path.join(directory_path, filename))
            modified_time = datetime.fromtimestamp(mtime).isoformat()
            upload_rows += UPLOAD_ROW.format(dir=directory,
                                             name=filename,
                                             modified_time=modified_time)
    context = populate_context({
        "title":
        "Sitemap",
        "content":
        UPLOADS_TEMPLATE.format(upload_rows=upload_rows),
    })
    return template.format(**context)
Esempio n. 11
0
def conversion(pid, offset, sequences, directory, file_count):
    """
    This function calls all functions required for the full latex to png conversion for a subset of the sequences.
    It is meant to be called for a single process. The respective subset depends on the given offset.

    :param pid: The identifier of a process i with i=0,1,2,.. .
    :param offset: The subset of indices the process will process gets computed by pid * offset - (pid+1) * offset.
    :param sequences: The list of sequences that is being processed.
    :param directory: The directory path which the png files should be written to.
    :param file_count: The amount of files already in the directory. This is required to generate file names.
    :return: The return value serves as synchronization point for ray and is of no other use.
    """

    start_index = pid * offset
    end_index = (pid + 1) * offset
    end_index = min(end_index, len(sequences))

    latex = template.get_template(sequences[start_index:end_index])
    name = str(file_count + start_index)

    file = pdflatex(latex, directory, name)
    file = pdf2png(directory, file, name)

    return True
Esempio n. 12
0
def main():
    form_values = get_form_values()
    query = get_db_query(form_values)
    table = get_table(query)
    template.get_template(table)
Esempio n. 13
0
        # noinspection PyProtectedMember
        BASE_DIR = sys._MEIPASS
    else:
        BASE_DIR = os.path.dirname(sys.executable)

else:
    # unfrozen
    BASE_DIR = os.path.dirname(os.path.realpath(__file__))

TEMP_FOOTAGE_NAME = "TEMP_FOOTAGE_%05d"
RENAME_PATTERN = TEMP_FOOTAGE_NAME + "%s"
RAW_PAD_REG = re.compile('\d+$')
FMT_PAD_REG = re.compile('%\d+d$')
SEP_REG = re.compile('[\._]$')
ASCII_REG = re.compile(r'\A[\x00-\x7f]*\Z')
TEMPLATE = template.get_template()
config_f = open(template.get_config_path(), 'r')
CONFIG = json.load(config_f)
config_f.close()


def _get_sequence_path_dic(folder_path):
    """
    src_pathは_normalize_padding_file_nameで%4d等に正規化された状態ではいります。
    
    :param folder_path:
    :return: { src_path: { "minPad": int, "count": int }, ... }
    """
    dst_file_names_dic = {}
    for root, dirs, files in os.walk(folder_path):
        for file_name in files:
Esempio n. 14
0
LITERAL_DIR = os.path.join(current_dir, 'literal')

for literal_filename in os.listdir(LITERAL_DIR):
    literal_file_path = os.path.join(LITERAL_DIR, literal_filename)
    target_file_path = os.path.join(TARGET_DIR, literal_filename)

    try:
        shutil.copytree(literal_file_path, target_file_path)
    except OSError as e:
        if e.errno == errno.ENOTDIR:
            shutil.copyfile(literal_file_path, target_file_path)
        else:
            raise

index_template = template.get_template(template_index_path)
index_html = template.apply_base_template(
    '::1',
    ['David Kerkeslager'],
    [],
    "David Kerkeslager's personal website",
    index_template.substitute(menu=menu.MENU),
)

with open(target_index_path, 'w') as target_index_file:
    target_index_file.write(index_html)

posts_target_dir = os.path.join(TARGET_DIR, 'posts')
posts_src_dir = os.path.join(current_dir, 'posts')

post_links = list(blog.generate(posts_src_dir, posts_target_dir))
Esempio n. 15
0
def deploy_vm(c, a):
    deploy_args = {}
    if a['--number']:
        n = int(a['--number'])
    else:
        n = 1
    if a['INSTANCE']:
        deploy_args['name'] = a['INSTANCE']
        deploy_args['displayname'] = a['INSTANCE']
    if a['--group']:
        deploy_args['group'] = a['--group']
    if a['--template']:
        try:
            template = get_template(c, a['--template'])[0]
            deploy_args['templateid'] = template.id
        except:
            print "Unable to get templateid for %s" % a['--template']
            sys.exit(1)
    if a['--offering']:
        try:
            offering = get_offering(c, a['--offering'])[0]
            deploy_args['serviceofferingid'] = offering.id
        except:
            print "Unable to get offeringid for %s" % a['--offering']
            sys.exit(1)
    if a['--network']:
        try:
            network = get_network(c, a['--network'])[0]
            deploy_args['networkids'] = network.id
        except:
            print "Unable to get networkid for %s" % a['--network']
            sys.exit(1)
    if a['--zone']:
        zone = get_zone(c, a['--zone'])[0]
        deploy_args['zoneid'] = zone.id
    else:
        zone = get_zone(c)[0]
        deploy_args['zoneid'] = zone.id
    if a['--sshkey']:
        try:
            sshkey = get_sshkey(c, a['--sshkey'])[0]
            deploy_args['keypair'] = sshkey.name
        except:
            print "Unable to get ssh key: %s" % a['--sshkey']
            sys.exit(1)
    if a['--user-data']:
        deploy_args['userdata'] = base64.b64encode(a['--user-data'])
    if a['--user-data-file']:
        if os.path.isfile(a['--user-data-file']):
            with open(a['--user-data-file']) as f:
                encoded = base64.b64encode(f.read())
            size = sys.getsizeof(encoded)
            deploy_args['userdata'] = encoded
    # Deploy it!
    res = []
    for i in range(n):
        if n > 1:
            append_hash = hashlib.new('sha1', str(random.randint(0,1000000))).hexdigest()[:3]
            deploy_args['name'] = "%s-%s" % (a['INSTANCE'], append_hash)
            deploy_args['displayname'] = "%s-%s" % (a['INSTANCE'], append_hash)
        res.append(c.deploy_virtualmachine(**deploy_args))
    vms = []
    if a['--tags']:
        tags = {}
        for tag in a['--tags'].split(','):
            regex = re.compile(r"\b(\w+)\s*:\s*([^:]*)(?=\s+\w+\s*:|$)")
            tags.update(dict(regex.findall(tag)))
    if not a['--nowait']:
        for j in res:
            if a['--tags']:
                c.create_tags(resourceids=j.id, resourcetype='UserVm', tags=tags)
            vms.append(j.get_result())
    else:
        for j in res:
            if a['--tags']:
                c.create_tags(resourceids=j.id, resourcetype='UserVm', tags=tags)
            vms.append(c.list_virtualmachines(id=j.id)[0])
    return vms
Esempio n. 16
0
def search(search_term):
    def find_name_matches(regex, filenames):
        name_match_rows = []
        for filename in filenames:
            match = regex.search(filename)
            if match:
                name_match_rows.append(NAME_MATCH_ROW.format(name=filename))
        return NAME_MATCHES.format(
            number_name_matches=len(name_match_rows),
            name_match_rows="\n".join(name_match_rows),
        )

    def find_content_matches(regex):
        content_matches = []
        for filename, content in page_cache.items():
            match = regex.search(content)
            if match:
                prev_line_end_pos = content.rfind("\n", 0, match.start())
                if prev_line_end_pos == -1:
                    prev_line_end_pos = 0
                next_line_end_pos = content.find("\n", match.end())
                if next_line_end_pos == -1:
                    next_line_end_pos = len(content)
                content_matches.append(
                    {
                        "content": "{prefix}<b>{match}</b>{suffix}".format(
                            prefix=content[prev_line_end_pos : match.start()],
                            match=content[match.start() : match.end()],
                            suffix=content[match.end() : next_line_end_pos],
                        ),
                        "name": filename,
                        "number_content_matches": len(regex.findall(content)),
                    }
                )

        content_matches.sort(key=lambda item: item["name"])
        content_matches.sort(
            key=lambda item: item["number_content_matches"], reverse=True
        )

        content_match_rows = ""
        for content_match in content_matches:
            content_match_rows += CONTENT_MATCH_ROW.format(**content_match)

        return CONTENT_MATCHES.format(
            number_content_pages=str(len(content_matches)),
            content_match_rows=content_match_rows,
        )

    regex = re.compile(search_term, re.IGNORECASE)
    template = get_template()
    filenames = os.listdir(PAGES_PATH)
    filenames.sort()
    name_matches = find_name_matches(regex, filenames)
    content_matches = find_content_matches(regex)

    context = populate_context(
        {
            "searchterm": f'value="{search_term}"',
            "title": "Search Results",
            "content": SEARCH_TEMPLATE.format(
                search_term=search_term,
                name_matches=name_matches,
                content_matches=content_matches,
            ),
        }
    )

    return template.format(**context)
Esempio n. 17
0
from math import tanh
import template

TAHN_P_RANGE = 300
X_SCALE_DOWN = 100.0
Y_SCALE_UP = 100

tanh_table = [None] * TAHN_P_RANGE;
for x_100 in range (0, TAHN_P_RANGE):
    x = x_100 / X_SCALE_DOWN
    tanh_table[x_100] = tanh(x) * Y_SCALE_UP

TEMPLATE_FILE = "tanh_lookup_table.h"
_template = template.get_template(TEMPLATE_FILE)
code = _template.render(tanh_p_range = TAHN_P_RANGE,
                        tanh_x_scale_up = int(X_SCALE_DOWN),
                        tanh_y_scale_down = Y_SCALE_UP,
                        tanh_table = tanh_table)

OUTPUT_FILE = f"/tmp/tanh_lookup_table.h"
with open(OUTPUT_FILE, "w") as output_file:
    output_file.write(code)
Esempio n. 18
0
def deploy_vm(c, a):
    deploy_args = {}
    if a['--number']:
        n = int(a['--number'])
    else:
        n = 1
    if a['INSTANCE']:
        deploy_args['name'] = a['INSTANCE']
        deploy_args['displayname'] = a['INSTANCE']
    if a['--group']:
        deploy_args['group'] = a['--group']
    if a['--template']:
        try:
            template = get_template(c, a['--template'])[0]
            deploy_args['templateid'] = template.id
        except:
            print "Unable to get templateid for %s" % a['--template']
            sys.exit(1)
    if a['--offering']:
        try:
            offering = get_offering(c, a['--offering'])[0]
            deploy_args['serviceofferingid'] = offering.id
        except:
            print "Unable to get offeringid for %s" % a['--offering']
            sys.exit(1)
    if a['--network']:
        try:
            network = get_network(c, a['--network'])[0]
            deploy_args['networkids'] = network.id
        except:
            print "Unable to get networkid for %s" % a['--network']
            sys.exit(1)
    if a['--zone']:
        zone = get_zone(c, a['--zone'])[0]
        deploy_args['zoneid'] = zone.id
    else:
        zone = get_zone(c)[0]
        deploy_args['zoneid'] = zone.id
    if a['--sshkey']:
        try:
            sshkey = get_sshkey(c, a['--sshkey'])[0]
            deploy_args['keypair'] = sshkey.name
        except:
            print "Unable to get ssh key: %s" % a['--sshkey']
            sys.exit(1)
    if a['--user-data']:
        deploy_args['userdata'] = base64.b64encode(a['--user-data'])
    if a['--user-data-file']:
        if os.path.isfile(a['--user-data-file']):
            with open(a['--user-data-file']) as f:
                encoded = base64.b64encode(f.read())
            size = sys.getsizeof(encoded)
            deploy_args['userdata'] = encoded
    # Deploy it!
    res = []
    for i in range(n):
        if n > 1:
            append_hash = hashlib.new('sha1', str(random.randint(
                0, 1000000))).hexdigest()[:3]
            deploy_args['name'] = "%s-%s" % (a['INSTANCE'], append_hash)
            deploy_args['displayname'] = "%s-%s" % (a['INSTANCE'], append_hash)
        res.append(c.deploy_virtualmachine(**deploy_args))
    vms = []
    if a['--tags']:
        tags = {}
        for tag in a['--tags'].split(','):
            regex = re.compile(r"\b(\w+)\s*:\s*([^:]*)(?=\s+\w+\s*:|$)")
            tags.update(dict(regex.findall(tag)))
    if not a['--nowait']:
        for j in res:
            if a['--tags']:
                c.create_tags(resourceids=j.id,
                              resourcetype='UserVm',
                              tags=tags)
            vms.append(j.get_result())
    else:
        for j in res:
            if a['--tags']:
                c.create_tags(resourceids=j.id,
                              resourcetype='UserVm',
                              tags=tags)
            vms.append(c.list_virtualmachines(id=j.id)[0])
    return vms
Esempio n. 19
0
LITERAL_DIR = os.path.join(current_dir, 'literal')

for literal_filename in os.listdir(LITERAL_DIR):
    literal_file_path = os.path.join(LITERAL_DIR, literal_filename)
    target_file_path = os.path.join(TARGET_DIR, literal_filename)
    
    try:
        shutil.copytree(literal_file_path, target_file_path)
    except OSError as e:
        if e.errno == errno.ENOTDIR:
            shutil.copyfile(literal_file_path, target_file_path)
        else:
            raise

index_template = template.get_template(template_index_path)
index_html = template.apply_base_template(
    '::1',
    ['David Kerkeslager'],
    [],
    "David Kerkeslager's personal website",
    index_template.substitute(menu = menu.MENU),
)

with open(target_index_path, 'w') as target_index_file:
    target_index_file.write(index_html)

posts_target_dir = os.path.join(TARGET_DIR, 'posts')
posts_src_dir = os.path.join(current_dir, 'posts')

post_links = list(blog.generate(posts_src_dir, posts_target_dir))