def vformat(self, format_string, args, kwargs):
        matcher = re.compile(self._expr, re.VERBOSE)

        # special case of returning the object if the entire string
        # matches a single parameter
        try:
            result = re.match('^%s$' % self._expr, format_string, re.VERBOSE)
        except TypeError:
            return format_string.format(**kwargs)
        if result is not None:
            try:
                return kwargs[result.group("key")]
            except KeyError:
                pass

        # handle multiple fields within string via a callback to re.sub()
        def re_replace(match):
            key = match.group("key")
            default = match.group("default")

            if default is not None:
                if key not in kwargs:
                    return default
                else:
                    return "{%s}" % key
            return match.group(0)

        format_string = matcher.sub(re_replace, format_string)

        return Formatter.vformat(self, format_string, args, kwargs)
示例#2
0
 def vformat(self, format_string, args, kwargs):
     self.unused_args = {}
     ret = Formatter.vformat(self, format_string, args, kwargs)
     if not self.unused_args:
         return ret
     extra_data =  ', '.join('{0}={1}'.format(*kv) for kv in self.unused_args.items())
     return '{0} ({1})'.format(ret, extra_data)
示例#3
0
def pformat(temp, **fmt):
    """Format a template string partially.

    Examples
    --------
    >>> pformat("{a}_{b}", a='x')
    'x_{b}'
    """
    formatter = Formatter()
    mapping = _FormatDict(fmt)
    return formatter.vformat(temp, (), mapping)
示例#4
0
def make_tag():
    today = datetime.datetime.today()
    date = today.strftime(date_format)
    print(date)
    seq=1
    "git tag --list=release/%s/*" % date
    values={
        "date": date,
        "sequence": seq
    }
    formatter = Formatter()
    tag = formatter.vformat(tag_format, [], values)
    print(tag)
示例#5
0
def _write_to_file(table_a_dest,
                   genome_ids_a,
                   genome_ids_b,
                   common_prefix_a,
                   common_prefix_b,
                   calculations):
    '''

    :param table_a_dest:
    :type table_a_dest: filename
    :param genome_ids_a:
    :type genome_ids_a: list or genome ids
    :param common_prefix_a:
    :type common_prefix_a: string
    :param common_prefix_b:
    :type common_prefix_b: string
    :param calculations:
    :type calculations: list of clade_calcs instances
    '''
    with open(table_a_dest, 'a') as write_handle:
        # Print introduction about the strain comparison
        write_handle.write('#{} {} strains compared with {} {} strains\n'.format(len(genome_ids_a),
                                                                                 common_prefix_a,
                                                                                 len(genome_ids_b),
                                                                                 common_prefix_b))
        # Print the genome IDs involved in each of the strains
        write_handle.write('#IDs {}: {}\n'.format(common_prefix_a,
                                                  ', '.join(genome_ids_a)))
        write_handle.write('#IDs {}: {}\n'.format(common_prefix_b,
                                                  ', '.join(genome_ids_b)))

        # Print column headers for the data to come
        max_nton = len(genome_ids_a) // 2
        headers = _get_column_headers(max_nton)
        write_handle.write('#' + '\t'.join(headers))
        write_handle.write('\n')

        # Print data rows
        format_str = '\t'.join('{{{}}}'.format(key) for key in headers)
        from string import Formatter
        formatter = Formatter()
        for clade_calcs in calculations:
            write_handle.write(formatter.vformat(format_str, None, clade_calcs.values))
            write_handle.write('\n')
示例#6
0
 def resolve_conf(unresolved):
     """take a config with values using string formatting; apply string formatting until they all don't;
        returns (dict of things that could be resolved, dict of things that couldn't be resolved)"""
     f = Formatter()
     resolved = {}
     while unresolved:
         changed_something, missing_defs = False, []
         for k, v in unresolved.items():
             if isinstance(v, basestring) and v and tuple(f.parse(v))[0][1] is not None:
                 try:
                     unresolved[k] = f.vformat(v, [], resolved)
                     changed_something = True
                 except KeyError, e: # missing a definition; but could in the next pass if we changed something
                     missing_defs.append(e.args[0])
             else:
                 # non strings are, by definition, resolved; no recursion into complex data structures here
                 # items without format specifiers are also resolved
                 del unresolved[k]
                 resolved[k] = v
                 changed_something = True
         if not changed_something:
             break
    def on_query_completions(self, view, prefix, locations):
        # Only trigger within LaTeX
        if not view.match_selector(locations[0],
                "text.tex.latex"):
            return []

        point = locations[0]

        try:
            completions, prefix, post_brace, new_point_a, new_point_b = get_cite_completions(view, point, autocompleting=True)
        except UnrecognizedCiteFormatError:
            return []
        except NoBibFilesError:
            sublime.status_message("No bib files found!")
            return []
        except BibParsingError as e:
            sublime.status_message("Bibliography " + e.filename + " is broken!")
            return []

        # filter against keyword or title
        if prefix:
            completions = [comp for comp in completions if prefix.lower() in "%s %s" %
                                                    (
                                                        comp['keyword'].lower(),
                                                        comp['title'].lower())]
            prefix += " "

        # get preferences for formating of autocomplete entries
        cite_autocomplete_format = get_setting('cite_autocomplete_format',
            "{keyword}: {title}")

        formatter = Formatter()
        r = [(prefix + formatter.vformat(cite_autocomplete_format, (), completion),
              completion['keyword'] + post_brace) for completion in completions]

        # print "%d bib entries matching %s" % (len(r), prefix)

        return r
