Grab genre URLs from iTunes Podcast preview
425498
def get_genres(self):
    
    page = r.get(ITUNES_GENRES_URL)
    tree = html.fromstring(page.content)
    elements = tree.xpath("//a[@class='top-level-genre']")
    return [e.attrib['href'] for e in elements]
981400
def prepend_urls(self):
        
        return [
            url(r"^(?P<resource_name>%s)/view/(?P<name>[\w\d_.-]+)%s$" % (self._meta.resource_name, trailing_slash()),
                self.wrap_view('view'), name="api_fileitem_view"),
            url(r"^(?P<resource_name>%s)/download/(?P<name>[\w\d_.-]+)%s$" % (
            self._meta.resource_name, trailing_slash()), self.wrap_view('download'), name="api_fileitem_download"),
            url(r"^(?P<resource_name>%s)/(?P<pk>\w[\w/-]*)/download%s$" % (self._meta.resource_name, trailing_slash()),
                self.wrap_view('download'), name="api_fileitem_download"),
            url(r"^(?P<resource_name>%s)/(?P<name>[\w\d_.-]+)/download%s$"
                % (self._meta.resource_name, trailing_slash()), self.wrap_view('download'),
                name="api_fileitem_download"),
            url(r"^(?P<resource_name>%s)/(?P<pk>\w[\w/-]*)/view%s$"
                % (self._meta.resource_name, trailing_slash()), self.wrap_view('view'), name="api_fileitem_view"),
            url(r"^(?P<resource_name>%s)/(?P<name>[\w\d_.-]+)/view%s$"
                % (self._meta.resource_name, trailing_slash()), self.wrap_view('view'), name="api_fileitem_view"),
            url(r"^(?P<resource_name>%s)/(?P<name>[\w\d_.-]+)/$"
                % self._meta.resource_name, self.wrap_view('dispatch_detail'), name="api_dispatch_detail_name"),
            url(r"^(?P<resource_name>%s)/(?P<id>[\d]+)/$"
                % self._meta.resource_name, self.wrap_view('dispatch_detail'), name="api_dispatch_detail"),
        ]
795798
def write_urls_index(app, exc):
    '''
    
    '''
    inventory = os.path.join(app.builder.outdir, 'objects.inv')
    objects = sphinx.ext.intersphinx.fetch_inventory(app, DOCS_URL, inventory)

    with open(os.path.join(app.builder.outdir, 'shorturls.json'), 'w') as f:
        json.dump(objects, f)
1122462
def parse_podcast(url):
    
    try:
        podcast = feedparser.parse(url)
        wentwrong = "urlopen" in str(podcast["bozo_exception"])
    except KeyError:
        wentwrong = False
    if wentwrong:
        print("Error: ", url, ": ", str(podcast["bozo_exception"]))
    return podcast
569008
def _get_contents_between(string, opener, closer):
    
    opener_location = string.index(opener)
    closer_location = string.index(closer)
    content = string[opener_location + 1:closer_location]
    return content
847121
def samples(self, anystring, limit=None, offset=None, sortby=None):
        ''''''

        uri = self._uris['samples'].format(anystring)
        params = {'limit': limit, 'offset': offset, 'sortby': sortby}

        return self.get_parse(uri, params)
1149601
def extract_listing(pid):
    """"""
    print("Extracting tracklisting...")
    listing_etree = open_listing_page(pid + '/segments.inc')
    track_divs = listing_etree.xpath('//div[@class="segment__track"]')

    listing = []
    for track_div in track_divs:
        try:
            artist_names = track_div.xpath('.//span[@property="byArtist"]'
                                           '//span[@class="artist"]/text()')
        except ValueError:
            artist_names = ['']

        if not artist_names:
            artist_names = ['']

        if len(artist_names) > 1:
            artists = ', '.join(artist_names[:-1]) + ' & ' + artist_names[-1]
        else:
            artists = artist_names[0]

        try:
            title, = track_div.xpath('.//p/span[@property="name"]/text()')
        except ValueError:
            title = ''

        try:
            label, = track_div.xpath('.//abbr[@title="Record Label"]'
                                     '/span[@property="name"]/text()')
        except ValueError:
            label = ''
        listing.append((artists, title, label))
    return listing
