Bibliographic entry in html format.
963025
def get_html(self):
        """"""
        # Author links
        au_link = ('<a href="https://www.scopus.com/authid/detail.url'
                   '?origin=AuthorProfile&authorId={0}">{1}</a>')
        if len(self.authors) > 1:
            authors = u', '.join([au_link.format(a.auid, a.given_name +
                                                 ' ' + a.surname)
                                 for a in self.authors[0:-1]])
            authors += (u' and ' +
                        au_link.format(self.authors[-1].auid,
                                       (str(self.authors[-1].given_name) +
                                        ' ' +
                                        str(self.authors[-1].surname))))
        else:
            a = self.authors[0]
            authors = au_link.format(a.auid, a.given_name + ' ' + a.surname)
        title = u'<a href="{}">{}</a>'.format(self.scopus_link, self.title)
        if self.volume and self.issueIdentifier:
            volissue = u'<b>{}({})</b>'.format(self.volume, self.issueIdentifier)
        elif self.volume:
            volissue = u'<b>{}</b>'.format(self.volume)
        else:
            volissue = 'no volume'
        jlink = '<a href="https://www.scopus.com/source/sourceInfo.url'\
                '?sourceId={}">{}</a>'.format(
                    self.source_id, self.publicationName)
        pages = _parse_pages(self, unicode=True)
        s = "{auth}, {title}, {jour}, {volissue}, {pages}, ({year}).".format(
                auth=authors, title=title, jour=jlink, volissue=volissue,
                pages=pages, year=self.coverDate[:4])
        if self.doi:
            s += ' <a href="https://doi.org/{0}">doi:{0}</a>.'.format(self.doi)
        return s
1277340
def htmlFromThing(thing,title):
    """"""
    try:
        thing2 = copy.copy(thing)
    except:
        print("crashed copying the thing! I can't document it.")
        return False
    stuff=analyzeThing(thing2)
    names2=list(stuff.keys())
    for i,name in enumerate(names2):
        if name.startswith("_"):
            names2[i]="zzzzzzzzzz"+name

    html="""<html><head><style>
    body {font-family: courier, monospace;}
    .name {font-weight: bold;}
    .type {font-style: italic; font-family: serif; color: #AAA;}
    .desc {}
    .itemEval {background-color: #DDFFDD;}
    .itemEvalFail {}
    table {font-size: .8em;
           margin-top: 20px;
           border-collapse: collapse;}
    tr {border: 1px solid #CCC; vertical-align: text-top;}
    td {padding: 2px 10px 2px 10px;}
    .credits {text-align: center;
              opacity: 0.5;
              margin-top: 50px;
              font-size: .8em;
              font-family: sans-serif;}
    </style></head><body>"""

    if title:
        html+='<span style="color: #CCC;">title: </span>%s<br>'%title
    textTitle=""
    textType=""
    try:
        textTitle=websafe(str(thing))
        textType=websafe(type(thing).__name__)
    except:
        pass
    html+='<span style="color: #CCC;">value: </span>%s<br>'%textTitle
    html+='<span style="color: #CCC;">&nbsp;type: </span>%s<br>'%textType
    html+='<table cellpadding=3 align="center">'
    html+='<tr style="background-color: #000; color: #FFF; font-weight: bold;">'
    html+='<td>property</td><td>type</td><td>value</td>'
    html+='<td>evaluated (without arguments)</td></tr>'
    for name in sorted(names2):
        if name.startswith("zzzzzzzzzz"):
            name=name[10:]
        itemName=str(name)
        itemType=websafe(stuff[name][0])
        itemStr=websafe(stuff[name][1])
        itemEval=websafe(stuff[name][2])
        color="DDDDFF"
        color2=""
        if "method" in itemType:
            itemName+="()"
            color="FFDDDD"
        if itemName.startswith("_"):
            color="EEEEEE"
        if itemStr.startswith("&lt;") and not ", " in itemStr:
            itemStr="""<span style="color: #CCC; font-family: serif;
                font-style: italic;">%s</span>"""%itemStr
        else:
            color2="DDFFDD"
            if itemEval=="":
                itemEval="FAILED TO EVALUATE"
        html+='<tr>'
        html+='<td class="name" style="background-color: #%s;">%s</td>'%(color,itemName)
        html+='<td class="type">%s</td>'%(itemType)
        html+='<td class="itemStr" style="background-color: #%s;">%s</td>'%(color2,itemStr)
        if itemEval=="FAILED TO EVALUATE":
            html+='<td class="itemEvalFail"></td>'
        else:
            html+='<td class="itemEval">%s</td>'%(itemEval)
        html+='</tr>'

    dt=datetime.datetime.now()
    html+="""</table><p class="credits">
    page automatically generated by
    <a href="https://pypi.python.org/pypi/webinspect/">webinspect</a>
    (version %s) %s</p>
    </body></html>"""%(__version__,dt.strftime("at %I:%M %p on %B %d, %Y"))

    return html
