Best Python code snippet using localstack_python
generate_java_entries.py
Source:generate_java_entries.py  
1# Copyright © 2021 Teamapps.org2# Licensed under the Apache License, Version 2.03"""4Generates Entries for EmojiIcon Library or CSV with emoji data5"""6import argparse7import io8import os9import sys10import unicodedata11import re12REG_IND_LETTR = ('1F1E6 1F1E7 1F1E8 1F1E9 1F1EA 1F1EB 1F1EC 1F1ED '13                 '1F1EE 1F1EF 1F1F0 1F1F1 1F1F2 1F1F3 1F1F4 1F1F5 '14                 '1F1F6 1F1F7 1F1F8 1F1F9 1F1FA 1F1FB 1F1FC 1F1FD '15                 '1F1FE 1F1FF').split()16TAG_LAT_LETTR = ('E0061 E0062 E0063 E0064 E0065 E0066 E0067 E0068 E0069 E006A '17                 'E006B E006C E006D E006E E006F E0070 E0071 E0072 E0073 E0074 '18                 'E0075 E0076 E0077 E0078 E0079 E007A').split()19SKIP_STATUSES = ('unqualified', 'non-fully-qualified', 'minimally-qualified')20FILE_PREFIX = 'u'21WORKING_DIR = os.path.dirname(os.path.abspath(__file__))22TEST_INPUT_PATH = os.path.join(WORKING_DIR, 'emoji-test-13.1.txt')23def strip_accents(s):24    return ''.join(c for c in unicodedata.normalize('NFD', s)25                    if unicodedata.category(c) != 'Mn')26def append_to_file(fpath, data, enc='utf-8'):27    with io.open(fpath, 'a', encoding=enc) as fp:28        fp.write(data)29def init_file(fpath, data, enc='utf-8'):30    with io.open(fpath, 'w', encoding=enc) as fp:31        fp.write(data)32def parse_emoji_test_file(filename):33    """34    Parses Unicode's 'emoji-test.txt' file (available from35    http://unicode.org/Public/emoji/M.m/ where 'M.m' is the version number)36    and returns a list of code points.37    """38    with io.open(filename, encoding='utf-8') as fp:39        lines = fp.read().splitlines()40    emoji_list = []41    for line in lines:42        line = line.strip()43        if not line or line.startswith('#'):44            continue45        codepoints, status_emoname = line.split(';')46        status = status_emoname.split('#', 1)[0].strip()47        emo_info = status_emoname.split('#', 1)[1].strip()48        emo_unicode = emo_info.split(' ')[0].strip()49        emo_version = emo_info.split(' ')[1].strip()50        emo_name = emo_info.split(emo_version)[1].strip()51        emo_data = [emo_unicode, emo_name, emo_version]52        # print('; '.join(emo_data))53        if status in SKIP_STATUSES:54            continue55        cdpts = codepoints.strip().split();56        emoji_list.append([cdpts, emo_data])57    return emoji_list58def emoji_data(emoji):59    cps = emoji[0]60    emoji_data = emoji[1]61    emoji_unicode =  emoji_data[0]62    emoji_name = emoji_data[1]63    # determine if it's a country/regional flag64    is_flag = False65    if len(cps) > 1 and cps[1] in (REG_IND_LETTR + TAG_LAT_LETTR):66        is_flag = True67    cps_html = ''.join('&#x{};'.format(cp) for cp in cps)68    # filenames have no 'FE0F' or 'E007F' components69    cps_filename = [cp for cp in cps if cp not in ('FE0F', 'E007F')]70    filename = FILE_PREFIX + '_'.join(cps_filename).lower()71    png_dir = 'flags_png' if is_flag else 'png'72    svg_dir = 'flags' if is_flag else 'svg'73    sbw_dir = 'flags_bw' if is_flag else 'svg_bw'74    png_file = "{}/{}.png".format(png_dir, filename)75    svg_file = "{}/{}.svg".format(svg_dir, filename)76    sbw_file = "{}/{}.svg".format(sbw_dir, filename)77    base_name = emoji_name.split(':', 1)[0].strip()78    try:79        variant = emoji_name.split(':', 1)[1].strip()80        safe_name = "{}__{}".format(base_name, variant)81    except IndexError:82        variant = ''83        safe_name = base_name84    if is_flag:85        flag_name = emoji_name.split(':', 1)[1].strip()86        base_name = flag_name # for csv87        safe_country = strip_accents(flag_name)88        safe_name = "flag_{}".format(safe_country)89        variant = ''90    safe_name = re.sub(r' ', '_', safe_name) # space to underline91    safe_name = re.sub(r'#', 'hash', safe_name) # keycap #92    safe_name = re.sub(r'[*]', 'star', safe_name) # keycap *93    safe_name = re.sub(r'keycap__', 'keycap_', safe_name) # keycap__94    safe_name = re.sub(r'ñ', 'n', safe_name) # piñata95    safe_name = re.sub(r'^1st(.*)', r'first\1', safe_name) # beginning with number96    safe_name = re.sub(r'^2nd(.*)', r'second\1', safe_name) # beginning with number97    safe_name = re.sub(r'^3rd(.*)', r'third\1', safe_name) # beginning with number98    safe_name = re.sub(r'[\W+]', '', safe_name).lower() # remove all non-word characters99    # return [i, emoji_unicode, safe_name, emoji_name, base_name, variant, '_'.join(cps), cps_html, filename, png_file, svg_file, sbw_file]100    return {101        'emoji_unicode': emoji_unicode,102        'safe_name': safe_name,103        'emoji_name': emoji_name,104        'base_name': base_name,105        'variant': variant,106        'cps': cps,107        'cps_html': cps_html,108        'filename': filename,109        'png_file': png_file,110        'svg_file': svg_file,111        'sbw_file': sbw_file,112        'is_flag' : is_flag113    }114def write_csv(emoji_list):115    csv_file = os.path.join(WORKING_DIR, '..', 'emoji.csv')116    # csv_header = '\t'.join(["emoji_unicode", "emoji_name", "codepoints_", "cps_html", "png_file", "svg_file", "sbw_file"])+"\n"117    csv_header = '"number", "emoji_unicode", "safe_name", "emoji_name", "base_name", "variant",  "codepoints_", "cps_html", "png_file", "svg_file", "sbw_file" \n'118    init_file(csv_file, csv_header)119    for i, emoji in enumerate(emoji_list, 1):120        emo_data = emoji_data(emoji)121        #csv_line = '"{}", "{}", "{}", "{}", "{}", "{}", "{}", "{}", "{}", "{}", "{}" \n'.format(i, emoji_unicode, safe_name, emoji_name, base_name, variant, '_'.join(cps), cps_html, png_file, svg_file, sbw_file)122        csv_line = '"{}", "{}", "{}", "{}", "{}", "{}", "{}", "{}", "{}", "{}", "{}" \n'.format(i, emo_data['emoji_unicode'], emo_data['safe_name'], emo_data['emoji_name'], emo_data['base_name'], emo_data['variant'], '_'.join(emo_data['cps']), emo_data['cps_html'], emo_data['filename'], emo_data['png_file'], emo_data['svg_file'], emo_data['sbw_file'])123        # csv_line = emo_data["safe_name"]124        append_to_file(csv_file, csv_line)125def write_java(emoji_list):126    java_file = os.path.join(WORKING_DIR, 'emoji.java')127    java_header = '        // generated entries \n'128    init_file(java_file, java_header)129    for i, emoji in enumerate(emoji_list, 1):130        emo_data = emoji_data(emoji)131        #csv_line = '"{}", "{}", "{}", "{}", "{}", "{}", "{}", "{}", "{}", "{}", "{}" \n'.format(i, emoji_unicode, safe_name, emoji_name, base_name, variant, '_'.join(cps), cps_html, png_file, svg_file, sbw_file)132        # csv_line = '"{}", "{}", "{}", "{}", "{}", "{}", "{}", "{}", "{}", "{}", "{}" \n'.format(i, emo_data['emoji_unicode'], emo_data['safe_name'], emo_data['emoji_name'], emo_data['base_name'], emo_data['variant'], '_'.join(emo_data['cps']), emo_data['cps_html'], emo_data['filename'], emo_data['png_file'], emo_data['svg_file'], emo_data['sbw_file'])133        # csv_line = emo_data["safe_name"]134        # append_to_file(csv_file, csv_line)135        # java_line = 'public static final EmojiIcon {} = create("{}", "{}", "{}", "{}", "{}", "{}", "{}", "{}", "{}", "{}", "{}");\n'.format(safe_name.upper(), i, emoji_unicode, safe_name, emoji_name, base_name, variant, '_'.join(cps), cps_html, png_file, svg_file, sbw_file)136        is_flag_java_boolean = "true" if emo_data['is_flag'] else "false"137        java_line = '        public static final EmojiIcon {} = create({}, "{}", "{}", {});\n'.format(emo_data['safe_name'].upper(), i, emo_data['emoji_unicode'], emo_data['safe_name'].upper(), is_flag_java_boolean)138        append_to_file(java_file, java_line)139def main(args=None):140    parser = argparse.ArgumentParser(description=__doc__)141    parser.add_argument(142        '-C',143        '--csv',144        help="generates csv instead of html",145        action='store_true',146    )147    parser.add_argument(148        '-J',149        '--java',150        help="generates java",151        action='store_true',152    )153    opts = parser.parse_args(args)154    emoji_list = parse_emoji_test_file(TEST_INPUT_PATH)155    if opts.csv:156        write_csv(emoji_list)157    elif opts.java:158        write_java(emoji_list)159    else:160        write_java(emoji_list)161if __name__ == "__main__":...utils.py
Source:utils.py  
1from typing import Union2from xml.sax.saxutils import escape3def get_unique_name(4    data: dict, base_name: str, count: Union[int, None] = None, separator: str = "_"5) -> str:6    """7    Check if the given `base_name` already exists as data key, if so it will keep8    trying to generate a new name based on the separator and count. If `name` for9    example is already taken, then `name_2` will be checked, if that is taken `name_3`10    and so forth.11    :param data: The object where the existence of the name as a key will be checked in.12    :param base_name: The name that will be checked in the data dict.13    :param count: The recursive count that must be checked.14    :param separator: The character that is placed between the `base_name` and the15        `count`.16    :return: The name that does not exist as key in the data dict.17    """18    keys = data.keys()19    new_name = f"{base_name}{separator}{count}" if count else base_name20    if new_name not in keys:21        return new_name22    return get_unique_name(data, base_name, count + 1 if count else 2, separator)23def safe_xml_tag_name(24    name: str, numeric_prefix: str = "tag-", empty_fallback: str = "empty-tag"25) -> str:26    """27    Returns a safe xml tag name by replacing invalid characters with a dash.28    :param name: The name that must be converted to a safe xml tag name.29    :param numeric_prefix: An xml tag name can't start with a number, so if that is30        the case, then this value will be prepended.31    :param empty_fallback: An xml tag name can't be empty, so if that is the case,32        then this fallback value will be returned.33    :return: A safe name that can be used as xml tag.34    """35    safe_name = ""36    for char in name:37        if char.isalnum():38            safe_name += char39        else:40            safe_name += "-"41    while "--" in safe_name:42        safe_name = safe_name.replace("--", "-")43    if safe_name.startswith("-"):44        safe_name = safe_name[1:]45    if safe_name.endswith("-"):46        safe_name = safe_name[:-1]47    if len(safe_name) > 0 and safe_name[0].isnumeric():48        safe_name = f"{numeric_prefix}{safe_name}"49    if len(safe_name) == 0:50        return empty_fallback51    return safe_name52def to_xml(val):53    """54    Encodes the given python value into an xml string. Does not return an entire55    xml document but instead a fragment just representing this value.56    :return: A string containing an xml fragment for the provided value.57    """58    if isinstance(val, bool):59        return "true" if val else "false"60    if isinstance(val, dict):61        return "".join([to_xml_elem(key, to_xml(val)) for key, val in val.items()])62    if isinstance(val, list):63        return "".join([to_xml_elem("item", to_xml(item)) for item in val])64    return escape(str(val))65def to_xml_elem(key, val):66    """67    Returns an xml element of type key containing the val, unless val is the68    empty string when it returns a closed xml element.69    :param key: The xml tag of the element to generate. This must be a valid xml tag70        name because it is not escaped.71    :param val: The value of the element to generate.72    :return: An xml element string.73    """74    if val == "":75        return f"<{key}/>"76    else:...api.py
Source:api.py  
1# THIS FILE IS AUTO-GENERATED. DO NOT EDIT2class {{api_name}}Api:3  def __init__(self, client, base_path = "{{base_path}}"):4    self.client = client5    self.base_path = base_path6{{#operations}}7  def {{operation_id}}(self, {{#parameters}}{{safe_name}}=None{{^last}}, {{/last}}{{/parameters}}):8    __query = {9      {{#query}}10      "{{name}}": client.to_query({{safe_name}}){{^last}},{{/last}}11      {{/query}}12    }13    {{#required}}14    if {{safe_name}} is None:15      raise Exception("Missing required parameter \"{{safe_name}}\"")16    {{/required}}17    {{^body_present}}18    body = None19    {{/body_present}}20    format_args = {}21    path = "{{path}}"22    {{#parameters}}23    if "${{safe_name}}" in path:24      path = path.replace("${{safe_name}}", "%({{safe_name}})s")25      format_args["{{safe_name}}"] = {{safe_name}}26    {{/parameters}}27    ret = self.client.request("{{op}}", self.base_path + path % format_args, __query, body)28    if ret is not None:29      {{#success_type}}30      {{#custom}}31      from ..model.{{name}} import {{name}}32      ret = {{name}}.from_json(ret)33      {{/custom}}34      {{^custom}}35      pass36      {{/custom}}37      {{/success_type}}38    return ret...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