1326226
def scrape_mixcloud_url(mc_url, num_tracks=sys.maxsize, folders=False, custom_path=''):
    

    try:
        data = get_mixcloud_data(mc_url)
    except Exception as e:
        puts_safe(colored.red("Problem downloading ") + mc_url)
        print(e)
        return []

    filenames = []

    track_artist = sanitize_filename(data['artist'])
    track_title = sanitize_filename(data['title'])
    track_filename = track_artist + ' - ' + track_title + data['mp3_url'][-4:]

    if folders:
        track_artist_path = join(custom_path, track_artist)
        if not exists(track_artist_path):
            mkdir(track_artist_path)
        track_filename = join(track_artist_path, track_filename)
        if exists(track_filename):
            puts_safe(colored.yellow("Skipping") + colored.white(': ' + data['title'] + " - it already exists!"))
            return []
    else:
        track_filename = join(custom_path, track_filename)

    puts_safe(colored.green("Downloading") + colored.white(
        ': ' + data['artist'] + " - " + data['title'] + " (" + track_filename[-4:] + ")"))
    download_file(data['mp3_url'], track_filename)
    if track_filename[-4:] == '.mp3':
        tag_file(track_filename,
                 artist=data['artist'],
                 title=data['title'],
                 year=data['year'],
                 genre="Mix",
                 artwork_url=data['artwork_url'])
    filenames.append(track_filename)

    return filenames
25541
def preview(self):
        """"""

        if hasattr(self, '_url'):
            url = self._url + '/preview'
            return self.post(url)
        else:
            url = urljoin(recurly.base_uri(), self.collection_path + '/preview')
            return self.post(url)
822542
def preview(ident):
    ''''''
    source = get_source(ident)
    cls = backends.get(current_app, source.backend)
    max_items = current_app.config['HARVEST_PREVIEW_MAX_ITEMS']
    backend = cls(source, dryrun=True, max_items=max_items)
    return backend.harvest()
368469
function getIndexFile(answers) {
    const content = format(`
        import { create } from 'rung-sdk';
        import { String as Text } from 'rung-cli/dist/types';

        function render(name) {
            return <b>{ _('Hello {{name}}', { name }) }</b>;
        }

        function main(context) {
            const { name } = context.params;
            return {
                alerts: [{
                    title: _('Welcome'),
                    content: render(name),
                    resources: []
                }]
            };
        }

        const params = {
            name: {
                description: _('What is your name?'),
                type: Text
            }
        };

        export default create(main, {
            params,
            primaryKey: true,
            title: _(${JSON.stringify(answers.title)}),
            description: _(${JSON.stringify(answers.description)}),
            preview: render('Trixie')
        });
    `);

    return { filename: path.join(answers.name, 'index.js'), content };
}
858676
function(storybook, baseUrl, previewRoute) {
  // clean baseUrl. remove query/hash/trailing-slash
  var urlObj = url.parse(baseUrl);
  urlObj = omit(urlObj, 'hash', 'search', 'query');
  urlObj.pathname = urlObj.pathname.replace(/\/$/, '');
  baseUrl = url.format(urlObj);
  // transform into states
  var states = [];
  storybook.forEach(function(component) {
    component.stories.forEach(function(story) {
      var previewUrl = baseUrl + previewRoute + '?dataId=0&selectedKind=' + encodeURIComponent(component.kind) + '&selectedStory=' + encodeURIComponent(story.name);
      var state = {
        url: previewUrl,
        name: component.kind + ': ' + story.name
      };
      if (story.steps) {
        state.steps = story.steps;
      }
      states.push(state);
    });
  });
  return states;
}
623335
def Parse(self, persistence, knowledge_base, download_pathtype):
    """"""
    pathspecs = []

    if isinstance(persistence, rdf_client.OSXServiceInformation):
      if persistence.program:
        pathspecs = rdf_paths.PathSpec(
            path=persistence.program, pathtype=download_pathtype)
      elif persistence.args:
        pathspecs = rdf_paths.PathSpec(
            path=persistence.args[0], pathtype=download_pathtype)

    for pathspec in pathspecs:
      yield rdf_standard.PersistenceFile(pathspec=pathspec)