1119175
def publication_info(self, key, value):
    """"""
    def _get_cnum(value):
        w_value = force_single_element(value.get('w', ''))
        normalized_w_value = w_value.replace('/', '-').upper()

        return normalized_w_value

    def _get_material(value):
        schema = load_schema('elements/material')
        valid_materials = schema['enum']

        m_value = force_single_element(value.get('m', ''))
        normalized_m_value = m_value.lower()

        if normalized_m_value in valid_materials:
            return normalized_m_value

    def _get_parent_isbn(value):
        z_value = force_single_element(value.get('z', ''))
        if z_value:
            return normalize_isbn(z_value)

    def _get_pubinfo_freetext(value):
        x_value = force_single_element(value.get('x', ''))
        if not x_value.startswith('#DONE'):
            return x_value

    page_start, page_end, artid = split_page_artid(value.get('c'))

    parent_recid = maybe_int(force_single_element(value.get('0')))
    parent_record = get_record_ref(parent_recid, 'literature')

    journal_recid = maybe_int(force_single_element(value.get('1')))
    journal_record = get_record_ref(journal_recid, 'journals')

    conference_recid = maybe_int(force_single_element(value.get('2')))
    conference_record = get_record_ref(conference_recid, 'conferences')

    return {
        'artid': artid,
        'cnum': _get_cnum(value),
        'conf_acronym': force_single_element(value.get('q')),
        'conference_record': conference_record,
        'hidden': key.startswith('7731') or None,
        'journal_issue': force_single_element(value.get('n')),
        'journal_record': journal_record,
        'journal_title': force_single_element(value.get('p')),
        'journal_volume': force_single_element(value.get('v')),
        'material': _get_material(value),
        'page_end': page_end,
        'page_start': page_start,
        'parent_isbn': _get_parent_isbn(value),
        'parent_record': parent_record,
        'parent_report_number': force_single_element(value.get('r')),
        'pubinfo_freetext': _get_pubinfo_freetext(value),
        'year': maybe_int(force_single_element(value.get('y'))),
    }
5903
def _repr_html_(self):
        """"""
        out = "<table class='taqltable' style='overflow-x:auto'>\n"

        # Print column names (not if they are all auto-generated)
        if not(all([colname[:4] == "Col_" for colname in self.colnames()])):
            out += "<tr>"
            for colname in self.colnames():
                out += "<th><b>"+colname+"</b></th>"
            out += "</tr>"

        cropped = False
        rowcount = 0
        for row in self:
            rowout = _format_row(row, self.colnames(), self)
            rowcount += 1
            out += rowout
            if "\n" in rowout:  # Double space after multiline rows
                out += "\n"
            out += "\n"
            if rowcount >= 20:
                cropped = True
                break

        if out[-2:] == "\n\n":
            out = out[:-1]

        out += "</table>"

        if cropped:
            out += ("<p style='text-align:center'>(" +
                    str(self.nrows()-20)+" more rows)</p>\n")

        return out
