_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
31
13.1k
language
stringclasses
1 value
meta_information
dict
q10500
compute_objective_value
train
def compute_objective_value(objective_func, parameters, data=None, cl_runtime_info=None): """Calculate and return the objective function value of the given model for the given parameters. Args: objective_func (mot.lib.cl_function.CLFunction): A CL function with the signature: .. code-block:: c double <func_name>(local const mot_float_type* const x, void* data, local mot_float_type* objective_list); parameters (ndarray): The parameters to use in the evaluation of the model, an (d, p) matrix with d problems and p parameters. data (mot.lib.kernel_data.KernelData): the user provided data for the ``void* data``
python
{ "resource": "" }
q10501
get_log
train
def get_log(username): """ Return a list of page views. Each item is a dict with `datetime`, `method`, `path` and `code` keys. """ redis = get_redis_client() log_key = 'log:{}'.format(username) raw_log = redis.lrange(log_key, 0, -1) log = [] for raw_item in raw_log:
python
{ "resource": "" }
q10502
get_token
train
def get_token(username, length=20, timeout=20): """ Obtain an access token that can be passed to a websocket client. """ redis = get_redis_client() token = get_random_string(length)
python
{ "resource": "" }
q10503
UserLogMiddleware.get_log
train
def get_log(self, request, response): """ Return a dict of data to log for a given request and response. Override this method if you need to log a different set of values. """ return {
python
{ "resource": "" }
q10504
MusicManager.download
train
def download(self, song): """Download a song from a Google Music library. Parameters: song (dict): A song dict. Returns: tuple: Song content as bytestring, suggested filename.
python
{ "resource": "" }
q10505
MusicManager.quota
train
def quota(self): """Get the uploaded track count and allowance. Returns: tuple: Number of uploaded tracks, number of tracks allowed. """ response = self._call( mm_calls.ClientState, self.uploader_id
python
{ "resource": "" }
q10506
MusicManager.songs
train
def songs(self, *, uploaded=True, purchased=True): """Get a listing of Music Library songs. Returns: list: Song dicts. """ if not uploaded and not purchased: raise ValueError("'uploaded' and 'purchased' cannot both be False.") if purchased and uploaded: song_list = [] for chunk in self.songs_iter(export_type=1): song_list.extend(chunk) elif purchased: song_list = [] for chunk in self.songs_iter(export_type=2): song_list.extend(chunk) elif uploaded:
python
{ "resource": "" }
q10507
MusicManager.songs_iter
train
def songs_iter(self, *, continuation_token=None, export_type=1): """Get a paged iterator of Music Library songs. Parameters: continuation_token (str, Optional): The token of the page to return. Default: Not sent to get first page. export_type (int, Optional): The type of tracks to return. 1 for all tracks, 2 for promotional and purchased. Default: ``1`` Yields: list:
python
{ "resource": "" }
q10508
GoogleMusicClient.login
train
def login(self, username, *, token=None): """Log in to Google Music. Parameters: username (str, Optional): Your Google Music username. Used for keeping stored OAuth tokens for multiple accounts separate. device_id (str, Optional): A mobile
python
{ "resource": "" }
q10509
GoogleMusicClient.switch_user
train
def switch_user(self, username='', *, token=None): """Log in to Google Music with a different user. Parameters: username (str, Optional): Your Google Music username. Used for keeping stored OAuth tokens for multiple accounts separate. token (dict, Optional): An OAuth token compatible with ``requests-oauthlib``.
python
{ "resource": "" }
q10510
gen_tau
train
def gen_tau(S, K, delta): """The Robust part of the RSD, we precompute an array for speed """ pivot = floor(K/S) return [S/K * 1/d for d in
python
{ "resource": "" }
q10511
gen_mu
train
def gen_mu(K, delta, c): """The Robust Soliton Distribution on the degree of transmitted blocks """ S = c * log(K/delta) * sqrt(K) tau = gen_tau(S, K, delta)
python
{ "resource": "" }
q10512
gen_rsd_cdf
train
def gen_rsd_cdf(K, delta, c): """The CDF of the RSD on block degree, precomputed for sampling speed"""
python
{ "resource": "" }
q10513
PRNG._get_next
train
def _get_next(self): """Executes the next iteration of the PRNG evolution process, and returns the result """
python
{ "resource": "" }
q10514
PRNG._sample_d
train
def _sample_d(self): """Samples degree given the precomputed distributions above and the linear PRNG output
python
{ "resource": "" }
q10515
PRNG.get_src_blocks
train
def get_src_blocks(self, seed=None): """Returns the indices of a set of `d` source blocks sampled from indices i = 1, ..., K-1 uniformly, where `d` is sampled from the RSD described above. """ if seed: self.state = seed blockseed = self.state d = self._sample_d() have = 0 nums = set()
python
{ "resource": "" }
q10516
run
train
def run(fn, blocksize, seed, c, delta): """Run the encoder until the channel is broken, signalling that the receiver has successfully reconstructed the file """ with open(fn, 'rb')
python
{ "resource": "" }
q10517
MobileClient.album
train
def album(self, album_id, *, include_description=True, include_songs=True): """Get information about an album. Parameters: album_id (str): An album ID. Album IDs start with a 'B'. include_description (bool, Optional): Include description of the album in the returned dict. include_songs (bool, Optional): Include songs from the album in the returned dict. Default: ``True``. Returns: dict: Album information.
python
{ "resource": "" }
q10518
MobileClient.artist
train
def artist( self, artist_id, *, include_albums=True, num_related_artists=5, num_top_tracks=5 ): """Get information about an artist. Parameters: artist_id (str): An artist ID. Artist IDs start with an 'A'. include_albums (bool, Optional): Include albums by the artist in returned dict. Default: ``True``. num_related_artists (int, Optional): Include up to given number of related artists in returned dict. Default: ``5``. num_top_tracks (int, Optional): Include up to given number of top tracks in returned dict.
python
{ "resource": "" }
q10519
MobileClient.browse_podcasts
train
def browse_podcasts(self, podcast_genre_id='JZCpodcasttopchartall'): """Get the podcasts for a genre from the Podcasts browse tab. Parameters: podcast_genre_id (str, Optional): A podcast genre ID as found
python
{ "resource": "" }
q10520
MobileClient.browse_podcasts_genres
train
def browse_podcasts_genres(self): """Get the genres from the Podcasts browse tab dropdown. Returns: list: Genre groups that contain sub groups. """ response = self._call(
python
{ "resource": "" }
q10521
MobileClient.browse_stations
train
def browse_stations(self, station_category_id): """Get the stations for a category from Browse Stations. Parameters: station_category_id (str): A station category ID as found with :meth:`browse_stations_categories`. Returns: list: Station
python
{ "resource": "" }
q10522
MobileClient.browse_stations_categories
train
def browse_stations_categories(self): """Get the categories from Browse Stations. Returns: list: Station categories that can contain subcategories. """ response = self._call( mc_calls.BrowseStationCategories )
python
{ "resource": "" }
q10523
MobileClient.config
train
def config(self): """Get a listing of mobile client configuration settings.""" response = self._call( mc_calls.Config )
python
{ "resource": "" }
q10524
MobileClient.devices
train
def devices(self): """Get a listing of devices registered to the Google Music account.""" response = self._call( mc_calls.DeviceManagementInfo )
python
{ "resource": "" }
q10525
MobileClient.explore_genres
train
def explore_genres(self, parent_genre_id=None): """Get a listing of song genres. Parameters: parent_genre_id (str, Optional): A genre ID. If given, a listing of this genre's sub-genres is returned. Returns: list: Genre dicts.
python
{ "resource": "" }
q10526
MobileClient.explore_tabs
train
def explore_tabs(self, *, num_items=100, genre_id=None): """Get a listing of explore tabs. Parameters: num_items (int, Optional): Number of items per tab to return. Default: ``100`` genre_id (genre_id, Optional): Genre ID from :meth:`explore_genres` to explore. Default: ``None``. Returns: dict: Explore tabs content. """ response = self._call( mc_calls.ExploreTabs, num_items=num_items,
python
{ "resource": "" }
q10527
MobileClient.listen_now_dismissed_items
train
def listen_now_dismissed_items(self): """Get a listing of items dismissed from Listen Now tab."""
python
{ "resource": "" }
q10528
MobileClient.listen_now_items
train
def listen_now_items(self): """Get a listing of Listen Now items. Note: This does not include situations; use the :meth:`situations` method instead. Returns: dict: With ``albums`` and ``stations`` keys of listen now items. """ response = self._call( mc_calls.ListenNowGetListenNowItems )
python
{ "resource": "" }
q10529
MobileClient.playlist_song
train
def playlist_song(self, playlist_song_id): """Get information about a playlist song. Note: This returns the playlist entry information only. For full song metadata, use :meth:`song` with the ``'trackId'`` field. Parameters: playlist_song_id (str): A playlist song ID. Returns: dict: Playlist song information. """ playlist_song_info = next( (
python
{ "resource": "" }
q10530
MobileClient.playlist_song_add
train
def playlist_song_add( self, song, playlist, *, after=None, before=None, index=None, position=None ): """Add a song to a playlist. Note: * Provide no optional arguments to add to end. * Provide playlist song dicts for ``after`` and/or ``before``. * Provide a zero-based ``index``. * Provide a one-based ``position``. Songs are inserted *at* given index or position. It's also possible to add to the end by using ``len(songs)`` for index or ``len(songs) + 1`` for position. Parameters: song (dict): A song dict. playlist (dict): A playlist dict. after (dict, Optional): A playlist song dict ``songs`` will follow. before (dict, Optional): A playlist song dict ``songs`` will precede. index (int, Optional): The zero-based index position to insert ``song``. position (int, Optional): The one-based position to insert ``song``. Returns: dict: Playlist dict including songs. """ prev, next_ = get_ple_prev_next( self.playlist_songs(playlist),
python
{ "resource": "" }
q10531
MobileClient.playlist_songs_add
train
def playlist_songs_add( self, songs, playlist, *, after=None, before=None, index=None, position=None ): """Add songs to a playlist. Note: * Provide no optional arguments to add to end. * Provide playlist song dicts for ``after`` and/or ``before``. * Provide a zero-based ``index``. * Provide a one-based ``position``. Songs are inserted *at* given index or position. It's also possible to add to the end by using ``len(songs)`` for index or ``len(songs) + 1`` for position. Parameters: songs (list): A list of song dicts. playlist (dict): A playlist dict. after (dict, Optional): A playlist song dict ``songs`` will follow. before (dict, Optional): A playlist song dict ``songs`` will precede. index (int, Optional): The zero-based index position to insert ``songs``. position (int, Optional): The one-based position to insert ``songs``. Returns: dict: Playlist dict including songs. """ playlist_songs = self.playlist_songs(playlist) prev, next_ = get_ple_prev_next( playlist_songs, after=after, before=before, index=index, position=position )
python
{ "resource": "" }
q10532
MobileClient.playlist_song_delete
train
def playlist_song_delete(self, playlist_song): """Delete song from playlist. Parameters: playlist_song (str): A playlist song dict. Returns: dict: Playlist dict including songs. """
python
{ "resource": "" }
q10533
MobileClient.playlist_songs_delete
train
def playlist_songs_delete(self, playlist_songs): """Delete songs from playlist. Parameters: playlist_songs (list): A list of playlist song dicts. Returns: dict: Playlist dict including songs. """ if not more_itertools.all_equal( playlist_song['playlistId'] for playlist_song in playlist_songs ): raise ValueError( "All 'playlist_songs' must be from the same playlist." ) mutations =
python
{ "resource": "" }
q10534
MobileClient.playlist_song_move
train
def playlist_song_move( self, playlist_song, *, after=None, before=None, index=None, position=None ): """Move a song in a playlist. Note: * Provide no optional arguments to move to end. * Provide playlist song dicts for ``after`` and/or ``before``. * Provide a zero-based ``index``. * Provide a one-based ``position``. Songs are inserted *at* given index or position. It's also possible to move to the end by using ``len(songs)`` for index or ``len(songs) + 1`` for position. Parameters: playlist_song (dict): A playlist song dict. after (dict, Optional): A playlist song dict ``songs`` will follow. before (dict, Optional): A playlist song dict ``songs`` will precede. index (int, Optional): The zero-based index position to insert ``song``. position (int, Optional): The one-based position to insert ``song``. Returns: dict: Playlist dict including songs. """ playlist_songs = self.playlist(
python
{ "resource": "" }
q10535
MobileClient.playlist_songs_move
train
def playlist_songs_move( self, playlist_songs, *, after=None, before=None, index=None, position=None ): """Move songs in a playlist. Note: * Provide no optional arguments to move to end. * Provide playlist song dicts for ``after`` and/or ``before``. * Provide a zero-based ``index``. * Provide a one-based ``position``. Songs are inserted *at* given index or position. It's also possible to move to the end by using ``len(songs)`` for index or ``len(songs) + 1`` for position. Parameters: playlist_songs (list): A list of playlist song dicts. after (dict, Optional): A playlist song dict ``songs`` will follow. before (dict, Optional): A playlist song dict ``songs`` will precede. index (int, Optional): The zero-based index position to insert ``songs``. position (int, Optional): The one-based position to insert ``songs``. Returns: dict: Playlist dict including songs. """ if not more_itertools.all_equal( playlist_song['playlistId'] for playlist_song in playlist_songs ): raise ValueError( "All 'playlist_songs' must be from the same playlist." ) playlist =
python
{ "resource": "" }
q10536
MobileClient.playlist_songs
train
def playlist_songs(self, playlist): """Get a listing of songs from a playlist. Paramters: playlist (dict): A playlist dict. Returns: list: Playlist song dicts. """ playlist_type = playlist.get('type') playlist_song_list = [] if playlist_type in ('USER_GENERATED', None): start_token = None playlist_song_list = [] while True: response = self._call( mc_calls.PlaylistEntryFeed, max_results=49995, start_token=start_token ) items = response.body.get('data', {}).get('items', []) if items: playlist_song_list.extend(items) start_token = response.body.get('nextPageToken') if start_token is None: break elif playlist_type == 'SHARED': playlist_share_token = playlist['shareToken'] start_token = None playlist_song_list = [] while True: response = self._call(
python
{ "resource": "" }
q10537
MobileClient.playlist
train
def playlist(self, playlist_id, *, include_songs=False): """Get information about a playlist. Parameters: playlist_id (str): A playlist ID. include_songs (bool, Optional): Include songs from the playlist in the returned dict. Default: ``False`` Returns: dict: Playlist information. """ playlist_info = next(
python
{ "resource": "" }
q10538
MobileClient.playlist_create
train
def playlist_create( self, name, description='', *, make_public=False, songs=None ): """Create a playlist. Parameters: name (str): Name to give the playlist. description (str): Description to give the playlist. make_public (bool, Optional): If ``True`` and account has a subscription, make playlist public. Default: ``False`` songs (list, Optional): A list of song dicts to add to the playlist. Returns:
python
{ "resource": "" }
q10539
MobileClient.playlist_subscribe
train
def playlist_subscribe(self, playlist): """Subscribe to a public playlist. Parameters: playlist (dict): A public playlist dict. Returns: dict: Playlist information. """ mutation = mc_calls.PlaylistBatch.create( playlist['name'], playlist['description'], 'SHARED', owner_name=playlist.get('ownerName', ''),
python
{ "resource": "" }
q10540
MobileClient.playlists
train
def playlists(self, *, include_songs=False): """Get a listing of library playlists. Parameters: include_songs (bool, Optional): Include songs in the returned playlist dicts. Default: ``False``.
python
{ "resource": "" }
q10541
MobileClient.playlists_iter
train
def playlists_iter(self, *, start_token=None, page_size=250): """Get a paged iterator of library playlists. Parameters: start_token (str): The token of the page to return. Default: Not sent to get first page. page_size (int, Optional): The maximum number of results per returned page. Max allowed is ``49995``. Default: ``250`` Yields: list: Playlist dicts. """ start_token = None
python
{ "resource": "" }
q10542
MobileClient.podcast
train
def podcast(self, podcast_series_id, *, max_episodes=50): """Get information about a podcast series. Parameters: podcast_series_id (str): A podcast series ID. max_episodes (int, Optional): Include up
python
{ "resource": "" }
q10543
MobileClient.podcasts
train
def podcasts(self, *, device_id=None): """Get a listing of subsribed podcast series. Paramaters: device_id (str, Optional): A mobile device ID. Default: Use ``device_id`` of the :class:`MobileClient` instance.
python
{ "resource": "" }
q10544
MobileClient.podcasts_iter
train
def podcasts_iter(self, *, device_id=None, page_size=250): """Get a paged iterator of subscribed podcast series. Parameters: device_id (str, Optional): A mobile device ID. Default: Use ``device_id`` of the :class:`MobileClient` instance. page_size (int, Optional): The maximum number of results per returned page. Max allowed is ``49995``. Default: ``250`` Yields: list: Podcast series dicts. """ if device_id is None:
python
{ "resource": "" }
q10545
MobileClient.podcast_episode
train
def podcast_episode(self, podcast_episode_id): """Get information about a podcast_episode. Parameters: podcast_episode_id (str): A podcast episode ID. Returns: dict: Podcast episode information. """ response = self._call( mc_calls.PodcastFetchEpisode,
python
{ "resource": "" }
q10546
MobileClient.podcast_episodes
train
def podcast_episodes(self, *, device_id=None): """Get a listing of podcast episodes for all subscribed podcasts. Paramaters: device_id (str, Optional): A mobile device ID. Default: Use ``device_id`` of the :class:`MobileClient` instance.
python
{ "resource": "" }
q10547
MobileClient.podcast_episodes_iter
train
def podcast_episodes_iter(self, *, device_id=None, page_size=250): """Get a paged iterator of podcast episode for all subscribed podcasts. Parameters: device_id (str, Optional): A mobile device ID. Default: Use ``device_id`` of the :class:`MobileClient` instance. page_size (int, Optional): The maximum number of results per returned page. Max allowed is ``49995``. Default: ``250``
python
{ "resource": "" }
q10548
MobileClient.search
train
def search(self, query, *, max_results=100, **kwargs): """Search Google Music and library for content. Parameters: query (str): Search text. max_results (int, Optional): Maximum number of results per type per location to retrieve. I.e up to 100 Google and 100 library for a total of 200 for the default value. Google only accepts values up to 100. Default: ``100`` kwargs (bool, Optional): Any of ``albums``, ``artists``, ``genres``, ``playlists``, ``podcasts``, ``situations``, ``songs``, ``stations``, ``videos`` set to ``True`` will include that result type in the returned dict. Setting none of them will include all result types in the returned dict. Returns: dict: A dict of results separated into keys: ``'albums'``, ``'artists'``, ``'genres'``, ``'playlists'``, ```'podcasts'``, ``'situations'``, ``'songs'``, ``'stations'``, ``'videos'``. Note:
python
{ "resource": "" }
q10549
MobileClient.search_suggestion
train
def search_suggestion(self, query): """Get search query suggestions for query. Parameters: query (str): Search text. Returns: list: Suggested query strings. """ response = self._call( mc_calls.QuerySuggestion, query
python
{ "resource": "" }
q10550
MobileClient.situations
train
def situations(self, *, tz_offset=None): """Get a listing of situations. Parameters: tz_offset (int, Optional): A time zone offset from UTC in seconds. """ response = self._call( mc_calls.ListenNowSituations,
python
{ "resource": "" }
q10551
MobileClient.song
train
def song(self, song_id): """Get information about a song. Parameters: song_id (str): A song ID. Returns: dict: Song information. """ if song_id.startswith('T'): song_info = self._call( mc_calls.FetchTrack, song_id
python
{ "resource": "" }
q10552
MobileClient.songs_add
train
def songs_add(self, songs): """Add store songs to your library. Parameters: songs (list): A list of store song dicts. Returns: list: Songs' library IDs. """ mutations = [mc_calls.TrackBatch.add(song) for song in songs] response = self._call( mc_calls.TrackBatch,
python
{ "resource": "" }
q10553
MobileClient.songs_delete
train
def songs_delete(self, songs): """Delete songs from library. Parameters: song (list): A list of song dicts. Returns: list: Successfully deleted song IDs. """ mutations = [mc_calls.TrackBatch.delete(song['id']) for song in songs] response = self._call( mc_calls.TrackBatch, mutations ) success_ids = [ res['id'] for res in response.body['mutate_response']
python
{ "resource": "" }
q10554
MobileClient.song_play
train
def song_play(self, song): """Add play to song play count. Parameters: song (dict): A song dict. Returns: bool: ``True`` if successful, ``False`` if not. """ if 'storeId' in song: song_id = song['storeId'] elif 'trackId' in song: song_id = song['trackId'] else: song_id = song['id']
python
{ "resource": "" }
q10555
MobileClient.song_rate
train
def song_rate(self, song, rating): """Rate song. Parameters: song (dict): A song dict. rating (int): 0 (not rated), 1 (thumbs down), or 5 (thumbs up). Returns: bool: ``True`` if successful, ``False`` if not. """ if 'storeId' in
python
{ "resource": "" }
q10556
MobileClient.songs
train
def songs(self): """Get a listing of library songs. Returns: list: Song dicts. """ song_list = []
python
{ "resource": "" }
q10557
MobileClient.songs_iter
train
def songs_iter(self, *, page_size=250): """Get a paged iterator of library songs. Parameters: page_size (int, Optional): The maximum number of results per returned page. Max allowed is ``49995``. Default: ``250`` Yields: list: Song dicts. """ start_token = None while True: response = self._call( mc_calls.TrackFeed, max_results=page_size,
python
{ "resource": "" }
q10558
MobileClient.station
train
def station(self, station_id, *, num_songs=25, recently_played=None): """Get information about a station. Parameters: station_id (str): A station ID. Use 'IFL' for I'm Feeling Lucky. num_songs (int, Optional): The maximum number of songs to return from the station. Default: ``25`` recently_played (list, Optional): A list of dicts in the form of {'id': '', 'type'} where ``id`` is a song
python
{ "resource": "" }
q10559
MobileClient.station_feed
train
def station_feed(self, *, num_songs=25, num_stations=4): """Generate stations. Note: A Google Music subscription is required. Parameters: num_songs (int, Optional): The total number of songs to return. Default: ``25`` num_stations (int, Optional): The number of stations to return when no station_infos is provided. Default: ``5`` Returns: list: Station information dicts. """
python
{ "resource": "" }
q10560
MobileClient.station_songs
train
def station_songs(self, station, *, num_songs=25, recently_played=None): """Get a listing of songs from a station. Parameters: station (str): A station dict. num_songs (int, Optional): The maximum number of songs to return from the station. Default: ``25`` recently_played (list, Optional): A list of dicts in the form of {'id': '', 'type'} where ``id`` is a song ID and ``type`` is 0 for a library song and
python
{ "resource": "" }
q10561
MobileClient.stations
train
def stations(self, *, generated=True, library=True): """Get a listing of library stations. The listing can contain stations added to the library and generated from the library. Parameters: generated (bool, Optional): Include generated stations. Default: True library (bool, Optional): Include library stations. Default: True Returns: list: Station information dicts. """ station_list = []
python
{ "resource": "" }
q10562
MobileClient.stations_iter
train
def stations_iter(self, *, page_size=250): """Get a paged iterator of library stations. Parameters: page_size (int, Optional): The maximum number of results per returned page. Max allowed is ``49995``. Default: ``250`` Yields: list: Station dicts. """ start_token = None while True: response = self._call( mc_calls.RadioStation,
python
{ "resource": "" }
q10563
MobileClient.stream
train
def stream(self, item, *, device_id=None, quality='hi', session_token=None): """Get MP3 stream of a podcast episode, library song, station_song, or store song. Note: Streaming requires a ``device_id`` from a valid, linked mobile device. Parameters: item (str): A podcast episode, library song, station_song, or store song. A Google Music subscription is required to stream store songs. device_id (str, Optional): A mobile device ID. Default: Use ``device_id`` of the :class:`MobileClient` instance. quality (str, Optional): Stream quality is one of ``'hi'`` (320Kbps), ``'med'`` (160Kbps), or ``'low'`` (128Kbps). Default: ``'hi'``. session_token (str): Session token
python
{ "resource": "" }
q10564
MobileClient.stream_url
train
def stream_url(self, item, *, device_id=None, quality='hi', session_token=None): """Get a URL to stream a podcast episode, library song, station_song, or store song. Note: Streaming requires a ``device_id`` from a valid, linked mobile device. Parameters: item (str): A podcast episode, library song, station_song, or store song. A Google Music subscription is required to stream store songs. device_id (str, Optional): A mobile device ID. Default: Use ``device_id`` of the :class:`MobileClient` instance. quality (str, Optional): Stream quality is one of ``'hi'`` (320Kbps), ``'med'`` (160Kbps), or ``'low'`` (128Kbps). Default: ``'hi'``. session_token (str): Session token from a station dict required for unsubscribed users to stream a station song. station['sessionToken'] as returend by :meth:`station` only exists for free accounts. Returns: str: A URL to an MP3 file. """ if device_id is None: device_id = self.device_id if 'episodeId' in item: # Podcast episode. response = self._call( mc_calls.PodcastEpisodeStreamURL, item['episodeId'], quality=quality, device_id=device_id ) elif 'wentryid' in item: # Free account station song. response = self._call( mc_calls.RadioStationTrackStreamURL, item['storeId'], item['wentryid'], session_token, quality=quality, device_id=device_id ) elif 'trackId' in item: # Playlist song. response = self._call( mc_calls.TrackStreamURL, item['trackId'], quality=quality, device_id=device_id ) elif 'storeId' in item
python
{ "resource": "" }
q10565
MobileClient.thumbs_up_songs
train
def thumbs_up_songs(self, *, library=True, store=True): """Get a listing of 'Thumbs Up' store songs. Parameters: library (bool, Optional): Include 'Thumbs Up' songs from library. Default: True generated (bool, Optional): Include 'Thumbs Up' songs from store. Default: True Returns: list: Dicts of 'Thumbs Up' songs. """ thumbs_up_songs = [] if library is True:
python
{ "resource": "" }
q10566
MobileClient.top_charts
train
def top_charts(self): """Get a listing of the default top charts.""" response
python
{ "resource": "" }
q10567
MobileClient.top_charts_for_genre
train
def top_charts_for_genre(self, genre_id): """Get a listing of top charts for a top chart genre. Parameters: genre_id (str): A top chart
python
{ "resource": "" }
q10568
MobileClient.top_charts_genres
train
def top_charts_genres(self): """Get a listing of genres from the browse top charts tab."""
python
{ "resource": "" }
q10569
run
train
def run(stream=sys.stdin.buffer): """Reads from stream, applying the LT decoding algorithm to incoming encoded blocks until
python
{ "resource": "" }
q10570
_split_file
train
def _split_file(f, blocksize): """Block file byte contents into blocksize chunks, padding last one if necessary """ f_bytes = f.read() blocks = [int.from_bytes(f_bytes[i:i+blocksize].ljust(blocksize,
python
{ "resource": "" }
q10571
encoder
train
def encoder(f, blocksize, seed=None, c=sampler.DEFAULT_C, delta=sampler.DEFAULT_DELTA): """Generates an infinite sequence of blocks to transmit to the receiver """ # Generate seed if not provided if seed is None: seed = randint(0, 1 << 31 - 1) # get file blocks filesize, blocks = _split_file(f, blocksize) # init stream vars K = len(blocks) prng = sampler.PRNG(params=(K, delta, c)) prng.set_seed(seed) # block generation loop while True: blockseed, d, ix_samples = prng.get_src_blocks() block_data = 0
python
{ "resource": "" }
q10572
_read_block
train
def _read_block(blocksize, stream): """Read block data from network into integer type """
python
{ "resource": "" }
q10573
read_blocks
train
def read_blocks(stream): """Generate parsed blocks from input stream """ while True: header = _read_header(stream)
python
{ "resource": "" }
q10574
BlockGraph.add_block
train
def add_block(self, nodes, data): """Adds a new check node and edges between that node and all source nodes it connects, resolving all message passes that become possible as a result. """ # We can eliminate this source node if len(nodes) == 1: to_eliminate = list(self.eliminate(next(iter(nodes)), data)) # Recursively eliminate all nodes that can now be resolved while len(to_eliminate): other, check = to_eliminate.pop() to_eliminate.extend(self.eliminate(other, check)) else: # Pass messages from already-resolved source nodes for node in list(nodes): if node in self.eliminated: nodes.remove(node) data ^= self.eliminated[node] # Resolve if we are left
python
{ "resource": "" }
q10575
BlockGraph.eliminate
train
def eliminate(self, node, data): """Resolves a source node, passing the message to all associated checks """ # Cache resolved value self.eliminated[node] = data others = self.checks[node]
python
{ "resource": "" }
q10576
mobileclient
train
def mobileclient(username=None, device_id=None, *, token=None, locale='en_US'): """Create and authenticate a Google Music mobile client. >>> import google_music >>> mc = google_music.mobileclient('username') Parameters: username (str, Optional): Your Google Music username. This is used to store OAuth credentials for different accounts separately.
python
{ "resource": "" }
q10577
_dendropy_to_dataframe
train
def _dendropy_to_dataframe( tree, add_node_labels=True, use_uids=True): """Convert Dendropy tree to Pandas dataframe.""" # Maximum distance from root. tree.max_distance_from_root() # Initialize the data object. idx = [] data = { 'type': [], 'id': [], 'parent': [], 'length': [], 'label': [], 'distance': []} if use_uids: data['uid'] = [] # Add labels to internal nodes if set to true. if add_node_labels: for i, node in enumerate(tree.internal_nodes()): node.label = str(i) for node in tree.nodes(): # Get node type if node.is_leaf(): type_ = 'leaf' label = str(node.taxon.label).replace(' ', '_') elif node.is_internal(): type_ = 'node' label = str(node.label) # Set node label and parent. id_ = label parent_node = node.parent_node length = node.edge_length distance = node.distance_from_root() # Is this node a root? if parent_node is None and length is None: parent_label =
python
{ "resource": "" }
q10578
_read
train
def _read( filename=None, data=None, schema=None, add_node_labels=True, use_uids=True ): """Read a phylogenetic tree into a phylopandas.DataFrame. The resulting DataFrame has the following columns: - name: label for each taxa or node. - id: unique id (created by phylopandas) given to each node. - type: type of node (leaf, internal, or root). - parent: parent id. necessary for constructing trees. - length: length of branch from parent to node. - distance: distance from root. Parameters ----------
python
{ "resource": "" }
q10579
pandas_df_to_biopython_seqrecord
train
def pandas_df_to_biopython_seqrecord( df, id_col='uid', sequence_col='sequence', extra_data=None, alphabet=None, ): """Convert pandas dataframe to biopython seqrecord for easy writing. Parameters ---------- df : Dataframe Pandas dataframe to convert id_col : str column in dataframe to use as sequence label sequence_col str: column in dataframe to use as sequence data extra_data : list extra columns to use in sequence description line alphabet : biopython Alphabet object Returns ------- seq_records : List of biopython seqrecords. """ seq_records = [] for i, row in df.iterrows(): # Tries getting sequence data. If a TypeError at the seqrecord # creation is thrown, it is assumed that this row does not contain # sequence data and therefore the row is ignored. try: # Get sequence seq = Seq(row[sequence_col], alphabet=alphabet) #
python
{ "resource": "" }
q10580
pandas_series_to_biopython_seqrecord
train
def pandas_series_to_biopython_seqrecord( series, id_col='uid', sequence_col='sequence', extra_data=None, alphabet=None ): """Convert pandas series to biopython seqrecord for easy writing. Parameters ---------- series : Series Pandas series to convert id_col : str column in dataframe to use as sequence label sequence_col : str column in dataframe to use as sequence data extra_data : list extra columns to use in sequence description line Returns ------- seq_records : List of biopython seqrecords. """ # Get sequence
python
{ "resource": "" }
q10581
_write
train
def _write( data, filename=None, schema='fasta', id_col='uid', sequence_col='sequence', extra_data=None, alphabet=None, **kwargs): """General write function. Write phylopanda data to biopython format. Parameters ---------- filename : str File to write string to. If no filename is given, a string will be returned. sequence_col : str (default='sequence') Sequence column name in DataFrame. id_col : str (default='id') ID column name in DataFrame id_only : bool (default=False) If True, use only the ID column to label sequences in fasta. """ # Check Alphabet if given if alphabet is None: alphabet = Bio.Alphabet.Alphabet() elif alphabet in ['dna', 'rna', 'protein', 'nucleotide']: alphabet = getattr(Bio.Alphabet, 'generic_{}'.format(alphabet)) else: raise Exception( "The alphabet is not recognized. Must be 'dna', 'rna', " "'nucleotide', or 'protein'.") # Build a list of records from a pandas DataFrame if type(data) is pd.DataFrame: seq_records = pandas_df_to_biopython_seqrecord( data, id_col=id_col,
python
{ "resource": "" }
q10582
_read
train
def _read( filename, schema, seq_label='sequence', alphabet=None, use_uids=True, **kwargs): """Use BioPython's sequence parsing module to convert any file format to a Pandas DataFrame. The resulting DataFrame has the following columns: - name - id - description - sequence """ # Check Alphabet if given if alphabet is None: alphabet = Bio.Alphabet.Alphabet() elif alphabet in ['dna', 'rna', 'protein', 'nucleotide']: alphabet = getattr(Bio.Alphabet, 'generic_{}'.format(alphabet)) else:
python
{ "resource": "" }
q10583
read_blast_xml
train
def read_blast_xml(filename, **kwargs): """Read BLAST XML format.""" # Read file. with open(filename, 'r') as f: blast_record = NCBIXML.read(f) # Prepare DataFrame fields. data = {'accession': [], 'hit_def': [], 'hit_id': [], 'title': [], 'length': [], 'e_value': [], 'sequence': []} # Get alignments from blast result. for i, s in enumerate(blast_record.alignments): data['accession'] = s.accession data['hit_def'] = s.hit_def
python
{ "resource": "" }
q10584
_pandas_df_to_dendropy_tree
train
def _pandas_df_to_dendropy_tree( df, taxon_col='uid', taxon_annotations=[], node_col='uid', node_annotations=[], branch_lengths=True, ): """Turn a phylopandas dataframe into a dendropy tree. Parameters ---------- df : DataFrame DataFrame containing tree data. taxon_col : str (optional) Column in dataframe to label the taxon. If None, the index will be used. taxon_annotations : str List of columns to annotation in the tree taxon. node_col : str (optional) Column in dataframe to label the nodes. If None, the index will be used. node_annotations : str List of columns to annotation in the node taxon. branch_lengths : bool If True, inclues branch lengths. """ if isinstance(taxon_col, str) is False: raise Exception("taxon_col must be a string.") if isinstance(node_col, str) is False: raise Exception("taxon_col must be a string.") # Construct a list of nodes from dataframe. taxon_namespace = dendropy.TaxonNamespace() nodes = {} for idx in df.index: # Get node data. data = df.loc[idx] # Get taxon for node (if leaf node). taxon = None if data['type'] == 'leaf': taxon = dendropy.Taxon(label=data[taxon_col]) # Add annotations data. for ann in taxon_annotations: taxon.annotations.add_new(ann, data[ann]) taxon_namespace.add_taxon(taxon) # Get label for node. label = data[node_col] # Get edge length. edge_length = None if branch_lengths is True: edge_length = data['length'] # Build a node n = dendropy.Node( taxon=taxon, label=label,
python
{ "resource": "" }
q10585
_write
train
def _write( df, filename=None, schema='newick', taxon_col='uid', taxon_annotations=[], node_col='uid', node_annotations=[], branch_lengths=True, **kwargs ): """Write a phylopandas tree DataFrame to various formats. Parameters ---------- df : DataFrame DataFrame containing tree data. filename : str filepath to write out tree. If None, will return string. schema : str tree format to write out. taxon_col : str (optional) Column in dataframe to label the taxon. If None, the index will be used. taxon_annotations : str List of columns to annotation in the tree taxon. node_col : str (optional) Column in dataframe to label the nodes. If None, the index will be used. node_annotations : str
python
{ "resource": "" }
q10586
get_random_id
train
def get_random_id(length): """Generate a random, alpha-numerical id.""" alphabet = string.ascii_uppercase + string.ascii_lowercase
python
{ "resource": "" }
q10587
PyGreen.set_folder
train
def set_folder(self, folder): """ Sets the folder where the files to serve are located. """
python
{ "resource": "" }
q10588
PyGreen.run
train
def run(self, host='0.0.0.0', port=8080): """ Launch a development web server. """
python
{ "resource": "" }
q10589
PyGreen.get
train
def get(self, path): """ Get the content of a file, indentified by its path relative to the folder configured in PyGreen. If the file extension is one of the extensions that should be processed
python
{ "resource": "" }
q10590
PyGreen.gen_static
train
def gen_static(self, output_folder): """ Generates a complete static version of the web site. It will stored in output_folder. """ files = [] for l in self.file_listers: files += l()
python
{ "resource": "" }
q10591
PyGreen.cli
train
def cli(self, cmd_args=None): """ The command line interface of PyGreen. """ logging.basicConfig(level=logging.INFO, format='%(message)s') parser = argparse.ArgumentParser(description='PyGreen, micro web framework/static web site generator') subparsers = parser.add_subparsers(dest='action') parser_serve = subparsers.add_parser('serve', help='serve the web site') parser_serve.add_argument('-p', '--port', type=int, default=8080, help='port to serve on') parser_serve.add_argument('-f', '--folder', default=".", help='folder containg files to serve') parser_serve.add_argument('-d', '--disable-templates', action='store_true', default=False, help='just serve static files, do not use Mako') def serve(): if args.disable_templates: self.template_exts = set([])
python
{ "resource": "" }
q10592
WSGIMimeRender
train
def WSGIMimeRender(*args, **kwargs): ''' A wrapper for _WSGIMimeRender that wrapps the inner callable with wsgi_wrap first. ''' def wrapper(*args2, **kwargs2): # take the function def wrapped(f):
python
{ "resource": "" }
q10593
URI.relative
train
def relative(self): """Identify if this URI is relative to some "current context". For example, if the protocol is missing, it's protocol-relative. If the host is missing, it's host-relative, etc. """
python
{ "resource": "" }
q10594
URI.resolve
train
def resolve(self, uri=None, **parts): """Attempt to resolve a new URI given an updated URI, partial or complete.""" if uri: result = self.__class__(urljoin(str(self), str(uri))) else: result = self.__class__(self) for part, value
python
{ "resource": "" }
q10595
JalaliDate.replace
train
def replace(self, year=None, month=None, day=None): """ Replaces the given arguments on this instance, and return a new instance. :param year: :param month: :param day: :return: A :py:class:`khayyam.JalaliDate` with the same attributes, except for those attributes given new values by which keyword arguments are specified.
python
{ "resource": "" }
q10596
JalaliDate.todate
train
def todate(self): """ Calculates the corresponding day in the gregorian calendar. this is the main use case of this library. :return: Corresponding date
python
{ "resource": "" }
q10597
JalaliDatetime.date
train
def date(self): """ Return date object with same year, month and day. :rtype: :py:class:`khayyam.JalaliDate`
python
{ "resource": "" }
q10598
levinson_1d
train
def levinson_1d(r, order): """Levinson-Durbin recursion, to efficiently solve symmetric linear systems with toeplitz structure. Parameters --------- r : array-like input array to invert (since the matrix is symmetric Toeplitz, the corresponding pxp matrix is defined by p items only). Generally the autocorrelation of the signal for linear prediction coefficients estimation. The first item must be a non zero real. Notes ---- This implementation is in python, hence unsuitable for any serious computation. Use it as educational and reference purpose only. Levinson is a well-known algorithm to solve the Hermitian toeplitz equation: _ _ -R[1] = R[0] R[1] ... R[p-1] a[1] : : : : * : : : : _ * : -R[p] = R[p-1] R[p-2] ... R[0] a[p] _ with respect to a ( is the complex conjugate). Using the special symmetry in the matrix, the inversion can be done in O(p^2) instead of O(p^3). """ r = np.atleast_1d(r) if r.ndim > 1: raise ValueError("Only rank 1 are supported for now.") n = r.size if n <
python
{ "resource": "" }
q10599
acorr_lpc
train
def acorr_lpc(x, axis=-1): """Compute autocorrelation of x along the given axis. This compute the biased autocorrelation estimator (divided by the size of input signal) Notes ----- The reason why we do not use acorr directly is for speed issue.""" if not np.isrealobj(x): raise ValueError("Complex input not supported yet") maxlag = x.shape[axis]
python
{ "resource": "" }