示例#8
0
def f(string, *args, **kwargs):
    """
    String safe substitute format method.
    If you pass extra keys they will be ignored.
    If you pass incomplete substitute map, missing keys will be left unchanged.
    :param string:
    :param kwargs:
    :return:

    >>> f('{foo} {bar}', foo="FOO")
    'FOO {bar}'
    >>> f('{} {bar}', 1)
    '1 {bar}'
    >>> f('{foo} {}', 1)
    '{foo} 1'
    >>> f('{foo} {} {bar} {}', '|', bar='BAR')
    '{foo} | BAR {}'
    >>> f('{foo} {bar}', foo="FOO", bro="BRO")
    'FOO {bar}'
    """
    formatter = Formatter()
    args_mapping = FormatTuple(args)
    mapping = FormatDict(kwargs)
    return formatter.vformat(string, args_mapping, mapping)
    def run(self, edit):
        # get view and location of first selection, which we expect to be just the cursor position
        view = self.view
        point = view.sel()[0].b
        print (point)
        # Only trigger within LaTeX
        # Note using score_selector rather than match_selector
        if not view.score_selector(point,
                "text.tex.latex"):
            return

        try:
            completions, prefix, post_brace, new_point_a, new_point_b = get_cite_completions(view, point)
        except UnrecognizedCiteFormatError:
            sublime.error_message("Not a recognized format for citation completion")
            return
        except NoBibFilesError:
            sublime.error_message("No bib files found!")
            return
        except BibParsingError as e:
            sublime.error_message("Bibliography " + e.filename + " is broken!")
            return
        except BibParsingError as e:
            sublime.error_message(e.message)
            return

        # filter against keyword, title, or author
        if prefix:
            completions = [comp for comp in completions if prefix.lower() in "%s %s %s" % 
                                                    (
                                                        comp['keyword'].lower(),
                                                        comp['title'].lower(),
                                                        comp['author'].lower())]

        # Note we now generate citation on the fly. Less copying of vectors! Win!
        def on_done(i):
            print ("latex_cite_completion called with index %d" % (i,) )

            # Allow user to cancel
            if i < 0:
                return

            keyword = completions[i]['keyword']
            # notify any plugins
            notification_thread = threading.Thread(
                target=run_plugin_command,
                args=(
                    'on_insert_citation',
                    keyword
                ),
                kwargs={
                    'stop_on_first': False,
                    'expect_result': False
                }
            )

            notification_thread.daemon = True
            notification_thread.start()

            cite = completions[i]['keyword'] + post_brace

            #print("DEBUG: types of new_point_a and new_point_b are " + repr(type(new_point_a)) + " and " + repr(type(new_point_b)))
            # print "selected %s:%s by %s" % completions[i][0:3]
            # Replace cite expression with citation
            # the "latex_tools_replace" command is defined in latex_ref_cite_completions.py
            view.run_command("latex_tools_replace", {"a": new_point_a, "b": new_point_b, "replacement": cite})
            # Unselect the replaced region and leave the caret at the end
            caret = view.sel()[0].b
            view.sel().subtract(view.sel()[0])
            view.sel().add(sublime.Region(caret, caret))

        # get preferences for formating of quick panel
        cite_panel_format = get_setting('cite_panel_format',
            ["{title} ({keyword})", "{author}"])

        completions_length = len(completions)
        if completions_length == 0:
            return
        elif completions_length == 1:
            # only one entry, so insert entry
            view.run_command("latex_tools_replace",
                {
                    "a": new_point_a,
                    "b": new_point_b,
                    "replacement": completions[0]['keyword'] + post_brace
                }
            )

            # Unselect the replaced region and leave the caret at the end
            caret = view.sel()[0].b
            view.sel().subtract(view.sel()[0])
            view.sel().add(sublime.Region(caret, caret))
        else:
            # show quick
            formatter = Formatter()
            view.window().show_quick_panel([[formatter.vformat(s, (), completion) for s in cite_panel_format] \
                                        for completion in completions], on_done)
    def run(self, edit):
        # get view and location of first selection, which we expect to be just the cursor position
        view = self.view
        point = view.sel()[0].b
        print (point)
        # Only trigger within LaTeX
        # Note using score_selector rather than match_selector
        if not view.score_selector(point,
                "text.tex.latex"):
            return

        try:
            completions, prefix, post_brace, new_point_a, new_point_b = get_cite_completions(view, point)
        except UnrecognizedCiteFormatError:
            sublime.error_message("Not a recognized format for citation completion")
            return
        except NoBibFilesError:
            sublime.error_message("No bib files found!")
            return
        except BibParsingError as e:
            sublime.error_message("Bibliography " + e.filename + " is broken!")
            return
        except BibParsingError as e:
            sublime.error_message(e.message)
            return

        # filter against keyword, title, or author
        if prefix:
            completions = [comp for comp in completions if prefix.lower() in "%s %s %s" % 
                                                    (
                                                        comp['keyword'].lower(),
                                                        comp['title'].lower(),
                                                        comp['author'].lower())]

        # Note we now generate citation on the fly. Less copying of vectors! Win!
        def on_done(i):
            print ("latex_cite_completion called with index %d" % (i,) )

            # Allow user to cancel
            if i < 0:
                return

            keyword = completions[i]['keyword']
            # notify any plugins
            notification_thread = threading.Thread(
                target=run_plugin_command,
                args=(
                    'on_insert_citation',
                    keyword
                ),
                kwargs={
                    'stop_on_first': False,
                    'expect_result': False
                }
            )

            notification_thread.daemon = True
            notification_thread.start()

            cite = completions[i]['keyword'] + post_brace

            #print("DEBUG: types of new_point_a and new_point_b are " + repr(type(new_point_a)) + " and " + repr(type(new_point_b)))
            # print "selected %s:%s by %s" % completions[i][0:3]
            # Replace cite expression with citation
            # the "latex_tools_replace" command is defined in latex_ref_cite_completions.py
            view.run_command("latex_tools_replace", {"a": new_point_a, "b": new_point_b, "replacement": cite})
            # Unselect the replaced region and leave the caret at the end
            caret = view.sel()[0].b
            view.sel().subtract(view.sel()[0])
            view.sel().add(sublime.Region(caret, caret))

        # get preferences for formating of quick panel
        cite_panel_format = get_setting('cite_panel_format',
            ["{title} ({keyword})", "{author}"])

        completions_length = len(completions)
        if completions_length == 0:
            return
        elif completions_length == 1:
            # only one entry, so insert entry
            view.run_command("latex_tools_replace",
                {
                    "a": new_point_a,
                    "b": new_point_b,
                    "replacement": completions[0]['keyword'] + post_brace
                }
            )

            # Unselect the replaced region and leave the caret at the end
            caret = view.sel()[0].b
            view.sel().subtract(view.sel()[0])
            view.sel().add(sublime.Region(caret, caret))
        else:
            # show quick
            formatter = Formatter()
            view.window().show_quick_panel([[formatter.vformat(s, (), completion) for s in cite_panel_format] \
                                        for completion in completions], on_done)