571569
def htmlize_list(items):
    
    out = ["<ul>"]
    for item in items:
        out.append("<li>" + htmlize(item) + "</li>")
    out.append("</ul>")
    return "\n".join(out)
63204
def main():
    
    args = command_line()

    # TODO: Decouple Book interface and implementation
    query = Book(
        title=args.title,
        author=args.author,
        max_results=args.max,
        language_code=args.language,
        fields=('title', 'authors', 'imageLinks', 'categories', 'description'),
    )

    if args.verbose:
        print('Request URL:')
        print(query.url)
        print(query.__dict__)

    # Temporary Display Interface
    books = query.json.get('items', None)
    if not books:
        raise AttributeError('Web Request Failed')

    for book in books:
        info = book['volumeInfo']

        # Retrieve ISBN/Reference Info
        if 'industryIdentifiers' in info:
            identifiers = dict([(ref['type'], ref['identifier']) for ref in info['industryIdentifiers']])

            # Prefer ISBN 13 over ISBN 10
            if 'ISBN_13' in identifiers:
                isbn_id, isbn = 'ISBN_13', identifiers['ISBN_13']
            else:
                isbn_id, isbn = identifiers.popitem()

        else:
            isbn_id, isbn = 'ISBN_##', 'N/A'

        # Format/Print
        display = 'Title: {title}\nAuthor: {authors}\n{isbn_id}: {isbn}\n'.format(
            title=info['title'],
            authors=', '.join(info.get('authors', ['N/A'])),
            isbn_id=isbn_id,
            isbn=isbn,
        )

        print(display)
446894
def write_bib(refs):
    '''
    '''

    full_str = ''

    lib_citation_desc, lib_citations = get_library_citation()

    full_str += '%' * 80 + '\n'
    full_str += textwrap.indent(lib_citation_desc, '% ')
    full_str += '%' * 80 + '\n\n'

    for k, r in lib_citations.items():
        full_str += _ref_bib(k, r) + '\n\n'

    full_str += '%' * 80 + '\n'
    full_str += "% References for the basis set\n"
    full_str += '%' * 80 + '\n'

    # First, write out the element, description -> key mapping
    # Also make a dict of unique reference to output
    unique_refs = {}

    for ref in refs:
        full_str += '% {}\n'.format(compact_elements(ref['elements']))

        for ri in ref['reference_info']:
            full_str += '%     {}\n'.format(ri['reference_description'])

            refdata = ri['reference_data']

            if len(refdata) == 0:
                full_str += '%     (...no reference...)\n%\n'
            else:
                rkeys = [x[0] for x in ri['reference_data']]
                full_str += '%         {}\n%\n'.format(' '.join(rkeys))

            for k, r in refdata:
                unique_refs[k] = r

    full_str += '\n\n'

    # Go through them sorted alphabetically by key
    for k, r in sorted(unique_refs.items(), key=lambda x: x[0]):
        full_str += '{}\n\n'.format(_ref_bib(k, r))

    return full_str
1168976
def filelist2html(lst, fldr, hasHeader='N'):
    
    txt = '<TABLE width=100% border=0>'
    numRows = 1
    if lst:
        for l in lst:
            if hasHeader == 'Y':
                if numRows == 1:
                    td_begin = '<TH>'
                    td_end = '</TH>'
                else:
                    td_begin = '<TD>'
                    td_end = '</TD>'
            else:
                td_begin = '<TD>'
                td_end = '</TD>'
            numRows += 1
            txt += '<TR>'
            if type(l) is str:
                txt += td_begin + link_file(l, fldr) + td_end
            elif type(l) is list:
                txt += td_begin
                for i in l:
                    txt+= link_file(i, fldr) + '; '
                txt += td_end
            else:
                txt += td_begin + str(l) + td_end
            txt += '</TR>\n'
    txt += '</TABLE><BR>\n'
    return txt
