Converts names, descriptions and defaults for settings in
    ``yacms.conf.registry`` into RST format for use in docs,
    optionally filtered by setting names with the given prefix.
322729
def build_settings_docs(docs_path, prefix=None):
    
    # String to use instead of setting value for dynamic defaults
    dynamic = "[dynamic]"
    lines = [".. THIS DOCUMENT IS AUTO GENERATED VIA conf.py"]
    for name in sorted(registry.keys()):
        if prefix and not name.startswith(prefix):
            continue
        setting = registry[name]
        settings_name = "``%s``" % name
        settings_label = ".. _%s:" % name
        setting_default = setting["default"]
        if isinstance(setting_default, str):
            if gethostname() in setting_default or (
                setting_default.startswith("/") and
                    os.path.exists(setting_default)):
                setting_default = dynamic
        if setting_default != dynamic:
            setting_default = repr(deep_force_unicode(setting_default))
        lines.extend(["", settings_label])
        lines.extend(["", settings_name, "-" * len(settings_name)])
        lines.extend(["",
            urlize(setting["description"] or "").replace(
                "<a href=\"", "`").replace(
                "\" rel=\"nofollow\">", " <").replace(
                "</a>", ">`_")])
        if setting["choices"]:
            choices = ", ".join(["%s: ``%s``" % (str(v), force_text(k))
                                 for k, v in setting["choices"]])
            lines.extend(["", "Choices: %s" % choices, ""])
        lines.extend(["", "Default: ``%s``" % setting_default])
    with open(os.path.join(docs_path, "settings.rst"), "w") as f:
        f.write("\n".join(lines).replace("u'", "'").replace("yo'",
            "you'").replace("&#39;", "'"))
1278687
def to_s(format = :default)
      title_suffix = " (#{title})" if has_title?
      formatted_name = "#{family_name.upcase}, #{given_name}#{title_suffix}"
      formatted_nhs_number = " (#{nhs_number})" if nhs_number.present?
      case format
      when :default then formatted_name
      when :long then "#{formatted_name}#{formatted_nhs_number}"
      else full_name
      end
    end
144643
def _from_docstring_rst(doc):
    

    def format_fn(line, status):
        """ format function """

        if re_from_data.match(line):
            line = re_from_data.sub(r"**\1** ", line)
            status["add_line"] = True
        line = re_from_defaults.sub(r"*\1*", line)
        if status["listing"]:
            # parameters
            if re_from_param.match(line):
                m = re_from_param.match(line)
                line = "  - ``{}`` {}".format(m.group(1), m.group(3))
            # status items
            elif re_from_status.match(line):
                m = re_from_status.match(line)
                line = "  - ``{}`` {}".format(m.group(1), m.group(3))
            # bullets
            elif re_from_item.match(line):
                line = re_from_item.sub(r"  -", line)
            # is continuation line
            else:
                line = " " * 4 + line.lstrip()
        # in .rst format code samples use double backticks vs single ones for
        # .md This converts them.
        line = re_lone_backtick.sub("``", line)
        return line

    return _reformat_docstring(doc, format_fn, code_newline="\n")
177599
def create_module_rst_file(module_name):
    

    return_text = 'Module:  ' + module_name
    dash = '=' * len(return_text)
    return_text += '\n' + dash + '\n\n'
    return_text += '.. automodule:: ' + module_name + '\n'
    return_text += '   :members:\n\n'

    return return_text
1287376
def _set_prefixes(self, conf):
        
        if conf.get('legacy_namespace', 'y') in self.TRUE_VALUES:
            self.count_prefix = 'stats_counts'
            self.count_suffix = ''
            self.gauge_prefix = 'stats.gauges'
            self.timer_prefix = 'stats.timers'
            self.rate_prefix = 'stats'
            self.rate_suffix = ''
        else:
            global_prefix = conf.get('global_prefix', 'stats')
            self.count_prefix = '%s.%s' % (global_prefix,
                                           conf.get('prefix_counter',
                                                    'counters'))
            self.count_suffix = '.count'
            self.gauge_prefix = '%s.%s' % (global_prefix,
                                           conf.get('prefix_gauge', 'gauges'))
            self.timer_prefix = '%s.%s' % (global_prefix,
                                           conf.get('prefix_timer', 'timers'))
            self.rate_prefix = self.count_prefix
            self.rate_suffix = '.rate'