示例#11
0
 def dictformat(string, dictionary):
     formatter = Formatter()
     return formatter.vformat(string, (), dictionary)
class Env(object):
    """
    Stores config settings for fusionbox fabric helper routines.  Dynamically
    builds the value of certain properties unless their value was manually set.

    NOTE:
    Be careful not to define properties that reference each other...will cause
    a stack overflow.
    """

    DEFAULTS = {
        # Global defaults
        "transport_method": "git",
        "tld": ".com",
        "web_home": "/var/www",
        "workon_home": "/var/python-environments",
        "backups_dir": "backups",
        "media_dir": "media",
        "virtualenv": "{project_name}",
        "vassal": "{project_name}",
        # Dev defaults
        "dev_project_name": "{project_name}",
        "dev_tld": "{tld}",
        "dev_web_home": "{web_home}",
        "dev_virtualenv": "{virtualenv}",
        "dev_vassal": "{vassal}",
        "dev_workon_home": "{workon_home}",
        "dev_project_dir": "{dev_project_name}{dev_tld}",
        "dev_project_path": "{dev_web_home}/{dev_project_dir}",
        "dev_virtualenv_path": "{dev_workon_home}/{dev_virtualenv}",
        "dev_restart_cmd": "sudo touch /etc/vassals/{dev_vassal}.ini",
        "dev_backups_dir": "{backups_dir}",
        "dev_media_dir": "{media_dir}",
        "dev_media_path": "{dev_project_path}/{dev_media_dir}",
        # Live defaults
        "live_project_name": "{project_name}",
        "live_tld": "{tld}",
        "live_web_home": "{web_home}",
        "live_virtualenv": "{virtualenv}",
        "live_vassal": "{vassal}",
        "live_workon_home": "{workon_home}",
        "live_project_dir": "{live_project_name}{live_tld}",
        "live_project_path": "{live_web_home}/{live_project_dir}",
        "live_virtualenv_path": "{live_workon_home}/{live_virtualenv}",
        "live_restart_cmd": "sudo touch /etc/vassals/{live_vassal}.ini",
        "live_backups_dir": "{backups_dir}",
        "live_media_dir": "{media_dir}",
        "live_media_path": "{live_project_path}/{live_media_dir}",
        # Local defaults
        "local_backups_dir": "{backups_dir}",
        "local_media_dir": "{media_dir}",
    }

    def __init__(self):
        self._formatter = Formatter()

    def __getattr__(self, name):
        if name in self.DEFAULTS:
            # If there is a default value format, build the default value
            return self._format(self.DEFAULTS[name])
        else:
            raise AttributeError("'{0}' object has no attribute '{1}'".format(type(self).__name__, name))

    def __getitem__(self, key):
        return getattr(self, key)

    def _format(self, f):
        # Use a string formatter instance so we can use any object that defines
        # __getitem__
        return self._formatter.vformat(f, None, self)

    def role(self, role, name):
        return getattr(self, role + "_" + name)
