Export API documentation as Markdown.
508542
function (basePath) {
    var fullPath = normalizePath(this.path, basePath) || '/';

    var markdown = '';
    if (this.title) {
      markdown += '# ' + this.title + '\n\n';
    }
    if (this.description) {
      markdown += this.description + '\n\n';
    }

    // Export own request handlers.
    for (var method in this.handlers) {
      var handler = this.handlers[method];
      markdown += '## ' + (handler.title || '(no title)') + '\n\n';
      markdown += '    ' + method.toUpperCase() + ' ' + fullPath + '\n\n';
      if (handler.description) {
        markdown += handler.description + '\n\n';
      }

      if (handler.examples && handler.examples.length > 0) {
        var example = handler.examples[0];

        var request = example.request || {};
        if (request.urlParameters || request.headers || request.body) {
          markdown += '### Example input:\n\n';
          var exampleURL = '    ' + method.toUpperCase() + ' ' + fullPath;
          if (request.urlParameters) {
            exampleURL = replaceUrlParameters(exampleURL,
              request.urlParameters);
          }
          markdown += exampleURL + '\n';
          var requestHeaders = request.headers || {};
          for (var header in requestHeaders) {
            markdown += '    ' + header + ': ' + requestHeaders[header] + '\n';
          }
          if (request.body) {
            var requestBody = '    ' + jsonStringifyIfObject(request.body)
              .trim().replace(/\n/g, '\n    ');
            markdown += '    \n' + requestBody + '\n';
          }
          markdown += '\n';
        }

        var response = example.response || {};
        var hasResponseStatus = isExplicitExample(response.status);
        var hasResponseBody = isExplicitExample(response.body);
        if (hasResponseStatus || response.headers || hasResponseBody) {
          markdown += '### Example response:\n\n';
          if (hasResponseStatus) {
            var message = http.STATUS_CODES[response.status];
            markdown += '    Status: ' + response.status + ' ' + message + '\n';
          }
          var responseHeaders = response.headers || {};
          for (var header in responseHeaders) {
            var value = responseHeaders[header];
            if (isExplicitExample(value)) {
              markdown += '    ' + header + ': ' + value + '\n';
            }
          }
          if (hasResponseBody) {
            if (hasResponseStatus || Object.keys(responseHeaders).length > 0) {
              markdown += '    \n';
            }
            markdown += '    ' + jsonStringifyIfObject(response.body).trim()
              .replace(/\n/g, '\n    ') + '\n';
          }
          markdown += '\n';
        }
        // TODO Document all unique possible status codes?
        // TODO Document all request parameters?
      }
    }

    // Export children's request handlers recursively.
    for (var path in this.children) {
      var child = this.children[path];
      markdown += child.toMarkdown(fullPath);
    }

    return markdown;
  }