125589
def get_links(html, outformat):
    
    if outformat == FORMAT_BIBTEX:
        refre = re.compile(r'<a href="https://scholar.googleusercontent.com(/scholar\.bib\?[^"]*)')
    elif outformat == FORMAT_ENDNOTE:
        refre = re.compile(r'<a href="https://scholar.googleusercontent.com(/scholar\.enw\?[^"]*)"')
    elif outformat == FORMAT_REFMAN:
        refre = re.compile(r'<a href="https://scholar.googleusercontent.com(/scholar\.ris\?[^"]*)"')
    elif outformat == FORMAT_WENXIANWANG:
        refre = re.compile(r'<a href="https://scholar.googleusercontent.com(/scholar\.ral\?[^"]*)"')
    reflist = refre.findall(html)
    # escape html entities
    reflist = [re.sub('&(%s);' % '|'.join(name2codepoint), lambda m:
                      chr(name2codepoint[m.group(1)]), s) for s in reflist]
    return reflist
254866
def write_bibtex_dict(stream, entries):
    
    from bibtexparser.bwriter import BibTexWriter

    writer = BibTexWriter()
    writer.indent = '  '
    writer.entry_separator = ''
    first = True

    for rec in entries:
        if first:
            first = False
        else:
            stream.write(b'\n')
        stream.write(writer._entry_to_bibtex(rec).encode('utf8'))
142666
def author_json_details(author, author_json, contributions, correspondence,
                        competing_interests, equal_contributions_map, present_address_data,
                        foot_notes_data, html_flag=True):
    # Configure the XML to HTML conversion preference for shorthand use below
    convert = lambda xml_string: xml_to_html(html_flag, xml_string)

    """"""
    if author_affiliations(author):
        author_json["affiliations"] = author_affiliations(author)

    # foot notes or additionalInformation
    if author_foot_notes(author, foot_notes_data):
        author_json["additionalInformation"] = author_foot_notes(author, foot_notes_data)

    # email
    if author_email_addresses(author, correspondence):
        author_json["emailAddresses"] = author_email_addresses(author, correspondence)

    # phone
    if author_phone_numbers(author, correspondence):
        author_json["phoneNumbers"] = author_phone_numbers_json(author, correspondence)

    # contributions
    if author_contribution(author, contributions):
        author_json["contribution"] = convert(author_contribution(author, contributions))

    # competing interests
    if author_competing_interests(author, competing_interests):
        author_json["competingInterests"] = convert(
            author_competing_interests(author, competing_interests))

    # equal-contributions
    if author_equal_contribution(author, equal_contributions_map):
        author_json["equalContributionGroups"] = author_equal_contribution(author, equal_contributions_map)

    # postalAddress
    if author_present_address(author, present_address_data):
        author_json["postalAddresses"] = author_present_address(author, present_address_data)

    return author_json
170777
def html(content, **kwargs):
    """"""
    if hasattr(content, 'read'):
        return content
    elif hasattr(content, 'render'):
        return content.render().encode('utf8')

    return str(content).encode('utf8')
1110606
def _page_html(page):
    
    out = []
    out.append(_html_title(page))
    out.append(_html_image(page))
    out.append(page.data.get('extract'))
    return "\n".join([x for x in out if x])
737505
def _parse_authors(html_chunk):
    
    authors = html_chunk.match(
        ["div", {"class": "comment"}],
        "h3",
        "a",
    )

    if not authors:
        return []

    authors = map(
        lambda x: Author(                            # create Author objects
            x.getContent().strip(),
            normalize_url(BASE_URL, x.params.get("href", None))
        ),
        authors
    )

    return filter(lambda x: x.name.strip(), authors)