示例#13
0
class CpuUsage(IntervalModule):
    """
    Shows CPU usage.
    The first output will be inacurate.

    Linux only

    .. rubric:: Available formatters

    * `{usage}`      — usage average of all cores
    * `{usage_cpu*}` — usage of one specific core. replace "*" by core number starting at 0
    * `{usage_all}`  — usage of all cores separate. usess natsort when available(relevant for more than 10 cores)

    """

    format = "{usage:02}%"
    format_all = "{core}:{usage:02}%"
    exclude_average = False
    interval = 1
    color = None
    settings = (
        ("format", "format string."),
        ("format_all", ("format string used for {usage_all} per core. "
                        "Available formaters are {core} and {usage}. ")),
        ("exclude_average", ("If True usage average of all cores will "
                             "not be in format_all.")),
        ("color", "HTML color code #RRGGBB")
    )

    def init(self):
        self.prev_total = defaultdict(int)
        self.prev_busy = defaultdict(int)
        self.formatter = Formatter()

    def get_cpu_timings(self):
        """
        reads and parses /proc/stat
        returns dictionary with all available cores including global average
        """
        timings = {}
        with open('/proc/stat', 'r') as file_obj:
            for line in file_obj:
                if 'cpu' in line:
                    line = line.strip().split()
                    timings[line[0]] = [int(x) for x in line[1:]]

        return timings

    def calculate_usage(self, cpu, total, busy):
        """
        calculates usage
        """
        diff_total = total - self.prev_total[cpu]
        diff_busy = busy - self.prev_busy[cpu]

        self.prev_total[cpu] = total
        self.prev_busy[cpu] = busy

        if diff_total == 0:
            return 0
        else:
            return int(diff_busy / diff_total * 100)

    def gen_format_all(self, usage):
        """
        generates string for format all
        """
        format_string = " "
        core_strings = []
        for core, usage in usage.items():
            if core == 'usage_cpu' and self.exclude_average:
                continue
            elif core == 'usage':
                continue

            core = core.replace('usage_', '')
            string = self.formatter.vformat(self.format_all, (),
                                            {'core': core, 'usage': usage})
            core_strings.append(string)

        core_strings = sorted(core_strings)

        return format_string.join(core_strings)

    def get_usage(self):
        """
        parses /proc/stat and calcualtes total and busy time
        (more specific USER_HZ see man 5 proc for further informations )
        """
        usage = {}

        for cpu, timings in self.get_cpu_timings().items():
            cpu_total = sum(timings)
            del timings[3:5]
            cpu_busy = sum(timings)
            cpu_usage = self.calculate_usage(cpu, cpu_total, cpu_busy)

            usage['usage_' + cpu] = cpu_usage

        # for backward compatibility
        usage['usage'] = usage['usage_cpu']

        return usage

    def run(self):
        usage = self.get_usage()
        usage['usage_all'] = self.gen_format_all(usage)

        self.data = usage
        self.output = {
            "full_text": self.format.format_map(usage),
            "color": self.color
        }
示例#14
0
 def dictformat(string, dictionary):
     formatter = Formatter()
     return formatter.vformat(string, (), dictionary)
示例#15
0
 def test_dot(self):
     f=Formatter()
     x=Str('bla')
     x.x='foo'
     self.assertEqual(f.vformat('{x}{x.x}',[], {'x':x}), 'blafoo')
示例#16
0
 def test_dot(self):
     f = Formatter()
     x = Str('bla')
     x.x = 'foo'
     self.assertEqual(f.vformat('{x}{x.x}', [], {'x': x}), 'blafoo')