255505
def markdown(self,md,project):
        
        if len(self.doc) > 0:
            if len(self.doc) == 1 and ':' in self.doc[0]:
                words = self.doc[0].split(':')[0].strip()
                if words.lower() not in ['author','date','license','version','category','summary','deprecated','display','graph']:
                    self.doc.insert(0,'')
                self.doc.append('')
            self.doc = '\n'.join(self.doc)
            self.doc = md.convert(self.doc)
            self.meta = md.Meta
            md.reset()
            md.Meta = {}
        else:
            if self.settings['warn'].lower() == 'true' and self.obj != 'sourcefile' and self.obj != 'genericsource':
                #TODO: Add ability to print line number where this item is in file
                print('Warning: Undocumented {} {} in file {}'.format(self.obj, self.name, self.hierarchy[0].name))
            self.doc = ""
            self.meta = {}

        if self.parent:
            self.display = self.parent.display

        #~ print (self.meta)
        for key in self.meta:
            #~ print(key, self.meta[key])
            if key == 'display':
                tmp = [ item.lower() for item in self.meta[key] ]
                if type(self) == FortranSourceFile:
                    while 'none' in tmp:
                        tmp.remove('none')
                if len(tmp) == 0:
                    pass
                elif 'none' in tmp:
                    self.display = []
                elif 'public' not in tmp and 'private' not in tmp and 'protected' not in tmp:
                    pass
                else:
                    self.display = tmp
            elif len(self.meta[key]) == 1:
                self.meta[key] = self.meta[key][0]
            elif key == 'summary':
                self.meta[key] = '\n'.join(self.meta[key])
        if hasattr(self,'num_lines'): self.meta['num_lines'] = self.num_lines

        self.doc = ford.utils.sub_macros(ford.utils.sub_notes(self.doc),self.base_url)

        if 'summary' in self.meta:
            self.meta['summary'] = md.convert(self.meta['summary'])
            self.meta['summary'] = ford.utils.sub_macros(ford.utils.sub_notes(self.meta['summary']),self.base_url)
        elif PARA_CAPTURE_RE.search(self.doc):
            if self.get_url() == None:
                # There is no stand-alone webpage for this item (e.g.,
                # an internal routine in a routine, so make the whole
                # doc blob appear, without the link to "more..."
                self.meta['summary'] = self.doc
            else:
                self.meta['summary'] = PARA_CAPTURE_RE.search(self.doc).group()
        else:
            self.meta['summary'] = ''
        if self.meta['summary'].strip() != self.doc.strip():
            self.meta['summary'] += '<a href="{}" class="pull-right"><emph>Read more&hellip;</emph></a>'.format(self.get_url())
        if 'graph' not in self.meta:
            self.meta['graph'] = self.settings['graph']
        else:
            self.meta['graph'] = self.meta['graph'].lower()
        if 'graph_maxdepth' not in self.meta:
            self.meta['graph_maxdepth'] = self.settings['graph_maxdepth']
        if 'graph_maxnodes' not in self.meta:
            self.meta['graph_maxnodes'] = self.settings['graph_maxnodes']

        if self.obj == 'proc' or self.obj == 'type' or self.obj == 'program':
            if 'source' not in self.meta:
                self.meta['source'] = self.settings['source'].lower()
            else:
                self.meta['source'] = self.meta['source'].lower()
            if self.meta['source'] == 'true':
                if self.obj == 'proc':
                    obj = self.proctype.lower()
                else:
                    obj = self.obj
                regex = re.compile(self.SRC_CAPTURE_STR.format(obj,self.name), re.IGNORECASE|re.DOTALL|re.MULTILINE)
                match = regex.search(self.hierarchy[0].raw_src)
                if match:
                    self.src = highlight(match.group(),FortranLexer(),HtmlFormatter())
                else:
                    self.src = ''
                    if self.settings['warn'].lower() == 'true':
                        print('Warning: Could not extract source code for {} {} in file {}'.format(self.obj, self.name, self.hierarchy[0].name))

        if self.obj == 'proc':
            if 'proc_internals' not in self.meta:
                self.meta['proc_internals'] = self.settings['proc_internals'].lower()
            else:
                self.meta['proc_internals'] = self.meta['proc_internals'].lower()

        # Create Markdown
        for item in self.iterator('variables', 'modules', 'submodules', 'common',
                                   'subroutines', 'modprocedures', 'functions',
                                   'interfaces', 'absinterfaces', 'types',
                                   'programs', 'blockdata', 'boundprocs',
                                   'finalprocs', 'args', 'enums'):
            if isinstance(item, FortranBase):
                item.markdown(md, project)
        if hasattr(self,'retvar'):
            if self.retvar:
                if isinstance(self.retvar, FortranBase):
                    self.retvar.markdown(md, project)
        if hasattr(self,'procedure'):
            if isinstance(self.procedure, FortranBase):
                self.procedure.markdown(md, project)
        return
729723
function plugin(options){
  options = options || {};
  var from = options.from || 'markdown';
  var to   = options.to   || 'html5';
  var args = options.args || [];
  var opts = options.opts || {};
  var pattern = options.pattern || '**/*.md';
  var extension = options.ext || '.html';

  if (to === 'docx' || to === 'pdf') {
    opts.encoding = 'binary'
  }

  return function(files, metalsmith, done){
    selectedFiles = match(Object.keys(files), pattern)
    async.eachLimit(selectedFiles, 100, function(file, cb){

      var data = files[file];
      var dir = dirname(file);
      var html = basename(file, extname(file)) + extension;
      if ('.' != dir) html = dir + '/' + html;

      debug('Converting file %s', file);
      var md = data.contents.toString();

      pandoc = pdc.stream(from, to, args, opts);

      var result = new Buffer(0);
      var chunks = [];
      var size = 0;
      var error = '';

      // listen on error
      pandoc.on('error', function (err) {
        debug('error: ', err);
        return cb(err);
      });

      // collect result data
      pandoc.stdout.on('data', function (data) {
        chunks.push(data);
        size += data.length;
      });

      // collect error data
      pandoc.stderr.on('data', function (data) {
        error += data;
      });

      // listen on exit
      pandoc.on('close', function (code) {
        var msg = '';
        if (code !== 0)
          msg += 'pandoc exited with code ' + code + (error ? ': ' : '.');
        if (error)
          msg += error;

        if (msg)
          return cb(new Error(msg));

        var result = Buffer.concat(chunks, size);

        data.contents = result;
        delete files[file];
        files[html] = data;
        cb(null, result);
      });

      // finally, send source string
      pandoc.stdin.end(md, 'utf8');

    }, done);
  };
}
815858
def to_html(doc, output="/tmp", style="dep"):
    
    # generate filename from first six non-punct tokens
    file_name = "-".join([w.text for w in doc[:6] if not w.is_punct]) + ".html"
    html = displacy.render(doc, style=style, page=True)  # render markup
    if output is not None:
        output_path = Path(output)
        if not output_path.exists():
            output_path.mkdir()
        output_file = Path(output) / file_name
        output_file.open("w", encoding="utf-8").write(html)  # save to file
        print("Saved HTML to {}".format(output_file))
    else:
        print(html)