517275
def _parse_docstring(self, docstring):
        """"""
        match = re.match(r"""
            # Following PEP 257
            \s* (?P<summary>[^\n]+?) \s*   # First line

            (                              # Description and YAML are optional
              (\n \s*){2}                  # Blank line

              # Description (optional)
              (
                (?!-{3,})                     # Don't use YAML as description
                \s* (?P<description>.+?) \s*  # Third line and maybe others
                (?=-{3,})?                    # Stop if "---" is found
              )?

              # YAML spec (optional) **currently not used**
              (
                -{3,}\n                       # "---" begins yaml spec
                (?P<open_api>.+)
              )?
            )?
            $""", docstring, re.VERBOSE | re.DOTALL)

        summary = 'TODO write the summary.'
        description = 'TODO write/remove the description'
        if match:
            m_dict = match.groupdict()
            summary = m_dict['summary']
            if m_dict['description']:
                description = re.sub(r'(\s|\n){2,}', ' ',
                                     m_dict['description'])
        self._summary = summary
        self._description = description
1147483
def override(settings, yaml=None, env=None):
    
    if yaml is not None:
        if hasattr(yaml, 'read'):
            settings.update(load_yaml(yaml.read()))
        else:
            if os.path.exists(yaml):
                with open(yaml) as f:
                    settings.update(load_yaml(f.read()))

    if env is not None:
        for k, v in os.environ.items():
            if k.startswith(env):
                settings[k[len(env):]] = load_yaml(v)
781740
private function generateNamesDescription()
    {
        foreach ($this->app['config']->get('contenttypes') as $ctname => $ctype) {
            $keyprefix = 'contenttypes.' . $this->slugifyKey($ctname) . '.';

            // Names & description
            $setkeys = [
                'name.plural'   => 'name',
                'name.singular' => 'singular_name',
                'description'   => 'description',
            ];
            foreach ($setkeys as $setkey => $getkey) {
                $key = $keyprefix . $setkey;

                if ($this->isSaved($key)) {
                    $this->translation[$key] = $this->saved[$key];
                } else {
                    if (isset($ctype[$getkey]) && $ctype[$getkey] !== '') {
                        $this->hints[$key] = $ctype[$getkey];
                    } else {
                        $fallback = $this->fallback($key);
                        if ($fallback !== false) {
                            $this->hints[$key] = $fallback;
                        }
                    }
                    $this->translation[$key] = '';
                }
                // Remember names for later usage
                if ($setkey == 'name.plural') {
                    $this->ctnames[$ctname]['%contenttypes%'] = $this->translation[$key];
                } elseif ($setkey == 'name.singular') {
                    $this->ctnames[$ctname]['%contenttype%'] = $this->translation[$key];
                }
            }
        }
    }
499525
def to_yaml(cls, config, compact=False, indent=2, level=0):
        
        lines = ""
        if isinstance(config, ConfigTree):
            if len(config) > 0:
                if level > 0:
                    lines += '\n'
                bet_lines = []
                for key, item in config.items():
                    bet_lines.append('{indent}{key}: {value}'.format(
                        indent=''.rjust(level * indent, ' '),
                        key=key.strip('"'),  # for dotted keys enclosed with "" to not be interpreted as nested key,
                        value=cls.to_yaml(item, compact, indent, level + 1))
                    )
                lines += '\n'.join(bet_lines)
        elif isinstance(config, list):
            config_list = [line for line in config if line is not None]
            if len(config_list) == 0:
                lines += '[]'
            else:
                lines += '\n'
                bet_lines = []
                for item in config_list:
                    bet_lines.append('{indent}- {value}'.format(indent=''.rjust(level * indent, ' '),
                                                                value=cls.to_yaml(item, compact, indent, level + 1)))
                lines += '\n'.join(bet_lines)
        elif isinstance(config, basestring):
            # if it contains a \n then it's multiline
            lines = config.split('\n')
            if len(lines) == 1:
                lines = config
            else:
                lines = '|\n' + '\n'.join([line.rjust(level * indent, ' ') for line in lines])
        elif config is None or isinstance(config, NoneValue):
            lines = 'null'
        elif config is True:
            lines = 'true'
        elif config is False:
            lines = 'false'
        else:
            lines = str(config)
        return lines
1073619
def _format_help_dicts(help_dicts, display_defaults=False):
    
    help_strs = []
    for help_dict in help_dicts:
        help_str = "%s (%s" % (
            help_dict["var_name"],
            "Required" if help_dict["required"] else "Optional",
        )
        if help_dict.get("default") and display_defaults:
            help_str += ", Default=%s)" % help_dict["default"]
        else:
            help_str += ")"
        if help_dict.get("help_str"):
            help_str += ": %s" % help_dict["help_str"]
        help_strs.append(help_str)

    return "\n".join(help_strs)
