write the markdown formated content of the database tables' metadata to local wiki pages
966958
def _write_wiki_pages(
            self):
        
        self.log.debug('starting the ``_write_wiki_pages`` method')

        pathToWriteFile = self.settings[
            "sherlock wiki root"] + "/Crossmatch-Catalogue Tables.md"
        writeFile = codecs.open(pathToWriteFile, encoding='utf-8', mode='w')
        now = datetime.now()
        now = now.strftime("%Y-%m-%d %H:%M")
        lastUpdated = """Last Updated %(now)s
""" % locals()

        writeFile.write(lastUpdated + self.mdTables)
        writeFile.close()

        pathToWriteFile = self.settings[
            "sherlock wiki root"] + "/Crossmatch-Catalogue Views.md"
        writeFile = codecs.open(pathToWriteFile, encoding='utf-8', mode='w')
        now = datetime.now()
        now = now.strftime("%Y-%m-%d %H:%M")
        lastUpdated = """Last Updated %(now)s
""" % locals()

        writeFile.write(lastUpdated + self.mdViews)
        writeFile.close()

        pathToWriteFile = self.settings[
            "sherlock wiki root"] + "/Crossmatch-Catalogue Streams.md"
        writeFile = codecs.open(pathToWriteFile, encoding='utf-8', mode='w')
        now = datetime.now()
        now = now.strftime("%Y-%m-%d %H:%M")
        lastUpdated = """Last Updated %(now)s
""" % locals()

        writeFile.write(lastUpdated + self.mdStreams)
        writeFile.close()

        self.log.debug('completed the ``_write_wiki_pages`` method')
        return None
1335354
def markdown(self,md,base_url='..'):
        
        print("\nProcessing documentation comments...")
        ford.sourceform.set_base_url(base_url)        
        if self.settings['warn'].lower() == 'true': print()
        for src in self.allfiles:
            src.markdown(md, self)
742873
private function print_updated_content() {
        global $COURSE, $OUTPUT;
        $page = $this->page;

        if ($page->timerendered + WIKI_REFRESH_CACHE_TIME < time()) {
            $fresh = wiki_refresh_cachedcontent($page);
            $page = $fresh['page'];
        }

        $swid = $this->subwiki->id;

        $table = new html_table();
        $table->head = array(get_string('updatedpages', 'wiki') . $OUTPUT->help_icon('updatedpages', 'wiki'));
        $table->attributes['class'] = 'generalbox table';
        $table->data = array();
        $table->rowclasses = array();

        if ($pages = wiki_get_updated_pages_by_subwiki($swid)) {
            $strdataux = '';
            foreach ($pages as $page) {
                $user = wiki_get_user_info($page->userid);
                $strdata = strftime('%d %b %Y', $page->timemodified);
                if ($strdata != $strdataux) {
                    $table->data[] = array($OUTPUT->heading($strdata, 4));
                    $strdataux = $strdata;
                }
                $link = wiki_parser_link($page->title, array('swid' => $swid));
                $class = ($link['new']) ? 'class="wiki_newentry"' : '';

                $linkpage = '<a href="' . $link['url'] . '"' . $class . '>' . format_string($link['content']) . '</a>';
                $icon = $OUTPUT->user_picture($user, array($COURSE->id));
                $table->data[] = array("$icon&nbsp;$linkpage");
            }
        } else {
            $table->data[] = array(get_string('noupdatedpages', 'wiki'));
        }

        echo html_writer::table($table);
    }