467568
def process_docstring(app, what, name, obj, options, lines):
    """"""
    # pylint: disable=unused-argument
    # pylint: disable=too-many-arguments
    lines.extend(_format_contracts(what=what, obj=obj))
401883
function lintMarkdown(files) {
    const config = yaml.safeLoad(fs.readFileSync(path.join(__dirname, "./.markdownlint.yml"), "utf8")),
        result = markdownlint.sync({
            files,
            config,
            resultVersion: 1
        }),
        resultString = result.toString(),
        returnCode = resultString ? 1 : 0;

    if (resultString) {
        console.error(resultString);
    }
    return { code: returnCode };
}
1281453
def exporter(directory, method, datasets):
    """"""
    if method.lower() == 'json':
        # Convert json_dict to a JSON styled string
        json_string = json.dumps(datasets, indent=4)
        savefile = open('{}/exported.json'.format(directory), 'w+')
        savefile.write(json_string)
        savefile.close()

    if method.lower() == 'csv':
        with open('{}/exported.csv'.format(directory), 'w+') as csvfile:
            csv_writer = csv.writer(
                csvfile, delimiter=',', quoting=csv.QUOTE_MINIMAL)
            for key, values in datasets.items():
                if values is None:
                    csv_writer.writerow([key])
                else:
                    csv_writer.writerow([key] + values)
        csvfile.close()
1373431
def _write_member_markdown_to_file(self, f, prefix, name, member):
    """"""
    if (inspect.isfunction(member) or inspect.ismethod(member) or
        isinstance(member, property)):
      print("- - -", file=f)
      print("", file=f)
      self._print_function(f, prefix, name, member)
      print("", file=f)
    elif inspect.isclass(member):
      print("- - -", file=f)
      print("", file=f)
      print("%s `class %s` {#%s}" % (prefix, name,
                                     _get_anchor(self._module_to_name, name)),
            file=f)
      print("", file=f)
      self._write_class_markdown_to_file(f, name, member)
      print("", file=f)
    else:
      raise RuntimeError("Member %s has unknown type %s" % (name, type(member)))
248652
def _write_class_markdown_to_file(self, f, name, cls):
    
    # Build the list of class methods to document.
    methods = dict(self.get_class_members(name, cls))
    # Used later to check if any methods were called out in the class
    # docstring.
    num_methods = len(methods)
    try:
      self._write_docstring_markdown_to_file(f, "####", inspect.getdoc(cls),
                                             methods, {})
    except ValueError as e:
      raise ValueError(str(e) + " in class `%s`" % cls.__name__)

    # If some methods were not described, describe them now if they are
    # defined by the class itself (not inherited).  If NO methods were
    # described, describe all methods.
    #
    # TODO(touts): when all methods have been categorized make it an error
    # if some methods are not categorized.
    any_method_called_out = (len(methods) != num_methods)
    if any_method_called_out:
      other_methods = {n: m for n, m in methods.items() if n in cls.__dict__}
      if other_methods:
        print("\n#### Other Methods", file=f)
    else:
      other_methods = methods
    for name in sorted(other_methods):
      self._write_member_markdown_to_file(f, "####", *other_methods[name])