96610
def _set_defaults(self, namespace, optional_cfg_files):
        
        # Add current configuration directory
        namespace["config_dir"] = self.config_dir

        # Load defaults
        for idx, cfg_file in enumerate([self.CONFIG_INI] + optional_cfg_files):
            if any(i in cfg_file for i in set('/' + os.sep)):
                continue # skip any non-plain filenames

            try:
                defaults = pymagic.resource_string("pyrocore", "data/config/" + cfg_file) #@UndefinedVariable
            except IOError as exc:
                if idx and exc.errno == errno.ENOENT:
                    continue
                raise

            ini_file = ConfigParser.SafeConfigParser()
            ini_file.optionxform = str # case-sensitive option names
            ini_file.readfp(StringIO.StringIO(defaults), "<defaults>")
            self._set_from_ini(namespace, ini_file)
942136
def parse_names_and_default(self):
        """"""
        result = {}
        for title, text in self.formal_content.items():

            if not text:
                result[title] = []
                continue

            logger.debug('\n' + text)

            collect = []
            to_list = text.splitlines()

            # parse first line. Should NEVER failed.
            # this will ensure in `[default: xxx]`,
            # the `xxx`(e.g: `\t`, `,`) will not be changed by _format_line
            previous_line = to_list.pop(0)
            collect.append(self.parse_line_option_indent(previous_line))

            for line in to_list:
                indent_match = self.indent_re.match(line)
                this_indent = len(indent_match.groupdict()['indent'])

                if this_indent >= collect[-1]['indent']:
                    # A multi line description
                    previous_line = line
                    continue

                # new option line
                # deal the default for previous option
                collect[-1]['default'] = self.parse_default(previous_line)
                # deal this option
                collect.append(self.parse_line_option_indent(line))
                logger.debug(collect[-1])
                previous_line = line
            else:
                collect[-1]['default'] = self.parse_default(previous_line)

            result[title] = [
                (each['option'], each['default']) for each in collect]

        return result
1318733
def setup_regex(self):
        """"""
        #Regex for grabbing out valid XML tags that represent known docstrings that we can work with.
        self.keywords = [ "summary", "usage", "errors", "member", "group", "local", 
                          "comments", "parameter" ]
        #Regex for extracting the contents of docstrings minus the !! and any leading spaces.
        self._RX_DOCS = "^\s*!!(?P<docstring>.+?)$"
        self.RE_DOCS = re.compile(self._RX_DOCS, re.M)
        #Regex for handling cross references in the documentation
        self._RX_REFS = r"@CREF\[(?P<reference>[^\]]+)\]"
        self.RE_REFS = re.compile(self._RX_REFS)
        #Regex to match first lines of declarations for code elements that can be
        #decorated by docstrings.
        self._RX_DECOR = (r"((?P<type>character|real|type|logical|integer|complex)?"
                          r"(?P<kind>\([a-z0-9_]+\))?)?(,?(?P<modifiers>[^\n]+?))?"
                          r"\s*(?P<codetype>subroutine|function|type|module|interface)\s+(?P<name>[^(]+)")
        self.RE_DECOR = re.compile(self._RX_DECOR, re.I)
        #Regex for getting the docstrings decorating one or more modules in a code file,
        #Since they aren't contained inside any other code element, we can't just use
        #the normal docblocks routines.
        self._RX_MODDOCS = (r"^(?P<docstring>\s*!!.+?)\n\s*module\s+(?P<name>[A-Za-z0-9_]+)"
                            ".+?end\s+module(\s+(?P=name))?")
        self.RE_MODDOCS = re.compile(self._RX_MODDOCS, re.DOTALL | re.I)
1049366
def set_default_names(data):
    """"""
    if all(name is not None for name in data.index.names):
        return data

    data = data.copy()
    if data.index.nlevels > 1:
        names = [name if name is not None else 'level_{}'.format(i)
                 for i, name in enumerate(data.index.names)]
        data.index.names = names
    else:
        data.index.name = data.index.name or 'index'
    return data
500777
def opt_restore(prefix, opts):
    

    return {prefix + name: value for name, value in opts.items()}
350801
def _prefix_from_opts(opts):
    
    p = Prefix()
    p.prefix = opts.get('prefix')
    p.type = opts.get('type')
    p.description = opts.get('description')
    p.node = opts.get('node')
    p.country = opts.get('country')
    p.order_id = opts.get('order_id')
    p.customer_id = opts.get('customer_id')
    p.alarm_priority = opts.get('alarm_priority')
    p.comment = opts.get('comment')
    p.monitor = _str_to_bool(opts.get('monitor'))
    p.vlan = opts.get('vlan')
    p.status = opts.get('status') or 'assigned' # default to assigned
    p.tags = list(csv.reader([opts.get('tags', '')], escapechar='\\'))[0]
    p.expires = opts.get('expires')
    return p
908718
def extract_config(config, prefix):
    """"""
    prefix = prefix.strip('.') + '.'
    plen = len(prefix)
    value = {}
    for k, v in config.items():
        if k.startswith(prefix):
            value[k[plen:]] = v
    return value