1371766
def skeleton(files, metadata, sqlite_extensions):
    ""
    if os.path.exists(metadata):
        click.secho(
            "File {} already exists, will not over-write".format(metadata),
            bg="red",
            fg="white",
            bold=True,
            err=True,
        )
        sys.exit(1)
    app = Datasette(files, sqlite_extensions=sqlite_extensions)
    databases = {}
    for database_name, info in app.inspect().items():
        databases[database_name] = {
            "title": None,
            "description": None,
            "description_html": None,
            "license": None,
            "license_url": None,
            "source": None,
            "source_url": None,
            "queries": {},
            "tables": {
                table_name: {
                    "title": None,
                    "description": None,
                    "description_html": None,
                    "license": None,
                    "license_url": None,
                    "source": None,
                    "source_url": None,
                    "units": {},
                }
                for table_name in (info.get("tables") or {})
            },
        }
    open(metadata, "w").write(
        json.dumps(
            {
                "title": None,
                "description": None,
                "description_html": None,
                "license": None,
                "license_url": None,
                "source": None,
                "source_url": None,
                "databases": databases,
            },
            indent=4,
        )
    )
    click.echo("Wrote skeleton to {}".format(metadata))
1009020
def compile_markdown_file(source_file):
  ''''''
  template = pkg_resources.resource_string('md2remark.resources.templates', 'slideshow.mustache')

  renderer = pystache.Renderer(search_dirs='./templates')

  f = open(source_file, 'r')
  slideshow_md = f.read()
  f.close()
  slideshow_name = os.path.split(source_file)[1].split('.')[0]

  rendered_text = renderer.render(template, {'title': slideshow_name, 'slideshow': slideshow_md})  

  if not os.path.exists('md2remark_build'):
    os.makedirs('md2remark_build')
  
  f = open(os.path.join('md2remark_build', slideshow_name + '.html'), 'w')
  f.write(rendered_text)
  f.close()
1054656
private function print_index_content() {
        global $OUTPUT;
        $page = $this->page;

        if ($page->timerendered + WIKI_REFRESH_CACHE_TIME < time()) {
            $fresh = wiki_refresh_cachedcontent($page);
            $page = $fresh['page'];
        }

        // navigation_node get_content calls format string for us
        $node = new navigation_node($page->title);

        $keys = array();
        $tree = array();
        $tree = wiki_build_tree($page, $node, $keys);

        $table = new html_table();
        $table->head = array(get_string('pageindex', 'wiki') . $OUTPUT->help_icon('pageindex', 'wiki'));
        $table->attributes['class'] = 'generalbox table';
        $table->data[] = array($this->render_navigation_node($tree));

        echo html_writer::table($table);
    }
882376
def render_markdown(self, text, context=github.GithubObject.NotSet):
        
        assert isinstance(text, (str, unicode)), text
        assert context is github.GithubObject.NotSet or isinstance(context, github.Repository.Repository), context
        post_parameters = {
            "text": text
        }
        if context is not github.GithubObject.NotSet:
            post_parameters["mode"] = "gfm"
            post_parameters["context"] = context._identity
        status, headers, data = self.__requester.requestJson(
            "POST",
            "/markdown",
            input=post_parameters
        )
        return data
706939
def dataset_to_markdown(dataset):
    
    text_template = """
# {title}

{description}

## Recursos del dataset

{distributions}
"""

    if "distribution" in dataset:
        distributions = "".join(
            map(distribution_to_markdown, dataset["distribution"]))
    else:
        distributions = ""

    text = text_template.format(
        title=dataset["title"],
        description=dataset.get("description", ""),
        distributions=distributions
    )

    return text
1347057
function writeTable(browserPlatformType) {
  let compatNotes = collectCompatNotes();
  let output = writeTableHead(browserPlatformType);
  output += '<tbody>';
  for (let row of features) {
    let feature = Object.keys(row).map((k) => row[k])[0];
    let desc = '';
    if (feature.description) {
      let label = Object.keys(row)[0];
      // Basic support or unnested features need no prefixing
      if (label.indexOf('.') === -1) {
        desc += feature.description;
        // otherwise add a prefix so that we know where this belongs to (e.g. "parse: ISO 8601 format")
      } else {
        desc += `<code>${label.slice(0, label.lastIndexOf('.'))}</code>: ${feature.description}`;
      }
    } else {
      desc += `<code>${Object.keys(row)[0]}</code>`;
    }
    if (feature.mdn_url) {
      desc = `<a href="${feature.mdn_url}">${desc}</a>`;
    }
    output += `<tr><td>${desc}</td>`;
    output += `${writeSupportCells(feature.support, compatNotes, browserPlatformType)}</tr>`;
  }
  output += '</tbody></table></div>';
  return output;
}
872060
def on_page_markdown(self, markdown, page, config,
                          site_navigation=None, **kwargs):
        ""

        # the site_navigation argument has been made optional
        # (deleted in post 1.0 mkdocs, but maintained here
        # for backward compatibility)

        if not self.variables:
            return markdown

        else:

            # Create templae and get the variables
            md_template = Template(markdown)

            # Execute the jinja2 template and return
            return md_template.render(**self.variables)