38313
function html(files, dir, useIcons, view, req) {
  return '<ul id="files" class="view-' + escapeHtml(view) + '">'
    + (view == 'details' ? (
      '<li class="header">'
      + '<span class="name">Name</span>'
      + '<span class="size">Size</span>'
      + '<span class="date">Modified</span>'
      + '</li>') : '')
    + files.map(function(file){
    var isDir = '..' == file.name || (file.stat && file.stat.isDirectory())
      , classes = []
      , path = dir.split('/').map(function (c) { return encodeURIComponent(c); });

    if (useIcons) {
      classes.push('icon');

      if (isDir) {
        classes.push('icon-directory');
      } else {
        var ext = extname(file.name);
        var icon = iconLookup(file.name);

        classes.push('icon');
        classes.push('icon-' + ext.substring(1));

        if (classes.indexOf(icon.className) === -1) {
          classes.push(icon.className);
        }
      }
    }

    path.push(encodeURIComponent(file.name));

    var date = file.stat && file.name !== '..'
      ? file.stat.mtime.toDateString() + ' ' + file.stat.mtime.toLocaleTimeString()
      : '';
    var size = file.stat && !isDir
      ? file.stat.size
      : '';

    return '<li><a href="'
      + escapeHtml(normalizeSlashes(normalize(req.prefixPath + path.join('/'))))
      + '" class="' + escapeHtml(classes.join(' ')) + '"'
      + ' title="' + escapeHtml(file.name) + '">'
      + '<span class="name">' + escapeHtml(file.name) + '</span>'
      + '<span class="size">' + escapeHtml(size) + '</span>'
      + '<span class="date">' + escapeHtml(date) + '</span>'
      + '</a></li>';

  }).join('\n') + '</ul>';
}
705283
def _create_html_tasklist(
            self,
            taskpaperDocPath):
        
        self.log.info('starting the ``_create_html_tasklist`` method')

        if self.editorialRootPath:
            return

        title = self.workspaceName
        content = "<h1>%(title)s tasks</h1><ul>\n" % locals()

        # OPEN TASKPAPER FILE
        doc = document(taskpaperDocPath)
        docTasks = doc.tasks

        for task in docTasks:

            tagString = " ".join(task.tags)
            tagString2 = ""
            for t in task.tags:
                t1 = t.split("(")[0]
                tagString2 += """ <span class="%(t1)s tag">@%(t)s</span>""" % locals()

            notes = task.notes
            filepath = notes[0].title.split(" > ")[0]
            basename = os.path.basename(filepath).replace(
                ".taskpaper", "").replace("-", " ")
            filepath = "dryx-open://" + filepath
            taskTitle = u"""<a href="%(filepath)s"><span class="bullet %(tagString)s">◉</span> </a>""" % locals() + \
                task.title[2:] + tagString2

            if len(notes[0].title.split(" > ")) > 1:
                parent = notes[0].title.split(" > ")[1]
                parent = """<span class="parent">%(basename)s > %(parent)s</span></br>\n""" % locals(
                )
            else:
                parent = """<span class="parent">%(basename)s</span></br>\n""" % locals(
                )
            taskContent = """</span>\n\t\t</br><span class="notes">""".join(task.to_string(
                title=False, indentLevel=0).split("\n")[1:])
            if len(taskContent):
                taskContent = """\n\t<br><span class="notes">""" + \
                    taskContent + """\n\t</span>"""
            else:
                taskContent = ""

            htmlTask = """<li class="XXX">%(parent)s%(taskTitle)s%(taskContent)s</li>\n"""  % locals()
            content += htmlTask

        content += "</ul>"

        htmlFilePath = taskpaperDocPath.replace(".taskpaper", ".html")
        try:
            self.log.debug("attempting to open the file %s" % (htmlFilePath,))
            writeFile = codecs.open(
                htmlFilePath, encoding='utf-8', mode='w')
        except IOError, e:
            message = 'could not open the file %s' % (htmlFilePath,)
            self.log.critical(message)
            raise IOError(message)
        writeFile.write(content)
        writeFile.close()

        self.log.info('completed the ``_create_html_tasklist`` method')
        return htmlFilePath
985410
def html(self):
        
        # No empty tooltips
        if self.description:
            tooltip = 'tooltip="{}"'.format(self.description)
        else:
            tooltip = ''

        return entry_html(
            title=self.title,
            thumbnail=self.thumbnail,
            link=self.html_link,
            tooltip=tooltip)