685282
def media(self, uri):
        """"""
        try:
            local_path, _ = urllib.request.urlretrieve(uri)
            metadata = mutagen.File(local_path, easy=True)
            if metadata.tags:
                self._tags = metadata.tags
            title = self._tags.get(TAG_TITLE, [])
            self._manager[ATTR_TITLE] = title[0] if len(title) else ''
            artist = self._tags.get(TAG_ARTIST, [])
            self._manager[ATTR_ARTIST] = artist[0] if len(artist) else ''
            album = self._tags.get(TAG_ALBUM, [])
            self._manager[ATTR_ALBUM] = album[0] if len(album) else ''
            local_uri = 'file://{}'.format(local_path)

        # urllib.error.HTTPError
        except Exception:  # pylint: disable=broad-except
            local_uri = uri
        self._player.set_state(Gst.State.NULL)
        self._player.set_property(PROP_URI, local_uri)
        self._player.set_state(Gst.State.PLAYING)
        self.state = STATE_PLAYING
        self._manager[ATTR_URI] = uri
        self._manager[ATTR_DURATION] = self._duration()
        self._manager[ATTR_VOLUME] = self._player.get_property(PROP_VOLUME)
        _LOGGER.info('playing %s (as %s)', uri, local_uri)
985875
def parse_torrent_buffer(torrent):
    """"""
    md = {}
    try:
        metadata = bencode.bdecode(torrent)
    except bencode.BTL.BTFailure:
        print 'Not a valid encoded torrent'
        return None
    if 'announce-list' in metadata:
        md['trackers'] = []
        for tracker in metadata['announce-list']:
            md['trackers'].append(tracker[0])
    if 'announce' in metadata:
        md['trackers'].append(metadata['announce'])
    md['trackers'] = list(set(md['trackers']))
    if 'name' in metadata['info']:
        md['name'] = metadata['info']['name']
    webseeds = []
    if 'httpseeds' in metadata:
        webseeds = metadata['httpseeds']
    if 'url-list' in metadata:
        webseeds += md['url-list']
    if webseeds:
        md['webseeds'] = webseeds
    if 'created by' in metadata:
        md['creator'] = metadata['created by']
    if 'creation date' in metadata:
        utc_dt = datetime.utcfromtimestamp(metadata['creation date'])
        md['created'] = utc_dt.strftime('%Y-%m-%d %H:%M:%S')
    if 'comment' in metadata:
        md['comment'] = metadata['comment']
    md['piece_size'] = metadata['info']['piece length']
    if 'length' in metadata['info']:
        md['file'] = {'path': metadata['info']['name'],
                      'length': metadata['info']['length']}
    if 'files' in metadata['info']:
        md['files'] = []
        for item in metadata['info']['files']:
            md['files'].append(
                {'path': item['path'][0], 'length': item['length']})
    # TODO check if torrent is private and encoding
    hashcontents = bencode.bencode(metadata['info'])
    digest = hashlib.sha1(hashcontents).digest()
    md['infoHash'] = hashlib.sha1(hashcontents).hexdigest()
    b32hash = base64.b32encode(digest)
    md['infoHash_b32'] = b32hash
    md['pieces'] = _split_pieces(metadata['info']['pieces'])
    md['total_size'] = hsize(sum([x['length'] for x in md['files']]))
    return md
938102
function getFormat (obj) {
	//undefined format - no format-related props, for sure
	if (!obj) return {}

	//if is string - parse format
	if (typeof obj === 'string' || obj.id) {
		return parse(obj.id || obj)
	}

	//if audio buffer - we know it’s format
	else if (isAudioBuffer(obj)) {
		var arrayFormat = fromTypedArray(obj.getChannelData(0))
		return {
			sampleRate: obj.sampleRate,
			channels: obj.numberOfChannels,
			samplesPerFrame: obj.length,
			float: true,
			signed: true,
			bitDepth: arrayFormat.bitDepth
		}
	}

	//if is array - detect format
	else if (ArrayBuffer.isView(obj)) {
		return fromTypedArray(obj)
	}

	//FIXME: add AudioNode, stream detection

	//else detect from obhect
	return fromObject(obj)
}
1093661
def get_now_playing(self):
        

        params = self._get_params()
        params["limit"] = "1"

        doc = self._request(self.ws_prefix + ".getRecentTracks", False, params)

        tracks = doc.getElementsByTagName("track")

        if len(tracks) == 0:
            return None

        e = tracks[0]

        if not e.hasAttribute("nowplaying"):
            return None

        artist = _extract(e, "artist")
        title = _extract(e, "name")

        return Track(artist, title, self.network, self.name)