13192
def generate_html_files(*args):
    '''
    
    '''
    _ = args

    for tag_key, tag_list in SWITCH_DICS.items():
        if tag_key.startswith('dic_'):
            __write_view_tmpl(tag_list)

    __write_filter_tmpl(TPL_LIST)
    __write_list_tmpl(TPL_LISTINFO)
511968
public StringBuffer markdown(SchemaMetadata meta, boolean include_input_fields, boolean include_output_fields) {
    MarkdownBuilder builder = new MarkdownBuilder();

    builder.comment("Preview with http://jbt.github.io/markdown-editor");
    builder.heading1("schema ", this.getClass().getSimpleName());
    builder.hline();
    // builder.paragraph(metadata.summary);

    // TODO: refactor with Route.markdown():

    // fields
    boolean first; // don't print the table at all if there are no rows

    try {
      if (include_input_fields) {
        first = true;
        builder.heading2("input fields");

        for (SchemaMetadata.FieldMetadata field_meta : meta.fields) {
          if (field_meta.direction == API.Direction.INPUT || field_meta.direction == API.Direction.INOUT) {
            if (first) {
              builder.tableHeader("name", "required?", "level", "type", "schema?", "schema", "default", "description", "values", "is member of frames", "is mutually exclusive with");
              first = false;
            }
            builder.tableRow(
                field_meta.name,
                String.valueOf(field_meta.required),
                field_meta.level.name(),
                field_meta.type,
                String.valueOf(field_meta.is_schema),
                field_meta.is_schema ? field_meta.schema_name : "", (null == field_meta.value ? "(null)" : field_meta.value.toString()), // Something better for toString()?
                field_meta.help,
                (field_meta.values == null || field_meta.values.length == 0 ? "" : Arrays.toString(field_meta.values)),
                (field_meta.is_member_of_frames == null ? "[]" : Arrays.toString(field_meta.is_member_of_frames)),
                (field_meta.is_mutually_exclusive_with == null ? "[]" : Arrays.toString(field_meta.is_mutually_exclusive_with))
            );
          }
        }
        if (first)
          builder.paragraph("(none)");
      }

      if (include_output_fields) {
        first = true;
        builder.heading2("output fields");
        for (SchemaMetadata.FieldMetadata field_meta : meta.fields) {
          if (field_meta.direction == API.Direction.OUTPUT || field_meta.direction == API.Direction.INOUT) {
            if (first) {
              builder.tableHeader("name", "type", "schema?", "schema", "default", "description", "values", "is member of frames", "is mutually exclusive with");
              first = false;
            }
            builder.tableRow(
                field_meta.name,
                field_meta.type,
                String.valueOf(field_meta.is_schema),
                field_meta.is_schema ? field_meta.schema_name : "",
                (null == field_meta.value ? "(null)" : field_meta.value.toString()), // something better than toString()?
                field_meta.help,
                (field_meta.values == null || field_meta.values.length == 0 ? "" : Arrays.toString(field_meta.values)),
                (field_meta.is_member_of_frames == null ? "[]" : Arrays.toString(field_meta.is_member_of_frames)),
                (field_meta.is_mutually_exclusive_with == null ? "[]" : Arrays.toString(field_meta.is_mutually_exclusive_with)));
          }
        }
        if (first)
          builder.paragraph("(none)");
      }

      // TODO: render examples and other stuff, if it's passed in
    }
    catch (Exception e) {
      IcedHashMapGeneric.IcedHashMapStringObject values = new IcedHashMapGeneric.IcedHashMapStringObject();
      values.put("schema", this);
      // TODO: This isn't quite the right exception type:
      throw new H2OIllegalArgumentException("Caught exception using reflection on schema: " + this,
          "Caught exception using reflection on schema: " + this + ": " + e,
          values);
    }
    return builder.stringBuffer();
  }