564579
function plugin(options){
  options = options || {};
  var keys = options.keys || [];

  return function(files, metalsmith, done){
    setImmediate(done);
    var md = new MarkdownIt(options);
    Object.keys(files).forEach(function(file){
      if (!markdown(file)) return;
      var data = files[file];
      var dir = dirname(file);
      var html = basename(file, extname(file)) + '.html';
      if ('.' != dir) html = dir + '/' + html;

      var str = md.render(data.contents.toString());
      data.contents = new Buffer(str);
      keys.forEach(function(key) {
        data[key] = md.render(data[key]);
      });

      delete files[file];
      files[html] = data;
    });
  };
}
287669
def generate_docs(klass):
    """"""
    import numina.types.datatype

    attrh = ('Attributes\n'
             '----------\n')

    doc = getattr(klass, '__doc__', None)

    if doc is None or doc == '':
        doc = "%s documentation." % klass.__name__

    if len(klass.stored()):
        doc = doc + '\n\n' + attrh

    skeys = sorted(klass.stored().keys())
    for key in skeys:
        y = klass.stored()[key]

        if isinstance(y, Requirement):
            modo = 'requirement'
        elif isinstance(y, Result):
            modo = 'product'
        else:
            modo = ""
        if y.type.isproduct():
            tipo = y.type.__class__.__name__
        elif isinstance(y.type, numina.types.datatype.PlainPythonType):
            tipo = y.type.internal_type.__name__
        else:
            tipo = y.type.__class__.__name__

        if y.optional:
            if y.default_value():
                modo = "%s, optional, default=%s" % (modo, y.default)
            else:
                modo = "%s, optional" % (modo,)

        descript = y.description
        if descript:
            field = "%s : %s, %s\n %s\n" % (key, tipo, modo, descript)
        else:
            field = "%s : %s, %s\n" % (key, tipo, modo)
        doc = doc + field

    klass.__doc__ = doc
    return klass
766508
def docstring_to_markdown(docstring):
    
    new_docstring_lst = []

    for idx, line in enumerate(docstring.split('\n')):
        line = line.strip()
        if set(line) in ({'-'}, {'='}):
            new_docstring_lst[idx-1] = '**%s**' % new_docstring_lst[idx-1]
        elif line.startswith('>>>'):
            line = '    %s' % line
        new_docstring_lst.append(line)

    for idx, line in enumerate(new_docstring_lst[1:]):
        if line:
            if line.startswith('Description : '):
                new_docstring_lst[idx+1] = (new_docstring_lst[idx+1]
                                            .replace('Description : ', ''))
            elif ' : ' in line:
                line = line.replace(' : ', '` : ')
                new_docstring_lst[idx+1] = '\n- `%s\n' % line
            elif '**' in new_docstring_lst[idx-1] and '**' not in line:
                new_docstring_lst[idx+1] = '\n%s' % line.lstrip()
            elif '**' not in line:
                new_docstring_lst[idx+1] = '    %s' % line.lstrip()

    clean_lst = []
    for line in new_docstring_lst:
        if set(line.strip()) not in ({'-'}, {'='}):
            clean_lst.append(line)
    return clean_lst
512962
function rawData() {
  return {
    DocumentationGeneration: {
      name: 'DocumentationGeneration',
      submodules: {},
      elements: {},
      classes: {
        'Some.Class.ClassItem': 1,
        'SomeOther.Class.Description': 1
      },
      fors: {},
      namespaces: {},
      tag: 'module',
      file: 'lib/parse-markdown.js',
      line: 4,
      description: '# An H1\nAnd a paragraph'
    },
    CreateDirs: {
      name: 'CreateDirs',
      submodules: {},
      elements: {},
      classes: {
        'Some.Class.ClassItem': 1,
        'SomeOther.Class.Description': 1
      },
      fors: {},
      namespaces: {},
      tag: 'module',
      file: 'lib/create-dirs.js',
      line: 7,
      description: '`some code`'
    }
  };
}
1293094
function markdown(preset, options) {
  var stream = through(transform, flush)
  var parser = new Remarkable(preset, options)
  var buffer = []

  function transform(chunk, encoding, done) {
    buffer.push(chunk)
    done()
  }

  function flush(done) {
    this.push(parser.render(buffer.join('\n')))
    done()
  }

  return stream
}
668369
def build_docs(directory):
    """"""
    os.chdir(directory)
    process = subprocess.Popen(["make", "html"], cwd=directory)
    process.communicate()
102993
function getDocObject(dir, info) {
  const markdown = getReadmeText(dir);
  const html = marked(markdown);
  const cleanedHTML = prepareHTML(html, info);
  return { pkg: dir, html: cleanedHTML };
}
1364580
def render_docstring(self):
        """"""
        res = '{{{self.method}}} {self.uri} {self.title}\n'.format(self=self)
        if self.params:
            for group, params in self.params.items():
                res += '\n' + group + ' params:\n'
                for param in params.values():
                    res += param.render_docstring()
        return res