'Extract a dict containing the html, css, and js listings for a given
code sample identified by a name.
This should be pretty agnostic to markup patterns, since it just
requires a parent container with an DID and 3 child elements somewhere
within with class names "html", "css", and "js" - and our syntax
highlighting already does that with <pre>\'s
Given the name of a code sample, attempt to extract it from rendered
HTML with a fallback to non-rendered in case of errors.'

@newrelic.agent.function_trace()
def code_sample(self, name):

    parts = ('html', 'css', 'js')
    data = dict(((x, None) for x in parts))
    try:
        (src, errors) = self.document.get_rendered()
        if errors:
            src = self.document.html
    except:
        src = self.document.html
    if (not src):
        return data
    section = parse(src).extractSection(name).serialize()
    if section:
        sample = pq(('<section>%s</section>' % section))
    else:
        try:
            sample = pq(src).find(('[id=%s]' % quoteattr(name)))
        except ValueError:
            return data
    selector_templates = ('.%s', 'pre[class*="brush:%s"]', 'pre[class*="%s;"]')
    for part in parts:
        selector = ','.join(((selector_template % part) for selector_template in selector_templates))
        src = sample.find(selector).text()
        if (src is not None):
            src = src.replace(u'\xa0', u'    ')
            src = src.replace(u'&nbsp;', u'    ')
        if src:
            data[part] = src
    return data