622421
def save_html_with_metadata(fig, filename, fig_kwds, kwds):
    
    if isinstance(fig, str):
        text = fig
    else:
        from mpld3 import fig_to_html
        text = fig_to_html(fig, **fig_kwds)

    f = open(filename, 'w')
    for key, value in kwds.items():
        value = escape(value, escape_table)
        line = "<div class=pycbc-meta key=\"%s\" value=\"%s\"></div>" % (str(key), value)
        f.write(line)

    f.write(text)
1093237
function writeSummary(output) {
    var options = output.getOptions();
    var prefix = options.get('prefix');

    var filePath = SUMMARY_FILE;
    var engine = WebsiteGenerator.createTemplateEngine(output, filePath);
    var context = JSONUtils.encodeOutput(output);

    // Render the theme
    return Templating.renderFile(engine, prefix + '/summary.html', context)

    // Write it to the disk
    .then(function(tplOut) {
        return writeFile(output, filePath, tplOut.getContent());
    });
}
181049
def rdlfc_to_html(text, node=None, md=None):
    
    if md is None:
        md = markdown.Markdown()

    # --------------------------------------------------------------------------
    # Remove any common indentation
    # --------------------------------------------------------------------------
    linelist = text.splitlines()
    if linelist:
        text = (
            linelist[0].lstrip()
            + "\n"
            + textwrap.dedent("\n".join(linelist[1:]))
        )
    else:
        text = text.strip()

    # --------------------------------------------------------------------------
    # Parse and replace RDLFormatCode Tags
    # --------------------------------------------------------------------------
    token_spec = [
        ('b', r'\[b\]'),
        ('xb', r'\[/b\]'),
        ('i', r'\[i\]'),
        ('xi', r'\[/i\]'),
        ('u', r'\[u\]'),
        ('xu', r'\[/u\]'),
        ('color', r'\[color=[^\]]+\]'),
        ('xcolor', r'\[/color\]'),
        ('size', r'\[size=[^\]]+\]'),
        ('xsize', r'\[/size\]'),
        ('plainurl', r'\[url\].*?\[/url\]'),
        ('url', r'\[url=[^\]]+\]'),
        ('xurl', r'\[/url\]'),
        ('email', r'\[email\].*?\[/email\]'),
        ('img', r'\[img\].*?\[/img\]'),
        ('code', r'\[code\].*?\[/code\]'),
        ('list', r'\[list(?:=[^\]]+)?\]'),
        ('bullet', r'\[\*\]'),
        ('xlist', r'\[/list\]'),
        ('quote', r'\[quote\]'),
        ('xquote', r'\[/quote\]'),
        ('br', r'\[br\]'),
        ('lb', r'\[lb\]'),
        ('rb', r'\[rb\]'),
        ('p', r'\[p\]'),
        ('xp', r'\[/p\]'),
        ('sp', r'\[sp\]'),
        ('index', r'\[index\]'),
        ('index_parent', r'\[index_parent\]'),
        ('name', r'\[name\]'),
        ('instname', r'\[instname\]'),
    ]
    tok_regex = '|'.join('(?P<%s>%s)' % pair for pair in token_spec)
    pos = 0
    text_segs = []
    is_first_bullet = []
    list_end_tag = []
    for m in re.finditer(tok_regex, text, re.DOTALL):
        start = m.start()
        end = m.end()

        # Emit prior text
        if start != pos:
            text_segs.append(text[pos:start])
        pos = end

        if m.lastgroup == 'b':
            text_segs.append("<b>")
        elif m.lastgroup == 'xb':
            text_segs.append("</b>")
        elif m.lastgroup == 'i':
            text_segs.append("<i>")
        elif m.lastgroup == 'xi':
            text_segs.append("</i>")
        elif m.lastgroup == 'u':
            text_segs.append("<u>")
        elif m.lastgroup == 'xu':
            text_segs.append("</u>")
        elif m.lastgroup == 'color':
            m2 = re.match(r'\[color=([^\]]+)\]', m.group(0))
            text_segs.append('<span style="color:%s">' % m2.group(1))
        elif m.lastgroup == 'xcolor':
            text_segs.append('</span>')
        elif m.lastgroup == 'size':
            m2 = re.match(r'\[size=([^\]]+)\]', m.group(0))
            text_segs.append('<span style="font-size:%s">' % m2.group(1))
        elif m.lastgroup == 'xsize':
            text_segs.append('</span>')
        elif m.lastgroup == 'plainurl':
            m2 = re.match(r'\[url\](.*?)\[/url\]', m.group(0), re.DOTALL)
            text_segs.append('<a href="%s">%s</a>' % (m2.group(1).strip(), m2.group(1).strip()))
        elif m.lastgroup == 'url':
            m2 = re.match(r'\[url=([^\]]+)\]', m.group(0))
            text_segs.append('<a href="%s">' % m2.group(1).strip())
        elif m.lastgroup == 'xurl':
            text_segs.append('</a>')
        elif m.lastgroup == 'email':
            m2 = re.match(r'\[email\](.*?)\[/email\]', m.group(0), re.DOTALL)
            text_segs.append('<a href="mailto:%s">%s</a>' % (m2.group(1).strip(), m2.group(1).strip()))
        elif m.lastgroup == 'img':
            m2 = re.match(r'\[img\](.*?)\[/img\]', m.group(0), re.DOTALL)
            text_segs.append('<img src="%s">' % m2.group(1))
        elif m.lastgroup == 'code':
            m2 = re.match(r'\[code\](.*?)\s*\[/code\]', m.group(0), re.DOTALL)
            text_segs.append('<code>%s</code>' % m2.group(1))

        elif m.lastgroup == 'list':
            # List start tag
            m2 = re.match(r'\[list(?:=([^\]]+))?\]', m.group(0))
            ltype = m2.group(1)
            if ltype is None:
                text_segs.append('<ul>')
                is_first_bullet.append(True)
                list_end_tag.append('</ul>')
            elif ltype.strip() in ("1", "A", "a", "I", "i"):
                text_segs.append('<ol type="%s">' % ltype.strip())
                is_first_bullet.append(True)
                list_end_tag.append('</ol>')
            else:
                # Bad type. re-emit erronous list tag
                text_segs.append(m.group(0))

        elif m.lastgroup == 'bullet':
            if len(is_first_bullet) == 0: #pylint: disable=len-as-condition
                # Not inside a list tag. Re-emit erronous tag
                text_segs.append("\\[\\*\\]")
            else:
                if not is_first_bullet[-1]:
                    text_segs.append("</li>")
                is_first_bullet[-1] = False
                text_segs.append("<li>")

        elif m.lastgroup == 'xlist':
            if len(list_end_tag) == 0: #pylint: disable=len-as-condition
                # Not inside a list tag. Re-emit erronous tag
                text_segs.append(m.group(0))
            else:
                if not is_first_bullet[-1]:
                    text_segs.append("</li>")
                text_segs.append(list_end_tag[-1])
                is_first_bullet.pop()
                list_end_tag.pop()

        elif m.lastgroup == 'quote':
            text_segs.append('"')
        elif m.lastgroup == 'xquote':
            text_segs.append('"')
        elif m.lastgroup == 'br':
            text_segs.append("<br>")
        elif m.lastgroup == 'lb':
            text_segs.append("\\[")
        elif m.lastgroup == 'rb':
            text_segs.append("\\]")
        elif m.lastgroup == 'p':
            text_segs.append("\n\n<p>")
        elif m.lastgroup == 'xp':
            text_segs.append("</p>")
        elif m.lastgroup == 'sp':
            text_segs.append("&nbsp")
        elif m.lastgroup == 'index':
            if (node is not None) and node.inst.is_array:
                subscripts = []
                if node.current_idx is None:
                    # Index is not known. Use range
                    for dim in node.inst.array_dimensions:
                        subscripts.append("[0:%d]" % dim)
                else:
                    # Index is known
                    for idx in node.current_idx:
                        subscripts.append("[%d]" % idx)
                range_str = "".join(subscripts)
                text_segs.append("<span class='rdlfc-index'>%s</span>" % range_str)
            else:
                text_segs.append(m.group(0))
        elif m.lastgroup == 'index_parent':
            if (node is not None) and (node.parent is not None) and node.parent.inst.is_array:
                subscripts = []
                if node.parent.current_idx is None:
                    # Index is not known. Use range
                    for dim in node.parent.inst.array_dimensions:
                        subscripts.append("[0:%d]" % dim)
                else:
                    # Index is known
                    for idx in node.parent.current_idx:
                        subscripts.append("[%d]" % idx)
                range_str = "".join(subscripts)
                text_segs.append("<span class='rdlfc-index_parent'>%s</span>" % range_str)
            else:
                text_segs.append(m.group(0))
        elif m.lastgroup == 'name':
            if node is not None:
                text_segs.append(node.get_property("name"))
            else:
                text_segs.append(m.group(0))
        elif m.lastgroup == 'instname':
            if node is not None:
                text_segs.append(node.inst.inst_name)
            else:
                text_segs.append(m.group(0))

    # Emit trailing text
    text_segs.append(text[pos:])

    text_out = "".join(text_segs)

    #---------------------------------------------------------------------------
    # Pass through markdown processor
    #---------------------------------------------------------------------------
    text_out = md.reset().convert(text_out)

    return text_out
131084
function processMeta (markdownContent) {
  let meta = {};
  let metaArr;
  let metaString;
  let metas;

  let yamlObject;

  switch (true) {
    case _metaRegex.test(markdownContent):
      metaArr = markdownContent.match(_metaRegex);
      metaString = metaArr ? metaArr[1].trim() : '';

      if (metaString) {
        metas = metaString.match(/(.*): (.*)/ig);
        metas.forEach(item => {
          const parts = item.split(': ');
          if (parts[0] && parts[1]) {
            meta[cleanString(parts[0], true)] = parts[1].trim();
          }
        });
      }
      break;

    case _metaRegexYaml.test(markdownContent):
      metaArr = markdownContent.match(_metaRegexYaml);
      metaString = metaArr ? metaArr[1].trim() : '';
      yamlObject = yaml.safeLoad(metaString);
      meta = cleanObjectStrings(yamlObject);
      break;

    default:
    // No meta information
  }

  return meta;
}
735182
def generate_html(self, jdoc, schema, schemas):
        ''''''

        params = {'functions': sorted([j for j in jdoc \
                   if (j.schema_name == schema.object_name and j.object_type \
                       in ['function', 'procedure', 'trigger'])], \
                                      key=lambda x: x.object_name),
                   'tables': sorted([j for j in jdoc \
                   if (j.schema_name == schema.object_name and j.object_type \
                       in ['table', 'view', 'materialized view', 'foreign table'])], \
                                    key=lambda x: x.object_name),
                   'schema_name': schema.object_name,
                   'schemas': sorted(schemas, key=lambda x: x.object_name),
                   'project': self.project_name,
                   'title': '{}: schema {}'.format(self.project_name,
                                                   schema.object_name)}
        template = self.lookup.get_template('schema.mako')
        html = template.render_unicode(**params)

        return html