Instruction:
Explain what the following Python 3 code does
def basic(type='artist-radio', artist_id=None, artist=None, song_id=None, song=None, track_id=None, dmca=False,
          results=15, buckets=None, limit=False,genres=None,):
    """Get a basic playlist

    Args:

    Kwargs:
        type (str): a string representing the playlist type ('artist-radio' or 'song-radio')

        artist_id (str): the artist_id to seed the playlist

        artist (str): the name of an artist to seed the playlist

        song_id (str): a song_id to seed the playlist

        song (str): the name of a song to seed the playlist

        track_id (str): the name of a track to seed the playlist

        dmca (bool): make the playlist dmca-compliant

        results (int): desired length of the playlist

        buckets (list): A list of strings specifying which buckets to retrieve

        limit (bool): Whether results should be restricted to any idspaces given in the buckets parameter
    """

    limit = str(limit).lower()
    dmca = str(dmca).lower()

    kwargs = locals()
    kwargs['bucket'] = kwargs['buckets']
    del kwargs['buckets']
    kwargs['genre'] = kwargs['genres']
    del kwargs['genres']

    result = util.callm("%s/%s" % ('playlist', 'basic'), kwargs)
    return [Song(**util.fix(s_dict)) for s_dict in result['response']['songs']]

Response: Get a basic playlist with optional parameters


Instruction:
Can you generate the documentation for the following Python 3 function
def static(type='artist', artist_pick='song_hotttnesss-desc', variety=.5, artist_id=None, artist=None, song_id=None,
           track_id=None, description=None, style=None, mood=None, results=15, max_tempo=None, min_tempo=None,
           max_duration=None, min_duration=None, max_loudness=None, min_loudness=None, max_danceability=None,
           min_danceability=None, max_energy=None, min_energy=None, artist_max_familiarity=None,
           artist_min_familiarity=None, artist_max_hotttnesss=None, artist_min_hotttnesss=None,
           song_max_hotttnesss=None, song_min_hotttnesss=None, min_longitude=None, max_longitude=None,
           min_latitude=None, max_latitude=None, adventurousness=0.2, mode=None, key=None, buckets=None, sort=None,
           limit=False, seed_catalog=None, source_catalog=None, rank_type=None, test_new_things=None,
           artist_start_year_after=None, artist_start_year_before=None, artist_end_year_after=None,
           artist_end_year_before=None, dmca=False, distribution=None, song_type=None, genres=None):
    """Get a static playlist

    Args:

    Kwargs:
        type (str): a string representing the playlist type ('artist', 'artist-radio', ...)

        artist_pick (str): How songs should be chosen for each artist

        variety (float): A number between 0 and 1 specifying the variety of the playlist

        artist_id (str): the artist_id

        artist (str): the name of an artist

        song_id (str): the song_id

        track_id (str): the track id

        description (str): A string describing the artist and song

        style (str): A string describing the style/genre of the artist and song

        mood (str): A string describing the mood of the artist and song

        results (int): An integer number of results to return

        max_tempo (float): The max tempo of song results

        min_tempo (float): The min tempo of song results

        max_duration (float): The max duration of song results

        min_duration (float): The min duration of song results

        max_loudness (float): The max loudness of song results

        min_loudness (float): The min loudness of song results

        artist_max_familiarity (float): A float specifying the max familiarity of artists to search for

        artist_min_familiarity (float): A float specifying the min familiarity of artists to search for

        artist_max_hotttnesss (float): A float specifying the max hotttnesss of artists to search for

        artist_min_hotttnesss (float): A float specifying the max hotttnesss of artists to search for

        song_max_hotttnesss (float): A float specifying the max hotttnesss of songs to search for

        song_min_hotttnesss (float): A float specifying the max hotttnesss of songs to search for

        max_energy (float): The max energy of song results

        min_energy (float): The min energy of song results

        max_danceability (float): The max danceability of song results

        min_danceability (float): The min danceability of song results

        mode (int): 0 or 1 (minor or major)

        key (int): 0-11 (c, c-sharp, d, e-flat, e, f, f-sharp, g, a-flat, a, b-flat, b)

        max_latitude (float): A float specifying the max latitude of artists to search for

        min_latitude (float): A float specifying the min latitude of artists to search for

        max_longitude (float): A float specifying the max longitude of artists to search for

        min_longitude (float): A float specifying the min longitude of artists to search for

        adventurousness (float): A float ranging from 0 for old favorites to 1.0 for unheard music according to a seed_catalog

        sort (str): A string indicating an attribute and order for sorting the results

        buckets (list): A list of strings specifying which buckets to retrieve

        limit (bool): A boolean indicating whether or not to limit the results to one of the id spaces specified in buckets

        seed_catalog (str or Catalog): An Artist Catalog object or Artist Catalog id to use as a seed

        source_catalog (str or Catalog): A Catalog object or catalog id

        rank_type (str): A string denoting the desired ranking for description searches, either 'relevance' or 'familiarity'

        artist_start_year_before (int): Returned song's artists will have started recording music before this year.

        artist_start_year_after (int): Returned song's artists will have started recording music after this year.

        artist_end_year_before (int): Returned song's artists will have stopped recording music before this year.

        artist_end_year_after (int): Returned song's artists will have stopped recording music after this year.

        distribution (str): Affects the range of artists returned and how many songs each artist will have in the playlist relative to how similar they are to the seed. (wandering, focused)

        song_type (str):  A string or list of strings of the type of songs allowed.  The only valid song type at the moment is 'christmas'.
                          Valid formats are 'song_type', 'song_type:true', 'song_type:false', or 'song_type:any'.

    Returns:
        A list of Song objects

    Example:

    >>> p = playlist.static(type='artist-radio', artist=['ida maria', 'florence + the machine'])
    >>> p
    [<song - Pickpocket>,
     <song - Self-Taught Learner>,
     <song - Maps>,
     <song - Window Blues>,
     <song - That's Not My Name>,
     <song - My Lover Will Go>,
     <song - Home Sweet Home>,
     <song - Stella & God>,
     <song - Don't You Want To Share The Guilt?>,
     <song - Forget About It>,
     <song - Dull Life>,
     <song - This Trumpet In My Head>,
     <song - Keep Your Head>,
     <song - One More Time>,
     <song - Knights in Mountain Fox Jackets>]
    >>>

    """
    limit = str(limit).lower()

    if seed_catalog and isinstance(seed_catalog, catalog.Catalog):
        seed_catalog = seed_catalog.id

    if source_catalog and isinstance(source_catalog, catalog.Catalog):
        source_catalog = source_catalog.id
    dmca = str(dmca).lower()
    kwargs = locals()
    kwargs['bucket'] = kwargs['buckets'] or []
    del kwargs['buckets']
    kwargs['genre'] = kwargs['genres']
    del kwargs['genres']

    result = util.callm("%s/%s" % ('playlist', 'static'), kwargs)
    return [Song(**util.fix(s_dict)) for s_dict in result['response']['songs']]

Response: Returns a new playlist with the specified type and optional parameters.


Instruction:
Make a summary of the following Python 3 code
def _track_from_response(result, timeout):
    response = result['response']
    status = response['track']['status'].lower()

    if status == 'pending':
        # Need to wait for async upload or analyze call to finish.
        result = _wait_for_pending_track(response['track']['id'], timeout)
        response = result['response']
        status = response['track']['status'].lower()

    if not status == 'complete':
        track_id = response['track']['id']
        if status == 'pending':
            raise Exception('%s: the operation didn\'t complete before the timeout (%d secs)' %
                            (track_id, timeout))
        else:
            raise Exception('%s: there was an error analyzing the track, status: %s' % (track_id, status))
    else:
        # track_properties starts as the response dictionary.
        track_properties = response['track']
        # 'id' and 'md5' are separated to construct the Track object.
        identifier = track_properties.pop('id')
        md5        = track_properties.pop('md5', None) # tracks from song api calls will not have an md5
        # Pop off the audio_summary dict and make those keys attributes
        # of the Track. This includes things like tempo, energy, and loudness.
        track_properties.update(track_properties.pop('audio_summary'))
        return Track(identifier, md5, track_properties)

Response: This function creates a Track object from a response from a song api call.


Instruction:
Can you implement a function in Python 3 that
uploads audio file to a node.

Response:
def _upload(param_dict, timeout, data):
    """
    Calls upload either with a local audio file,
    or a url. Returns a track object.
    """
    param_dict['format'] = 'json'
    param_dict['wait'] = 'true'
    param_dict['bucket'] = 'audio_summary'
    result = util.callm('track/upload', param_dict, POST = True, socket_timeout = 300,  data = data)
    return _track_from_response(result, timeout)


Instruction:
Implement a function in Python 3 to
create a track object from a file - like object.

Response:
def track_from_file(file_object, filetype, timeout=DEFAULT_ASYNC_TIMEOUT, force_upload=False):
    """
    Create a track object from a file-like object.

    NOTE: Does not create the detailed analysis for the Track. Call
    Track.get_analysis() for that.

    Args:
        file_object: a file-like Python object
        filetype: the file type. Supported types include mp3, ogg, wav, m4a, mp4, au
        force_upload: skip the MD5 shortcut path, force an upload+analysis
    Example:
        >>> f = open("Miaow-01-Tempered-song.mp3")
        >>> t = track.track_from_file(f, 'mp3')
        >>> t
        < Track >
        >>>
    """
    if not force_upload:
        try:
            # Check if this file has already been uploaded.
            # This is much faster than uploading.
            md5 = hashlib.md5(file_object.read()).hexdigest()
            return track_from_md5(md5)
        except util.EchoNestAPIError:
            # Fall through to do a fresh upload.
            pass

    file_object.seek(0)
    return _track_from_data(file_object.read(), filetype, timeout)


Instruction:
Make a summary of the following Python 3 code
def track_from_filename(filename, filetype = None, timeout=DEFAULT_ASYNC_TIMEOUT, force_upload=False):
    filetype = filetype or filename.split('.')[-1]
    file_object = open(filename, 'rb')
    result = track_from_file(file_object, filetype, timeout, force_upload)
    file_object.close()
    return result

Response: Create a track object from a filename.


Instruction:
Write a Python 3 function that can
create a track object from a public URL.

Response:
def track_from_url(url, timeout=DEFAULT_ASYNC_TIMEOUT):
    """
    Create a track object from a public http URL.

    NOTE: Does not create the detailed analysis for the Track. Call
    Track.get_analysis() for that.

    Args:
        url: A string giving the URL to read from. This must be on a public machine accessible by HTTP.

    Example:
        >>> t = track.track_from_url("http://www.miaowmusic.com/mp3/Miaow-01-Tempered-song.mp3")
        >>> t
        < Track >
        >>>

    """
    param_dict = dict(url = url)
    return _upload(param_dict, timeout, data=None)


Instruction:
Explain what the following Python 3 code does
def track_from_id(identifier, timeout=DEFAULT_ASYNC_TIMEOUT):
    param_dict = dict(id = identifier)
    return _profile(param_dict, timeout)

Response: Create a track object from an Echo Nest track ID.


Instruction:
Can you generate the documentation for the following Python 3 function
def track_from_md5(md5, timeout=DEFAULT_ASYNC_TIMEOUT):
    param_dict = dict(md5 = md5)
    return _profile(param_dict, timeout)

Response: Create a track object from an md5 hash.


Instruction:
How would you explain what the following Python 3 function does
def get_analysis(self):
        if self.analysis_url:
            try:
                # Try the existing analysis_url first. This expires shortly
                # after creation.
                try:
                    json_string = urllib2.urlopen(self.analysis_url).read()
                except urllib2.HTTPError:
                    # Probably the analysis_url link has expired. Refresh it.
                    param_dict = dict(id = self.id)
                    new_track = _profile(param_dict, DEFAULT_ASYNC_TIMEOUT)
                    if new_track and new_track.analysis_url:
                        self.analysis_url = new_track.analysis_url
                        json_string = urllib2.urlopen(self.analysis_url).read()
                    else:
                        raise Exception("Failed to create track analysis.")

                analysis = json.loads(json_string)
                analysis_track = analysis.pop('track', {})
                self.__dict__.update(analysis)
                self.__dict__.update(analysis_track)
            except Exception: #pylint: disable=W0702
                # No detailed analysis found.
                raise Exception("Failed to create track analysis.")
        else:
            raise Exception("Failed to create track analysis.")

Response: Retrieve the detailed analysis for the track. Raises Exception if unable to create the detailed analysis.


Instruction:
How would you implement a function in Python 3 that
gets the tempo for a song

Response:
def get_tempo(artist, title):
    "gets the tempo for a song"
    results = song.search(artist=artist, title=title, results=1, buckets=['audio_summary'])
    if len(results) > 0:
        return results[0].audio_summary['tempo']
    else:
        return None


Instruction:
Explain what the following Python 3 code does
def list(sandbox_name, results=15, start=0):
    result = util.callm("%s/%s" % ('sandbox', 'list'), {'sandbox':sandbox_name, 'results': results, 'start': start})
    assets = result['response']['assets']
    start = result['response']['start']
    total = result['response']['total']

    return ResultList(assets, start, total)

Response: Returns a list of all assets available in this sandbox


Instruction:
Implement a Python 3 function for
searching for artists by name description style mood and start.

Response:
def search(name=None, description=None, style=None, mood=None, start=0, \
            results=15, buckets=None, limit=False, \
            fuzzy_match=False, sort=None, max_familiarity=None, min_familiarity=None, \
            max_hotttnesss=None, min_hotttnesss=None, test_new_things=None, rank_type=None, \
            artist_start_year_after=None, artist_start_year_before=None,artist_end_year_after=None,artist_end_year_before=None):
    """Search for artists by name, description, or constraint.

    Args:

    Kwargs:
        name (str): the name of an artist

        description (str): A string describing the artist

        style (str): A string describing the style/genre of the artist

        mood (str): A string describing the mood of the artist

        start (int): An integer starting value for the result set

        results (int): An integer number of results to return

        buckets (list): A list of strings specifying which buckets to retrieve

        limit (bool): A boolean indicating whether or not to limit the results to one of the id spaces specified in buckets

        fuzzy_match (bool): A boolean indicating whether or not to search for similar sounding matches (only works with name)

        max_familiarity (float): A float specifying the max familiarity of artists to search for

        min_familiarity (float): A float specifying the min familiarity of artists to search for

        max_hotttnesss (float): A float specifying the max hotttnesss of artists to search for

        min_hotttnesss (float): A float specifying the max hotttnesss of artists to search for

        artist_start_year_before (int): Returned artists will have started recording music before this year.

        artist_start_year_after (int): Returned artists will have started recording music after this year.

        artist_end_year_before (int): Returned artists will have stopped recording music before this year.

        artist_end_year_after (int): Returned artists will have stopped recording music after this year.

        rank_type (str): A string denoting the desired ranking for description searches, either 'relevance' or 'familiarity'

    Returns:
        A list of Artist objects

    Example:

    >>> results = artist.search(name='t-pain')
    >>> results
    [<artist - T-Pain>, <artist - T-Pain & Lil Wayne>, <artist - T Pain & 2 Pistols>, <artist - Roscoe Dash & T-Pain>, <artist - Tony Moxberg & T-Pain>, <artist - Flo-Rida (feat. T-Pain)>, <artist - Shortyo/Too Short/T-Pain>]
    >>>

    """
    limit = str(limit).lower()
    fuzzy_match = str(fuzzy_match).lower()
    kwargs = locals()
    kwargs['bucket'] = buckets or []
    del kwargs['buckets']
    """Search for artists"""
    result = util.callm("%s/%s" % ('artist', 'search'), kwargs)
    return [Artist(**util.fix(a_dict)) for a_dict in result['response']['artists']]


Instruction:
How would you explain what the following Python 3 function does
def top_hottt(start=0, results=15, buckets = None, limit=False):
    buckets = buckets or []
    kwargs = {}
    if start:
        kwargs['start'] = start
    if results:
        kwargs['results'] = results
    if buckets:
        kwargs['bucket'] = buckets
    if limit:
        kwargs['limit'] = 'true'

    """Get top hottt artists"""
    result = util.callm("%s/%s" % ('artist', 'top_hottt'), kwargs)
    return [Artist(**util.fix(a_dict)) for a_dict in result['response']['artists']]

Response: Return the top hottt artists in the specified buckets.


Instruction:
Make a summary of the following Python 3 code
def top_terms(results=15):

    kwargs = {}
    if results:
        kwargs['results'] = results

    """Get top terms"""
    result = util.callm("%s/%s" % ('artist', 'top_terms'), kwargs)
    return result['response']['terms']

Response: Get a list of the top overall terms of the current language.


Instruction:
Here you have a function in Python 3, explain what it does
def similar(names=None, ids=None, start=0, results=15, buckets=None, limit=False, max_familiarity=None, min_familiarity=None,
            max_hotttnesss=None, min_hotttnesss=None, seed_catalog=None,artist_start_year_before=None, \
            artist_start_year_after=None,artist_end_year_before=None,artist_end_year_after=None):
    """Return similar artists to this one

    Args:

    Kwargs:
        ids (str/list): An artist id or list of ids

        names (str/list): An artist name or list of names

        results (int): An integer number of results to return

        buckets (list): A list of strings specifying which buckets to retrieve

        limit (bool): A boolean indicating whether or not to limit the results to one of the id spaces specified in buckets

        start (int): An integer starting value for the result set

        max_familiarity (float): A float specifying the max familiarity of artists to search for

        min_familiarity (float): A float specifying the min familiarity of artists to search for

        max_hotttnesss (float): A float specifying the max hotttnesss of artists to search for

        min_hotttnesss (float): A float specifying the max hotttnesss of artists to search for

        seed_catalog (str): A string specifying the catalog similar artists are restricted to

    Returns:
        A list of similar Artist objects

    Example:

    >>> some_dudes = [artist.Artist('weezer'), artist.Artist('radiohead')]
    >>> some_dudes
    [<artist - Weezer>, <artist - Radiohead>]
    >>> sims = artist.similar(ids=[art.id for art in some_dudes], results=5)
    >>> sims
    [<artist - The Smashing Pumpkins>, <artist - Biffy Clyro>, <artist - Death Cab for Cutie>, <artist - Jimmy Eat World>, <artist - Nerf Herder>]
    >>>

    """

    buckets = buckets or []
    kwargs = {}

    if ids:
        if not isinstance(ids, list):
            ids = [ids]
        kwargs['id'] = ids
    if names:
        if not isinstance(names, list):
            names = [names]
        kwargs['name'] = names
    if max_familiarity is not None:
        kwargs['max_familiarity'] = max_familiarity
    if min_familiarity is not None:
        kwargs['min_familiarity'] = min_familiarity
    if max_hotttnesss is not None:
        kwargs['max_hotttnesss'] = max_hotttnesss
    if min_hotttnesss is not None:
        kwargs['min_hotttnesss'] = min_hotttnesss
    if seed_catalog is not None:
        kwargs['seed_catalog'] = seed_catalog
    if start:
        kwargs['start'] = start
    if results:
        kwargs['results'] = results
    if buckets:
        kwargs['bucket'] = buckets
    if limit:
        kwargs['limit'] = 'true'
    if artist_start_year_before:
        kwargs['artist_start_year_before'] = artist_start_year_before
    if artist_start_year_after:
        kwargs['artist_start_year_after'] = artist_start_year_after
    if artist_end_year_before:
        kwargs['artist_end_year_before'] = artist_end_year_before
    if artist_end_year_after:
        kwargs['artist_end_year_after'] = artist_end_year_after

    result = util.callm("%s/%s" % ('artist', 'similar'), kwargs)
    return [Artist(**util.fix(a_dict)) for a_dict in result['response']['artists']]

Response: Returns a list of similar artists to this one.


Instruction:
How would you code a function in Python 3 to
extract artists from a block of text.

Response:
def extract(text='', start=0, results=15, buckets=None, limit=False, max_familiarity=None, min_familiarity=None,
                max_hotttnesss=None, min_hotttnesss=None):
    """Extract artist names from a block of text.

    Args:

    Kwargs:
        text (str): The text to extract artists from

        start (int): An integer starting value for the result set

        results (int): An integer number of results to return

        buckets (list): A list of strings specifying which buckets to retrieve

        limit (bool): A boolean indicating whether or not to limit the results to one of the id spaces specified in buckets

        max_familiarity (float): A float specifying the max familiarity of artists to search for

        min_familiarity (float): A float specifying the min familiarity of artists to search for

        max_hotttnesss (float): A float specifying the max hotttnesss of artists to search for

        min_hotttnesss (float): A float specifying the max hotttnesss of artists to search for

    Returns:
        A list of Artist objects

    Example:

    >>> results = artist.extract(text='i saw beyonce at burger king, she was eatin, she was eatin')
    >>> results

    >>>

    """

    buckets = buckets or []
    kwargs = {}

    kwargs['text'] = text

    if max_familiarity is not None:
        kwargs['max_familiarity'] = max_familiarity
    if min_familiarity is not None:
        kwargs['min_familiarity'] = min_familiarity
    if max_hotttnesss is not None:
        kwargs['max_hotttnesss'] = max_hotttnesss
    if min_hotttnesss is not None:
        kwargs['min_hotttnesss'] = min_hotttnesss
    if start:
        kwargs['start'] = start
    if results:
        kwargs['results'] = results
    if buckets:
        kwargs['bucket'] = buckets
    if limit:
        kwargs['limit'] = 'true'

    result = util.callm("%s/%s" % ('artist', 'extract'), kwargs)

    return [Artist(**util.fix(a_dict)) for a_dict in result['response']['artists']]


Instruction:
Create a Python 3 function for
suggesting artists based upon partial names.

Response:
def suggest(q='', results=15, buckets=None, limit=False, max_familiarity=None, min_familiarity=None,
                max_hotttnesss=None, min_hotttnesss=None):
    """Suggest artists based upon partial names.

    Args:

    Kwargs:
        q (str): The text to suggest artists from

        results (int): An integer number of results to return

        buckets (list): A list of strings specifying which buckets to retrieve

        limit (bool): A boolean indicating whether or not to limit the results to one of the id spaces specified in buckets

        max_familiarity (float): A float specifying the max familiarity of artists to search for

        min_familiarity (float): A float specifying the min familiarity of artists to search for

        max_hotttnesss (float): A float specifying the max hotttnesss of artists to search for

        min_hotttnesss (float): A float specifying the max hotttnesss of artists to search for

    Returns:
        A list of Artist objects

    Example:

    >>> results = artist.suggest(text='rad')
    >>> results

    >>>

    """

    buckets = buckets or []
    kwargs = {}

    kwargs['q'] = q

    if max_familiarity is not None:
        kwargs['max_familiarity'] = max_familiarity
    if min_familiarity is not None:
        kwargs['min_familiarity'] = min_familiarity
    if max_hotttnesss is not None:
        kwargs['max_hotttnesss'] = max_hotttnesss
    if min_hotttnesss is not None:
        kwargs['min_hotttnesss'] = min_hotttnesss
    if results:
        kwargs['results'] = results
    if buckets:
        kwargs['bucket'] = buckets
    if limit:
        kwargs['limit'] = 'true'

    result = util.callm("%s/%s" % ('artist', 'suggest'), kwargs)

    return [Artist(**util.fix(a_dict)) for a_dict in result['response']['artists']]


Instruction:
Explain what the following Python 3 code does
def get_biographies(self, results=15, start=0, license=None, cache=True):
        if cache and ('biographies' in self.cache) and results==15 and start==0 and license==None:
            return self.cache['biographies']
        else:
            response = self.get_attribute('biographies', results=results, start=start, license=license)
            if results==15 and start==0 and license==None:
                self.cache['biographies'] = ResultList(response['biographies'], 0, response['total'])
            return ResultList(response['biographies'], start, response['total'])

Response: Get a list of artist biographies


Instruction:
Explain what the following Python 3 code does
def get_familiarity(self, cache=True):
        if not (cache and ('familiarity' in self.cache)):
            response = self.get_attribute('familiarity')
            self.cache['familiarity'] = response['artist']['familiarity']
        return self.cache['familiarity']

Response: Get our numerical estimation of how familiar an artist currently is to the world.


Instruction:
Write a Python 3 script for
getting the foreign id for this artist for a specific id space.

Response:
def get_foreign_id(self, idspace='musicbrainz', cache=True):
        """Get the foreign id for this artist for a specific id space

        Args:

        Kwargs:
            idspace (str): A string indicating the idspace to fetch a foreign id for.

        Returns:
            A foreign ID string

        Example:

        >>> a = artist.Artist('fabulous')
        >>> a.get_foreign_id('7digital')
        u'7digital:artist:186042'
        >>>
        """
        if not (cache and ('foreign_ids' in self.cache) and filter(lambda d: d.get('catalog') == idspace, self.cache['foreign_ids'])):
            response = self.get_attribute('profile', bucket=['id:'+idspace])
            foreign_ids = response['artist'].get("foreign_ids", [])
            self.cache['foreign_ids'] = self.cache.get('foreign_ids', []) + foreign_ids
        cval = filter(lambda d: d.get('catalog') == util.map_idspace(idspace),
                      self.cache.get('foreign_ids'))
        return cval[0].get('foreign_id') if cval else None


Instruction:
Make a summary of the following Python 3 code
def get_twitter_id(self, cache=True):
        if not (cache and ('twitter' in self.cache)):
            response = self.get_attribute('twitter')
            self.cache['twitter'] = response['artist'].get('twitter')
        return self.cache['twitter']

Response: Get the twitter id for this artist if it exists in the cache.


Instruction:
Can you tell what is the following Python 3 function doing
def get_hotttnesss(self, cache=True):
        if not (cache and ('hotttnesss' in self.cache)):
            response = self.get_attribute('hotttnesss')
            self.cache['hotttnesss'] = response['artist']['hotttnesss']
        return self.cache['hotttnesss']

Response: Get our numerical description of how hottt an artist currently is.


Instruction:
Implement a function in Python 3 to
get a list of artist images in a specific language.

Response:
def get_images(self, results=15, start=0, license=None, cache=True):
        """Get a list of artist images

        Args:
            cache (bool): A boolean indicating whether or not the cached value should be used (if available). Defaults to True.

            results (int): An integer number of results to return

            start (int): An integer starting value for the result set

            license (str): A string specifying the desired license type

        Returns:
            A list of image document dicts; list contains additional attributes 'start' and 'total'

        Example:

        >>> a = artist.Artist('Captain Beefheart')
        >>> images = a.get_images(results=1)
        >>> images.total
        49
        >>> images[0]['url']
        u'http://c4.ac-images.myspacecdn.com/images01/5/l_e1a329cdfdb16a848288edc6d578730f.jpg'
        >>>
        """

        if cache and ('images' in self.cache) and results==15 and start==0 and license==None:
            return self.cache['images']
        else:
            response = self.get_attribute('images', results=results, start=start, license=license)
            total = response.get('total') or 0
            if results==15 and start==0 and license==None:
                self.cache['images'] = ResultList(response['images'], 0, total)
            return ResultList(response['images'], start, total)


Instruction:
How would you implement a function in Python 3 that
gets a list of news articles on the web related to an artist.

Response:
def get_news(self, results=15, start=0, cache=True, high_relevance=False):
        """Get a list of news articles found on the web related to an artist

        Args:
            cache (bool): A boolean indicating whether or not the cached value should be used (if available). Defaults to True.

            results (int): An integer number of results to return

            start (int): An integer starting value for the result set

        Returns:
            A list of news document dicts; list contains additional attributes 'start' and 'total'

        Example:

        >>> a = artist.Artist('Henry Threadgill')
        >>> news = a.news
        >>> news.total
        41
        >>> news[0]['name']
        u'Jazz Journalists Association Announces 2010 Jazz Award Winners'
        >>>
        """
        if cache and ('news' in self.cache) and results==15 and start==0 and not high_relevance:
            return self.cache['news']
        else:
            high_relevance = 'true' if high_relevance else 'false'
            response = self.get_attribute('news', results=results, start=start, high_relevance=high_relevance)
            if results==15 and start==0:
                self.cache['news'] = ResultList(response['news'], 0, response['total'])
            return ResultList(response['news'], start, response['total'])


Instruction:
Create a Python 3 function to
return a list of similar Artist objects for this one.

Response:
def get_similar(self, results=15, start=0, buckets=None, limit=False, cache=True, max_familiarity=None, min_familiarity=None, \
                    max_hotttnesss=None, min_hotttnesss=None, min_results=None, reverse=False, artist_start_year_before=None, \
                    artist_start_year_after=None,artist_end_year_before=None,artist_end_year_after=None):
        """Return similar artists to this one

        Args:

        Kwargs:
            cache (bool): A boolean indicating whether or not the cached value should be used (if available). Defaults to True.

            results (int): An integer number of results to return

            start (int): An integer starting value for the result set

            max_familiarity (float): A float specifying the max familiarity of artists to search for

            min_familiarity (float): A float specifying the min familiarity of artists to search for

            max_hotttnesss (float): A float specifying the max hotttnesss of artists to search for

            min_hotttnesss (float): A float specifying the max hotttnesss of artists to search for

            reverse (bool): A boolean indicating whether or not to return dissimilar artists (wrecommender). Defaults to False.

        Returns:
            A list of similar Artist objects

        Example:

        >>> a = artist.Artist('Sleater Kinney')
        >>> similars = a.similar[:5]
        >>> similars
        [<artist - Bikini Kill>, <artist - Pretty Girls Make Graves>, <artist - Huggy Bear>, <artist - Bratmobile>, <artist - Team Dresch>]
        >>>
        """
        buckets = buckets or []
        kwargs = {}
        if max_familiarity:
            kwargs['max_familiarity'] = max_familiarity
        if min_familiarity:
            kwargs['min_familiarity'] = min_familiarity
        if max_hotttnesss:
            kwargs['max_hotttnesss'] = max_hotttnesss
        if min_hotttnesss:
            kwargs['min_hotttnesss'] = min_hotttnesss
        if min_results:
            kwargs['min_results'] = min_results
        if buckets:
            kwargs['bucket'] = buckets
        if limit:
            kwargs['limit'] = 'true'
        if reverse:
            kwargs['reverse'] = 'true'
        if artist_start_year_before:
            kwargs['artist_start_year_before'] = artist_start_year_before
        if artist_start_year_after:
            kwargs['artist_start_year_after'] = artist_start_year_after
        if artist_end_year_before:
            kwargs['artist_end_year_before'] = artist_end_year_before
        if artist_end_year_after:
            kwargs['artist_end_year_after'] = artist_end_year_after

        if cache and ('similar' in self.cache) and results==15 and start==0 and (not kwargs):
            return [Artist(**util.fix(a)) for a in self.cache['similar']]
        else:
            response = self.get_attribute('similar', results=results, start=start, **kwargs)
            if results==15 and start==0 and (not kwargs):
                self.cache['similar'] = response['artists']
            return [Artist(**util.fix(a)) for a in response['artists']]


Instruction:
Can you write a function in Python 3 where it
gets the songs associated with an artist.

Response:
def get_songs(self, cache=True, results=15, start=0):
        """Get the songs associated with an artist

        Args:

        Kwargs:
            cache (bool): A boolean indicating whether or not the cached value should be used (if available). Defaults to True.

            results (int): An integer number of results to return

            start (int): An integer starting value for the result set

        Results:
            A list of Song objects; list contains additional attributes 'start' and 'total'

        Example:

        >>> a = artist.Artist('Strokes')
        >>> a.get_songs(results=5)
        [<song - Fear Of Sleep>, <song - Red Light>, <song - Ize Of The World>, <song - Evening Sun>, <song - Juicebox>]
        >>>
        """

        if cache and ('songs' in self.cache) and results==15 and start==0:
            if not isinstance(self.cache['songs'][0], Song):
                song_objects = []
                for s in self.cache["songs"]:
                    song_objects.append(Song(id=s['id'],
                                             title=s['title'],
                                             artist_name=self.name,
                                             artist_id=self.id))
                self.cache['songs'] = song_objects
            return self.cache['songs']
        else:
            response = self.get_attribute('songs', results=results, start=start)
            for s in response['songs']:
                s.update({'artist_id':self.id, 'artist_name':self.name})
            songs = [Song(**util.fix(s)) for s in response['songs']]
            if results==15 and start==0:
                self.cache['songs'] = ResultList(songs, 0, response['total'])
            return ResultList(songs, start, response['total'])


Instruction:
Can you implement a function in Python 3 that
returns a list of term documents associated with an artist.

Response:
def get_terms(self, sort='weight', cache=True):
        """Get the terms associated with an artist

        Args:

        Kwargs:
            cache (bool): A boolean indicating whether or not the cached value should be used (if available). Defaults to True.

            sort (str): A string specifying the desired sorting type (weight or frequency)

        Results:
            A list of term document dicts

        Example:

        >>> a = artist.Artist('tom petty')
        >>> a.terms
        [{u'frequency': 1.0, u'name': u'heartland rock', u'weight': 1.0},
         {u'frequency': 0.88569401860168606,
          u'name': u'jam band',
          u'weight': 0.9116501862732439},
         {u'frequency': 0.9656145118557401,
          u'name': u'pop rock',
          u'weight': 0.89777934440040685},
         {u'frequency': 0.8414744288140491,
          u'name': u'southern rock',
          u'weight': 0.8698567153186606},
         {u'frequency': 0.9656145118557401,
          u'name': u'hard rock',
          u'weight': 0.85738022655218893},
         {u'frequency': 0.88569401860168606,
          u'name': u'singer-songwriter',
          u'weight': 0.77427243392312772},
         {u'frequency': 0.88569401860168606,
          u'name': u'rock',
          u'weight': 0.71158718989399083},
         {u'frequency': 0.60874110500110956,
          u'name': u'album rock',
          u'weight': 0.69758668733499629},
         {u'frequency': 0.74350792060935744,
          u'name': u'psychedelic',
          u'weight': 0.68457367494207944},
         {u'frequency': 0.77213698386292873,
          u'name': u'pop',
          u'weight': 0.65039556639337293},
         {u'frequency': 0.41747136183050298,
          u'name': u'bar band',
          u'weight': 0.54974975024767025}]
        >>>

        """
        if cache and ('terms' in self.cache) and sort=='weight':
            return self.cache['terms']
        else:
            response = self.get_attribute('terms', sort=sort)
            if sort=='weight':
                self.cache['terms'] = response['terms']
            return response['terms']


Instruction:
Can you create a Python 3 function that
gets the urls for an artist and return the dict containing the url

Response:
def get_urls(self, cache=True):
        """Get the urls for an artist

        Args:

        Kwargs:
            cache (bool): A boolean indicating whether or not the cached value should be used (if available). Defaults to True.

        Results:
            A url document dict

        Example:

        >>> a = artist.Artist('the unicorns')
        >>> a.get_urls()
        {u'amazon_url': u'http://www.amazon.com/gp/search?ie=UTF8&keywords=The Unicorns&tag=httpechonecom-20&index=music',
         u'aolmusic_url': u'http://music.aol.com/artist/the-unicorns',
         u'itunes_url': u'http://itunes.com/TheUnicorns',
         u'lastfm_url': u'http://www.last.fm/music/The+Unicorns',
         u'mb_url': u'http://musicbrainz.org/artist/603c5f9f-492a-4f21-9d6f-1642a5dbea2d.html',
         u'myspace_url': u'http://www.myspace.com/iwasbornunicorn'}
        >>>

        """
        if not (cache and ('urls' in self.cache)):
            response = self.get_attribute('urls')
            self.cache['urls'] = response['urls']
        return self.cache['urls']


Instruction:
How would you code a function in Python 3 to
get a list of video documents on the web related to an artist.

Response:
def get_video(self, results=15, start=0, cache=True):
        """Get a list of video documents found on the web related to an artist

        Args:

        Kwargs:
            cache (bool): A boolean indicating whether or not the cached value should be used (if available). Defaults to True.

            results (int): An integer number of results to return

            start (int): An integer starting value for the result set

        Returns:
            A list of video document dicts; list contains additional attributes 'start' and 'total'

        Example:

        >>> a = artist.Artist('the vapors')
        >>> a.get_video(results=1, start=2)
        [{u'date_found': u'2009-12-28T08:27:48',
          u'id': u'd02f9e6dc7904f70402d4676516286b9',
          u'image_url': u'http://i1.ytimg.com/vi/p6c0wOFL3Us/default.jpg',
          u'site': u'youtube',
          u'title': u'The Vapors-Turning Japanese (rectangular white vinyl promo)',
          u'url': u'http://youtube.com/watch?v=p6c0wOFL3Us'}]
        >>>

        """
        if cache and ('video' in self.cache) and results==15 and start==0:
            return self.cache['video']
        else:
            response = self.get_attribute('video', results=results, start=start)
            if results==15 and start==0:
                self.cache['video'] = ResultList(response['video'], 0, response['total'])
            return ResultList(response['video'], start, response['total'])


Instruction:
Implement a Python 3 function for
getting a list of years active dictionaries for an artist.

Response:
def get_years_active(self, cache=True):
        """Get a list of years active dictionaries for an artist

        Args:

        Kwargs:
            cache (bool): A boolean indicating whether or not the cached value should be used (if available). Defaults to True.

        Returns:
            A list of years active dictionaries; list contains additional attributes 'start' and 'total'

        Example:

        >>> a = artist.Artist('yelle')
        >>> a.get_years_active()
        [{ start: 2005 }]
        >>>

        """
        if cache and ('years_active' in self.cache):
            return self.cache['years_active']
        else:
            response = self.get_attribute('profile', bucket=['years_active'])
            self.cache['years_active'] = response['artist']['years_active']
            return response['artist']['years_active']


Instruction:
Create a Python 3 function for
getting the number of related documents of various types for the artist.

Response:
def get_doc_counts(self, cache=True):
        """
        Get the number of related documents of various types for the artist.
        The types include audio, biographies, blogs, images, news, reviews, songs, videos.

        Note that these documents can be retrieved by calling artist.<document type>, for example,
        artist.biographies.

        Args:

        Kwargs:
            cache (bool): A boolean indicating whether or not the cached value should be used (if available).
            Defaults to True.

        Returns:
            A dictionary with one key for each document type, mapped to an integer count of documents.

        Example:

        >>> a = artist.Artist("The Kinks")

        >>> a.get_doc_counts()
        {u'audio': 194,
         u'biographies': 9,
         u'blogs': 379,
         u'images': 177,
         u'news': 84,
         u'reviews': 110,
         u'songs': 499,
         u'videos': 340}
         >>>
        """
        if not cache or not ('doc_counts' in self.cache):
            response = self.get_attribute("profile", bucket='doc_counts')
            self.cache['doc_counts'] = response['artist']['doc_counts']
        return self.cache['doc_counts']


Instruction:
How would you implement a function in Python 3 that
wraps for the _run method of the base class

Response:
def run(self, bundle,
              container_id=None,
              log_path=None,
              pid_file=None,
              log_format="kubernetes"):

    ''' run is a wrapper to create, start, attach, and delete a container.

        Equivalent command line example:
          singularity oci run -b ~/bundle mycontainer

        Parameters
        ==========
        bundle: the full path to the bundle folder
        container_id: an optional container_id. If not provided, use same
                      container_id used to generate OciImage instance
        log_path: the path to store the log.
        pid_file: specify the pid file path to use
        log_format: defaults to kubernetes. Can also be "basic" or "json"
    '''
    return self._run(bundle,
                     container_id=container_id,
                     log_path=log_path,
                     pid_file=pid_file,
                     command="run",
                     log_format=log_format)


Instruction:
Create a Python 3 function for
creating a container from a bundle

Response:
def create(self, bundle,
                 container_id=None,
                 empty_process=False,
                 log_path=None,
                 pid_file=None,
                 sync_socket=None,
                 log_format="kubernetes"):

    ''' use the client to create a container from a bundle directory. The bundle
        directory should have a config.json. You must be the root user to
        create a runtime.

        Equivalent command line example:
           singularity oci create [create options...] <container_ID>

        Parameters
        ==========
        bundle: the full path to the bundle folder
        container_id: an optional container_id. If not provided, use same
                      container_id used to generate OciImage instance
        empty_process: run container without executing container process (for
                       example, for a pod container waiting for signals). This
                       is a specific use case for tools like Kubernetes
        log_path: the path to store the log.
        pid_file: specify the pid file path to use
        sync_socket: the path to the unix socket for state synchronization.
        log_format: defaults to kubernetes. Can also be "basic" or "json"
    '''
    return self._run(bundle,
                     container_id=container_id,
                     empty_process=empty_process,
                     log_path=log_path,
                     pid_file=pid_file,
                     sync_socket=sync_socket,
                     command="create",
                     log_format=log_format)


Instruction:
Implement a function in Python 3 to
delete an instance based on container_id

Response:
def delete(self, container_id=None, sudo=None):
    '''delete an instance based on container_id.

       Parameters
       ==========
       container_id: the container_id to delete
       sudo: whether to issue the command with sudo (or not)
             a container started with sudo will belong to the root user
             If started by a user, the user needs to control deleting it
             if the user doesn't set to True/False, we use client self.sudo

       Returns
       =======
       return_code: the return code from the delete command. 0 indicates a
                    successful delete, 255 indicates not.
    '''
    sudo = self._get_sudo(sudo)
    container_id = self.get_container_id(container_id)

    # singularity oci delete
    cmd = self._init_command('delete')

    # Add the container_id
    cmd.append(container_id)

    # Delete the container, return code goes to user (message to screen)
    return self._run_and_return(cmd, sudo=sudo)


Instruction:
Can you tell what is the following Python 3 function doing
def attach(self, container_id=None, sudo=False):
    '''attach to a container instance based on container_id

       Parameters
       ==========
       container_id: the container_id to delete
       sudo: whether to issue the command with sudo (or not)
             a container started with sudo will belong to the root user
             If started by a user, the user needs to control deleting it

       Returns
       =======
       return_code: the return code from the delete command. 0 indicates a
                    successful delete, 255 indicates not.
    '''
    sudo = self._get_sudo(sudo)
    container_id = self.get_container_id(container_id)

    # singularity oci delete
    cmd = self._init_command('attach')

    # Add the container_id
    cmd.append(container_id)

    # Delete the container, return code goes to user (message to screen)
    return self._run_and_return(cmd, sudo)

Response: attach to a container instance based on container_id


Instruction:
Make a summary of the following Python 3 code
def execute(self, command=None, container_id=None, sudo=False, stream=False):
    '''execute a command to a container instance based on container_id

       Parameters
       ==========
       container_id: the container_id to delete
       command: the command to execute to the container
       sudo: whether to issue the command with sudo (or not)
             a container started with sudo will belong to the root user
             If started by a user, the user needs to control deleting it
       stream: if True, return an iterate to iterate over results of exec.
               default is False, will return full output as string.

       Returns
       =======
       return_code: the return code from the delete command. 0 indicates a
                    successful delete, 255 indicates not.
    '''
    sudo = self._get_sudo(sudo)
    container_id = self.get_container_id(container_id)

    # singularity oci delete
    cmd = self._init_command('exec')

    # Add the container_id
    cmd.append(container_id)

    if command != None:
        if not isinstance(command, list):
            command = [command]

        cmd = cmd + command

        # Execute the command, return response to user
        if stream:
            return stream_command(cmd, sudo=sudo)
        return self._run_command(cmd, sudo=sudo, quiet=True)

Response: execute a command to a container instance based on container_id


Instruction:
Can you generate a brief explanation for the following Python 3 code
def update(self, container_id, from_file=None):
    '''update container cgroup resources for a specific container_id,
       The container must have state "running" or "created."

       Singularity Example:
           singularity oci update [update options...] <container_ID>
           singularity oci update --from-file cgroups-update.json mycontainer

       Parameters
       ==========
       container_id: the container_id to update cgroups for
       from_file: a path to an OCI JSON resource file to update from.
    '''
    sudo = self._get_sudo(sudo)
    container_id = self.get_container_id(container_id)

    # singularity oci delete
    cmd = self._init_command('update')

    if from_file != None:
        cmd = cmd + ['--from-file', from_file]

    # Add the container_id
    cmd.append(container_id)

    # Delete the container, return code goes to user (message to screen)
    return self._run_and_return(cmd, sudo)

Response: update container cgroup resources for a specific container_id


Instruction:
Can you tell what is the following Python 3 function doing
def get_client(quiet=False, debug=False):
    '''
       get the client and perform imports not on init, in case there are any
       initialization or import errors.

       Parameters
       ==========
       quiet: if True, suppress most output about the client
       debug: turn on debugging mode

    '''
    from spython.utils import get_singularity_version
    from .base import Client

    Client.quiet = quiet
    Client.debug = debug

    # Do imports here, can be customized
    from .apps import apps
    from .build import build
    from .execute import execute
    from .help import help
    from .inspect import inspect
    from .instances import ( instances, stopall ) # global instance commands
    from .run import run
    from .pull import pull

    # Actions
    Client.apps = apps
    Client.build = build
    Client.execute = execute
    Client.help = help
    Client.inspect = inspect
    Client.instances = instances
    Client.run = run
    Client.pull = pull

    # Command Groups, Images
    from spython.image.cmd import generate_image_commands  # deprecated
    Client.image = generate_image_commands()

    # Commands Groups, Instances
    from spython.instance.cmd import generate_instance_commands  # instance level commands
    Client.instance = generate_instance_commands()
    Client.instance_stopall = stopall
    Client.instance.version = Client.version

    # Commands Groups, OCI (Singularity version 3 and up)
    if "version 3" in get_singularity_version():
        from spython.oci.cmd import generate_oci_commands
        Client.oci = generate_oci_commands()()  # first () runs function, second
                                                # initializes OciImage class
        Client.oci.debug = Client.debug
        Client.oci.quiet = Client.quiet
        Client.oci.OciImage.quiet = Client.quiet
        Client.oci.OciImage.debug = Client.debug

    # Initialize
    cli = Client()

    # Pass on verbosity
    cli.image.debug = cli.debug
    cli.image.quiet = cli.quiet
    cli.instance.debug = cli.debug
    cli.instance.quiet = cli.quiet

    return cli

Response: get the client and perform imports not on init


Instruction:
How would you explain what the following Python 3 function does
def build(self, recipe=None,
                image=None,
                isolated=False,
                sandbox=False,
                writable=False,
                build_folder=None,
                robot_name=False,
                ext='simg',
                sudo=True,
                stream=False):

    '''build a singularity image, optionally for an isolated build
       (requires sudo). If you specify to stream, expect the image name
       and an iterator to be returned.

       image, builder = Client.build(...)

       Parameters
       ==========

       recipe: the path to the recipe file (or source to build from). If not
                  defined, we look for "Singularity" file in $PWD
       image: the image to build (if None, will use arbitary name
       isolated: if True, run build with --isolated flag
       sandbox: if True, create a writable sandbox
       writable: if True, use writable ext3 (sandbox takes preference)
       build_folder: where the container should be built.
       ext: the image extension to use.
       robot_name: boolean, default False. if you don't give your image a
                   name (with "image") then a fun robot name will be generated
                   instead. Highly recommended :)
       sudo: give sudo to the command (or not) default is True for build

    '''
    from spython.utils import check_install
    check_install()

    cmd = self._init_command('build')

    if 'version 3' in self.version():
        ext = 'sif'

    # No image provided, default to use the client's loaded image
    if recipe is None:
        recipe = self._get_uri()

    # If it's still None, try default build recipe
    if recipe is None:
        recipe = 'Singularity'

        if not os.path.exists(recipe):
            bot.exit('Cannot find %s, exiting.' %image)

    if image is None:
        if re.search('(docker|shub)://', recipe) and robot_name is False:
            image = self._get_filename(recipe, ext)
        else:
            image = "%s.%s" %(self.RobotNamer.generate(), ext)

    # Does the user want a custom build folder?
    if build_folder is not None:
        if not os.path.exists(build_folder):
            bot.exit('%s does not exist!' % build_folder)
        image = os.path.join(build_folder, image)

    # The user wants to run an isolated build
    if isolated is True:
        cmd.append('--isolated')

    if sandbox is True:
        cmd.append('--sandbox')
    elif sandbox is True:
        cmd.append('--writable')

    cmd = cmd + [image, recipe]

    if stream is False:
        output = self._run_command(cmd, sudo=sudo, capture=False)
    else:
        # Here we return the expected image, and an iterator!
        # The caller must iterate over
        return image, stream_command(cmd, sudo=sudo)

    if os.path.exists(image):
        return image

Response: build a singularity image


Instruction:
Can you implement a function in Python 3 that
starts an instance. This is done by default when an instance is created.

Response:
def start(self, image=None, name=None, args=None, sudo=False, options=[], capture=False):
    '''start an instance. This is done by default when an instance is created.

       Parameters
       ==========
       image: optionally, an image uri (if called as a command from Client)
       name: a name for the instance
       sudo: if the user wants to run the command with sudo
       capture: capture output, default is False. With True likely to hang.
       args: arguments to provide to the instance (supported Singularity 3.1+)
       options: a list of tuples, each an option to give to the start command
                [("--bind", "/tmp"),...]

       USAGE:
       singularity [...] instance.start [...] <container path> <instance name>

    '''
    from spython.utils import ( run_command,
                                check_install )
    check_install()

    # If name provided, over write robot (default)
    if name != None:
        self.name = name

    # If an image isn't provided, we have an initialized instance
    if image is None:

        # Not having this means it was called as a command, without an image
        if not hasattr(self, "_image"):
            bot.exit('Please provide an image, or create an Instance first.')

        image = self._image

    # Derive subgroup command based on singularity version
    subgroup = 'instance.start'
    if 'version 3' in self.version():
        subgroup = ["instance", "start"]

    cmd = self._init_command(subgroup)

    # Add options, if they are provided
    if not isinstance(options, list):
        options = options.split(' ')

    # Assemble the command!
    cmd = cmd + options + [image, self.name]

    # If arguments are provided
    if args != None:
        if not isinstance(args, list):
            args = [args]
        cmd = cmd + args

    # Save the options and cmd, if the user wants to see them later
    self.options = options
    self.args = args
    self.cmd = cmd

    output = run_command(cmd, sudo=sudo, quiet=True, capture=capture)

    if output['return_code'] == 0:
        self._update_metadata()

    else:
        message = '%s : return code %s' %(output['message'],
                                          output['return_code'])
        bot.error(message)

    return self


Instruction:
Can you create a Python 3 function that
imports will import the image to the image_path

Response:
def importcmd(self, image_path, input_source):
    '''import will import (stdin) to the image

       Parameters
       ==========
       image_path: path to image to import to.
       input_source: input source or file
       import_type: if not specified, imports whatever function is given

    '''
    from spython.utils import check_install
    check_install()

    cmd = ['singularity', 'image.import', image_path, input_source]
    output = self.run_command(cmd, sudo=False)
    self.println(output)
    return image_path


Instruction:
Explain what the following Python 3 code does
def inspect(self, image=None, json=True, app=None, quiet=True):
    '''inspect will show labels, defile, runscript, and tests for an image

       Parameters
       ==========
       image: path of image to inspect
       json: print json instead of raw text (default True)
       quiet: Don't print result to the screen (default True)
       app: if defined, return help in context of an app

    '''
    check_install()

    # No image provided, default to use the client's loaded image
    if image is None:
        image = self._get_uri()

    cmd = self._init_command('inspect')
    if app is not None:
        cmd = cmd + ['--app', app]

    options = ['e','d','l','r','hf','t']

    # After Singularity 3.0, helpfile was changed to H from

    if "version 3" in self.version():
        options = ['e','d','l','r','H','t']

    [cmd.append('-%s' % x) for x in options]

    if json is True:
        cmd.append('--json')

    cmd.append(image)
    result = run_command(cmd, quiet=False)

    if result['return_code'] == 0:
        result = jsonp.loads(result['message'][0])

        # Fix up labels
        labels = parse_labels(result)

        if not quiet:
            print(jsonp.dumps(result, indent=4))

    return result

Response: inspect will show labels defile runscript and tests for an image


Instruction:
How would you explain what the following Python 3 function does
def parse_labels(result):
    '''fix up the labels, meaning parse to json if needed, and return
       original updated object

       Parameters
       ==========
       result: the json object to parse from inspect
    '''

    if "data" in result:
        labels = result['data']['attributes'].get('labels') or {}

    elif 'attributes' in result:
        labels = result['attributes'].get('labels') or {}

    # If labels included, try parsing to json

    try:
        labels = jsonp.loads(labels)
    except:
        pass

    if "data" in result:
        result['data']['attributes']['labels'] = labels
    else:
        result['attributes']['labels'] = labels

    return result

Response:
fix up the labels meaning parse to json if needed and return the original updated object
       Parameters ==========
       result - the json object to parse from inspect


Instruction:
Write a Python 3 script to
give the user an ipython shell

Response:
def ipython(image):
    '''give the user an ipython shell
    '''

    # The client will announce itself (backend/database) unless it's get
    from spython.main import get_client
    from spython.main.parse import ( DockerRecipe, SingularityRecipe )

    client = get_client()
    client.load(image)

    # Add recipe parsers
    client.DockerRecipe = DockerRecipe
    client.SingularityRecipe = SingularityRecipe

    from IPython import embed
    embed()


Instruction:
Explain what the following Python 3 code does
def _setup(self, lines):
        '''setup required adding content from the host to the rootfs,
           so we try to capture with with ADD.
        '''
        bot.warning('SETUP is error prone, please check output.')

        for line in lines:

            # For all lines, replace rootfs with actual root /
            line = re.sub('[$]{?SINGULARITY_ROOTFS}?',
                          '', '$SINGULARITY_ROOTFS')

            # If we have nothing left, don't continue
            if line in ['', None]:
                continue

            # If the line starts with copy or move, assume is file from host
            if re.search('(^cp|^mv)', line):
                line = re.sub('(^cp|^mv)', '', line)
                self.files.append(line)

            # If it's a general command, add to install routine
            else:
                self.install.append(line)

Response: setup required adding content from the host to the rootfs so we try to capture with ADD.


Instruction:
Can you tell what is the following Python 3 function doing
def _from(self, line):
        ''' get the FROM container image name from a FROM line!

           Parameters
           ==========
           line: the line from the recipe file to parse for FROM

        '''
        self.fromHeader = line
        bot.debug('FROM %s' %self.fromHeader)

Response: get the FROM container image name from a FROM line!


Instruction:
Here you have a function in Python 3, explain what it does
def _env(self, lines):
        '''env will parse a list of environment lines and simply remove any
           blank lines, or those with export. Dockerfiles don't usually
           have exports.

           Parameters
           ==========
           lines: A list of environment pair lines.

        '''
        environ = [x for x in lines if not x.startswith('export')]
        self.environ += environ

Response:
This method will parse a list of environment lines and simply add any
           blank lines to the environment.


Instruction:
Make a summary of the following Python 3 code
def _comments(self, lines):
         ''' comments is a wrapper for comment, intended to be given a list
             of comments.

             Parameters
             ==========
             lines: the list of lines to parse

         '''
         for line in lines:
             comment = self._comment(line)
             self.comments.append(comment)

Response: comments is a wrapper for comment


Instruction:
Can you tell what is the following Python 3 function doing
def _run(self, lines):
        '''_parse the runscript to be the Docker CMD. If we have one line,
           call it directly. If not, write the entrypoint into a script.

           Parameters
           ==========
           lines: the line from the recipe file to parse for CMD

        '''
        lines = [x for x in lines if x not in ['', None]]

        # Default runscript is first index
        runscript = lines[0]

        # Multiple line runscript needs multiple lines written to script
        if len(lines) > 1:

            bot.warning('More than one line detected for runscript!')
            bot.warning('These will be echoed into a single script to call.')
            self._write_script('/entrypoint.sh', lines)
            runscript = "/bin/bash /entrypoint.sh"

        self.cmd = runscript

Response: _parse the runscript to be the Docker CMD.


Instruction:
Write a Python 3 script for
mapping will take the section name from a Singularity recipe and return a map function to add it to the appropriate place. Any lines that don't cleanly map are assumed to be comments. Parameters ========== section: the name of the Singularity recipe section Returns ======= function: to map a line to its command group (e.g., install)

Response:
def _get_mapping(self, section):
        '''mapping will take the section name from a Singularity recipe
           and return a map function to add it to the appropriate place.
           Any lines that don't cleanly map are assumed to be comments.

           Parameters
           ==========
           section: the name of the Singularity recipe section

           Returns
           =======
           function: to map a line to its command group (e.g., install)

        '''

        # Ensure section is lowercase
        section = section.lower()

        mapping = {"environment": self._env,
                   "comments": self._comments,
                   "runscript": self._run,
                   "labels": self._labels,
                   "setup": self._setup,
                   "files": self._files,
                   "from": self._from,
                   "post": self._post,
                   "test": self._test,
                   "help": self._comments}

        if section in mapping:
            return mapping[section]
        return self._comments


Instruction:
Can you create a Python 3 function that
parses is the base function for parsing the recipe and extracting the correct data structures.

Response:
def _parse(self):
        '''parse is the base function for parsing the recipe, and extracting
           elements into the correct data structures. Everything is parsed into
           lists or dictionaries that can be assembled again on demand.

           Singularity: we parse files/labels first, then install.
                        cd first in a line is parsed as WORKDIR

        '''
        # If the recipe isn't loaded, load it
        if not hasattr(self, 'config'):
            self.load_recipe()

        # Parse each section
        for section, lines in self.config.items():
            bot.debug(section)

            # Get the correct parsing function
            parser = self._get_mapping(section)

            # Parse it, if appropriate
            if parser:
                parser(lines)


Instruction:
How would you code a function in Python 3 to
load the From section of the Dockerfile.

Response:
def _load_from(self, line):
        '''load the From section of the recipe for the Dockerfile.
        '''
        # Remove any comments
        line = line.split('#',1)[0]
        line = re.sub('(F|f)(R|r)(O|o)(M|m):','', line).strip()
        bot.info('FROM %s' %line)
        self.config['from'] = line


Instruction:
How would you implement a function in Python 3 that
reads in a section to a list and stop when we hit the next section

Response:
def _load_section(self, lines, section):
        '''read in a section to a list, and stop when we hit the next section
        '''
        members = []

        while True:

            if len(lines) == 0:
                break
            next_line = lines[0]

            # The end of a section
            if next_line.strip().startswith("%"):
                break

            # Still in current section!
            else:
                new_member = lines.pop(0).strip()
                if new_member not in ['', None]:
                    members.append(new_member)

        # Add the list to the config
        if len(members) > 0:
            if section is not None:
                self.config[section] += members


Instruction:
Explain what the following Python 3 code does
def load_recipe(self):
        '''load will return a loaded in singularity recipe. The idea
           is that these sections can then be parsed into a Dockerfile,
           or printed back into their original form.

           Returns
           =======
           config: a parsed recipe Singularity recipe
        '''

        # Comments between sections, add to top of file
        lines = self.lines.copy()
        comments = []

        # Start with a fresh config!
        self.config = dict()

        section = None
        name = None

        while len(lines) > 0:

            # Clean up white trailing/leading space
            line = lines.pop(0)
            stripped = line.strip()

            # Bootstrap Line
            if re.search('(b|B)(o|O){2}(t|T)(s|S)(t|T)(r|R)(a|A)(p|P)', line):
                self._load_bootstrap(stripped)

            # From Line
            if re.search('(f|F)(r|R)(O|o)(m|M)', stripped):
                self._load_from(stripped)

            # Comment
            if stripped.startswith("#"):
                comments.append(stripped)
                continue

            # Section
            elif stripped.startswith('%'):
                section = self._add_section(stripped)
                bot.debug("Adding section title %s" %section)

            # If we have a section, and are adding it
            elif section is not None:
                lines = [line] + lines
                self._load_section(lines=lines,
                                   section=section)

            self.config['comments'] = comments

Response: load will return a loaded in singularity recipe


Instruction:
Can you generate the documentation for the following Python 3 function
def _add_section(self, line, section=None):
        '''parse a line for a section, and return the parsed section (if not
           None)

           Parameters
           ==========
           line: the line to parse
           section: the current (or previous) section

           Resulting data structure is:
           config['post'] (in lowercase)

        '''
        # Remove any comments
        line = line.split('#',1)[0].strip()

        # Is there a section name?
        parts = line.split(' ')
        if len(parts) > 1:
            name = ' '.join(parts[1:])
        section = re.sub('[%]|(\s+)','',parts[0]).lower()

        if section not in self.config:
            self.config[section] = []
            bot.debug("Adding section %s" %section)

        return section

Response: parse a line for a section and return the parsed section


Instruction:
Here you have a function in Python 3, explain what it does
def get_container_id(self, container_id=None):
        ''' a helper function shared between functions that will return a
            container_id. First preference goes to a container_id provided by
            the user at runtime. Second preference goes to the container_id
            instantiated with the client.

            Parameters
            ==========
            container_id: image uri to parse (required)
        '''

        # The user must provide a container_id, or have one with the client
        if container_id == None and self.container_id == None:
            bot.exit('You must provide a container_id.')

        # Choose whichever is not None, with preference for function provided
        container_id = container_id or self.container_id
        return container_id

Response:
a helper function shared between functions that will return a
            container_id


Instruction:
Can you write a function in Python 3 where it
runs a command and return the return code.

Response:
def _run_and_return(self, cmd, sudo=None):
        ''' Run a command, show the message to the user if quiet isn't set,
            and return the return code. This is a wrapper for the OCI client
            to run a command and easily return the return code value (what
            the user is ultimately interested in).

            Parameters
            ==========
            cmd: the command (list) to run.
            sudo: whether to add sudo or not.

        '''
        sudo = self._get_sudo(sudo)
        result = self._run_command(cmd,
                                   sudo=sudo,
                                   quiet=True,
                                   return_result=True)

        # Successful return with no output
        if len(result) == 0:
            return

        # Show the response to the user, only if not quiet.
        elif not self.quiet:
            bot.println(result['message'])

        # Return the state object to the user
        return result['return_code']


Instruction:
Create a Python 3 function to
export will export an image

Response:
def export(self, image_path, tmptar=None):
    '''export will export an image, sudo must be used.

       Parameters
       ==========

       image_path: full path to image
       tmptar: if defined, use custom temporary path for tar export

    '''
    from spython.utils import check_install
    check_install()

    if tmptar is None:
        tmptar = "/%s/tmptar.tar" %(tempfile.mkdtemp())
    cmd = ['singularity', 'image.export', '-f', tmptar, image_path]

    output = self.run_command(cmd, sudo=False)
    return tmptar


Instruction:
Can you generate a brief explanation for the following Python 3 code
def write_json(json_obj, filename, mode="w", print_pretty=True):
    '''write_json will (optionally,pretty print) a json object to file
    :param json_obj: the dict to print to json
    :param filename: the output file to write to
    :param pretty_print: if True, will use nicer formatting
    '''
    with open(filename, mode) as filey:
        if print_pretty:
            filey.writelines(
                json.dumps(
                    json_obj,
                    indent=4,
                    separators=(
                        ',',
                        ': ')))
        else:
            filey.writelines(json.dumps(json_obj))
    return filename

Response: write_json will print a json object to a file


Instruction:
Create a Python 3 function for
executing a command to a singularity container

Response:
def execute(self,
            image = None,
            command = None,
            app = None,
            writable = False,
            contain = False,
            bind = None,
            stream = False,
            nv = False,
            return_result=False):

    ''' execute: send a command to a container

        Parameters
        ==========

        image: full path to singularity image
        command: command to send to container
        app: if not None, execute a command in context of an app
        writable: This option makes the file system accessible as read/write
        contain: This option disables the automatic sharing of writable
                 filesystems on your host
        bind: list or single string of bind paths.
             This option allows you to map directories on your host system to
             directories within your container using bind mounts
        nv: if True, load Nvidia Drivers in runtime (default False)
        return_result: if True, return entire json object with return code
                       and message result (default is False)
    '''
    from spython.utils import check_install
    check_install()

    cmd = self._init_command('exec')

    # nv option leverages any GPU cards
    if nv is True:
        cmd += ['--nv']

    # If the image is given as a list, it's probably the command
    if isinstance(image, list):
        command = image
        image = None

    if command is not None:

        # No image provided, default to use the client's loaded image
        if image is None:
            image = self._get_uri()
            self.quiet = True

        # If an instance is provided, grab it's name
        if isinstance(image, self.instance):
            image = image.get_uri()

        # Does the user want to use bind paths option?
        if bind is not None:
            cmd += self._generate_bind_list(bind)

        # Does the user want to run an app?
        if app is not None:
            cmd = cmd + ['--app', app]

        sudo = False
        if writable is True:
            sudo = True

        if not isinstance(command, list):
            command = command.split(' ')

        cmd = cmd + [image] + command

        if stream is False:
            return self._run_command(cmd,
                                     sudo=sudo,
                                     return_result=return_result)
        return stream_command(cmd, sudo=sudo)

    bot.error('Please include a command (list) to execute.')


Instruction:
How would you implement a function in Python 3 that
parses a table to json from a string where a header is expected by default.

Response:
def parse_table(table_string, header, remove_rows=1):
    '''parse a table to json from a string, where a header is expected by default.
       Return a jsonified table.

       Parameters
       ==========
       table_string: the string table, ideally with a header
       header: header of expected table, must match dimension (number columns)
       remove_rows: an integer to indicate a number of rows to remove from top
                    the default is 1 assuming we don't want the header
    '''
    rows = [x for x in table_string.split('\n') if x]
    rows = rows[0+remove_rows:]

    # Parse into json dictionary
    parsed = []

    for row in rows:
        item = {}
        # This assumes no white spaces in each entry, which should be the case
        row = [x for x in row.split(' ') if x]
        for e in range(len(row)):
            item[header[e]] = row[e]
        parsed.append(item)
    return parsed


Instruction:
Write a Python 3 script for
getting is a list for a single instance

Response:
def get(self, name, return_json=False, quiet=False):
    '''get is a list for a single instance. It is assumed to be running,
       and we need to look up the PID, etc.
    '''
    from spython.utils import check_install
    check_install()

    # Ensure compatible for singularity prior to 3.0, and after 3.0
    subgroup = "instance.list"

    if 'version 3' in self.version():
        subgroup = ["instance", "list"]

    cmd = self._init_command(subgroup)

    cmd.append(name)
    output = run_command(cmd, quiet=True)

    # Success, we have instances

    if output['return_code'] == 0:

        # Only print the table if we are returning json
        if quiet is False:
            print(''.join(output['message']))

        # Prepare json result from table

        header = ['daemon_name','pid','container_image']
        instances = parse_table(output['message'][0], header)

        # Does the user want instance objects instead?
        listing = []
        if return_json is False:
            for i in instances:
                new_instance = Instance(pid=i['pid'],
                                        name=i['daemon_name'],
                                        image=i['container_image'],
                                        start=False)

                listing.append(new_instance)
            instances = listing

    # Couldn't get UID

    elif output['return_code'] == 255:
        bot.error("Couldn't get UID")

    # Return code of 0
    else:
        bot.info('No instances found.')

    # If we are given a name, return just one
    if name is not None and len(instances) == 1:
        instances = instances[0]

    return instances


Instruction:
How would you implement a function in Python 3 that
sets the message level in the environment to set based on args.

Response:
def set_verbosity(args):
    '''determine the message level in the environment to set based on args.
    '''
    level = "INFO"

    if args.debug is True:
        level = "DEBUG"
    elif args.quiet is True:
        level = "QUIET"

    os.environ['MESSAGELEVEL'] = level
    os.putenv('MESSAGELEVEL', level)
    os.environ['SINGULARITY_MESSAGELEVEL'] = level
    os.putenv('SINGULARITY_MESSAGELEVEL', level)

    # Import logger to set
    from spython.logger import bot
    bot.debug('Logging level %s' %level)
    import spython

    bot.debug("Singularity Python Version: %s" % spython.__version__)


Instruction:
Write a Python 3 function for
generating the list of commands that can be used to create an image.

Response:
def generate_image_commands():
    ''' The Image client holds the Singularity image command group, mainly
        deprecated commands (image.import) and additional command helpers
        that are commonly use but not provided by Singularity

        The levels of verbosity (debug and quiet) are passed from the main
        client via the environment variable MESSAGELEVEL.

        These commands are added to Client.image under main/__init__.py to
        expose subcommands:

            Client.image.export
            Client.image.imprt
            Client.image.decompress
            Client.image.create

    '''

    class ImageClient(object):
        group = "image"

    from spython.main.base.logger import println
    from spython.main.base.command import ( init_command, run_command )
    from .utils import ( compress, decompress )
    from .create import create
    from .importcmd import importcmd
    from .export import export

    ImageClient.create = create
    ImageClient.imprt = importcmd
    ImageClient.export = export
    ImageClient.decompress = decompress
    ImageClient.compress = compress
    ImageClient.println = println
    ImageClient.init_command = init_command
    ImageClient.run_command = run_command

    cli = ImageClient()
    return cli


Instruction:
Make a summary of the following Python 3 code
def init_command(self, action, flags=None):
    '''return the initial Singularity command with any added flags.

       Parameters
       ==========
       action: the main action to perform (e.g., build)
       flags: one or more additional flags (e.g, volumes)
              not implemented yet.
    '''

    if not isinstance(action, list):
        action = [action]
    cmd = ['singularity'] + action

    if self.quiet is True:
        cmd.insert(1, '--quiet')
    if self.debug is True:
        cmd.insert(1, '--debug')

    return cmd

Response: return the initial Singularity command with any added flags.


Instruction:
Write a Python 3 script to
generate bind string will take a single string or list of binds and return a list of binds that can be added to an exec or run command.

Response:
def generate_bind_list(self, bindlist=None):
    '''generate bind string will take a single string or list of binds, and
       return a list that can be added to an exec or run command. For example,
       the following map as follows:

      ['/host:/container', '/both'] --> ["--bind", "/host:/container","--bind","/both" ]
      ['/both']                     --> ["--bind", "/both"]
      '/host:container'             --> ["--bind", "/host:container"]
       None                         --> []

       An empty bind or otherwise value of None should return an empty list.
       The binds are also checked on the host.

       Parameters
       ==========
       bindlist: a string or list of bind mounts

    '''
    binds = []

    # Case 1: No binds provided
    if not bindlist:
        return binds

    # Case 2: provides a long string or non list, and must be split
    if not isinstance(bindlist, list):
        bindlist = bindlist.split(' ')

    for bind in bindlist:

        # Still cannot be None
        if bind:
            bot.debug('Adding bind %s' %bind)
            binds += ['--bind', bind]

            # Check that exists on host
            host = bind.split(':')[0]
            if not os.path.exists(host):
                bot.error('%s does not exist on host.' %bind)
                sys.exit(1)

    return binds


Instruction:
Write a Python 3 function for
sending command to the terminal

Response:
def send_command(self, cmd, sudo=False, stderr=None, stdout=None):
    '''send command is a non interactive version of run_command, meaning
       that we execute the command and return the return value, but don't
       attempt to stream any content (text from the screen) back to the
       user. This is useful for commands interacting with OCI bundles.

       Parameters
       ==========
       cmd: the list of commands to send to the terminal
       sudo: use sudo (or not)
    '''

    if sudo is True:
        cmd = ['sudo'] + cmd

    process = subprocess.Popen(cmd, stderr=stderr, stdout=stdout)
    result = process.communicate()
    return result


Instruction:
Write a Python 3 script to
wrap for the global run_command function.

Response:
def run_command(self, cmd,
                      sudo=False,
                      capture=True,
                      quiet=None,
                      return_result=False):

    '''run_command is a wrapper for the global run_command, checking first
       for sudo and exiting on error if needed. The message is returned as
       a list of lines for the calling function to parse, and stdout uses
       the parent process so it appears for the user.

       Parameters
       ==========
       cmd: the command to run
       sudo: does the command require sudo?
       quiet: if quiet set by function, overrides client setting.
       return_result: return the result, if not successful (default False).
       On success, returns result.

    '''
    # First preference to function, then to client setting
    if quiet == None:
        quiet = self.quiet

    result = run_cmd(cmd, sudo=sudo, capture=capture, quiet=quiet)

    # If one line is returned, squash dimension
    if len(result['message']) == 1:
        result['message'] = result['message'][0]

    # If the user wants to return the result, just return it
    if return_result is True:
        return result

    # On success, return result
    if result['return_code'] == 0:
        return result['message']

    return result


Instruction:
Can you generate the documentation for the following Python 3 function
def load(self, recipe):
        '''load a recipe file into the client, first performing checks, and
           then parsing the file.

           Parameters
           ==========
           recipe: the original recipe file, parsed by the subclass either
               DockerRecipe or SingularityRecipe

        '''
        self.recipe = recipe           # the recipe file
        self._run_checks()             # does the recipe file exist?
        self.parse()

Response: load a recipe file into the client


Instruction:
Can you create a Python 3 function that
parses is the base function for parsing the recipe, whether it be a Dockerfile or Singularity recipe. The recipe is read in as lines, and saved to a list if needed for the future. If the client has it, the recipe type specific _parse function is called. Instructions for making a client subparser: It should have a main function _parse that parses a list of lines from some recipe text file into the appropriate sections, e.g., self.fromHeader self.environ self.labels self.install self.files self.test self.entrypoint

Response:
def parse(self):
        '''parse is the base function for parsing the recipe, whether it be
           a Dockerfile or Singularity recipe. The recipe is read in as lines,
           and saved to a list if needed for the future. If the client has
           it, the recipe type specific _parse function is called.

           Instructions for making a client subparser:

               It should have a main function _parse that parses a list of lines
               from some recipe text file into the appropriate sections, e.g.,

               self.fromHeader
               self.environ
               self.labels
               self.install
               self.files
               self.test
               self.entrypoint

        '''

        self.cmd = None
        self.comments = []
        self.entrypoint = None
        self.environ = []
        self.files = []
        self.install = []
        self.labels = []
        self.ports = []
        self.test = None
        self.volumes = []

        if self.recipe:

            # Read in the raw lines of the file
            self.lines = read_file(self.recipe)

            # If properly instantiated by Docker or Singularity Recipe, parse
            if hasattr(self, '_parse'):
                self._parse()


Instruction:
Here you have a function in Python 3, explain what it does
def save(self, output_file=None,
                   convert_to=None,
                   runscript="/bin/bash",
                   force=False):

        '''save will convert a recipe to a specified format (defaults to the
           opposite of the recipe type originally loaded, (e.g., docker-->
           singularity and singularity-->docker) and write to an output file,
           if specified. If not specified, a temporary file is used.

           Parameters
           ==========
           output_file: the file to save to, not required (estimates default)
           convert_to: can be manually forced (docker or singularity)
           runscript: default runscript (entrypoint) to use
           force: if True, override discovery from Dockerfile

        '''

        converted = self.convert(convert_to, runscript, force)
        if output_file is None:
            output_file = self._get_conversion_outfile(convert_to=None)
        bot.info('Saving to %s' %output_file)
        write_file(output_file, converted)

Response: save will convert a recipe to a specified format and write to an output file


Instruction:
Write a Python 3 function that can
see convert and save. This is a helper function that returns the proper conversion function that does not call it.

Response:
def _get_converter(self, convert_to=None):
        '''see convert and save. This is a helper function that returns
           the proper conversion function, but doesn't call it. We do this
           so that in the case of convert, we do the conversion and return
           a string. In the case of save, we save the recipe to file for the
           user.

           Parameters
           ==========
           convert_to: a string either docker or singularity, if a different

           Returns
           =======
           converter: the function to do the conversion

        '''
        conversion = self._get_conversion_type(convert_to)

        # Perform conversion
        if conversion == "singularity":
            return self.docker2singularity
        return self.singularity2docker


Instruction:
Make a summary of the following Python 3 code
def _get_conversion_outfile(self, convert_to=None):
        '''a helper function to return a conversion temporary output file
           based on kind of conversion

           Parameters
           ==========
           convert_to: a string either docker or singularity, if a different

        '''
        conversion = self._get_conversion_type(convert_to)
        prefix = "Singularity"
        if conversion == "docker":
            prefix = "Dockerfile"
        suffix = next(tempfile._get_candidate_names())
        return "%s.%s" %(prefix, suffix)

Response: a helper function to return a conversion temporary output file based on kind of conversion


Instruction:
Can you tell what is the following Python 3 function doing
def _get_conversion_type(self, convert_to=None):
        '''a helper function to return the conversion type based on user
           preference and input recipe.

           Parameters
           ==========
           convert_to: a string either docker or singularity (default None)

        '''
        acceptable = ['singularity', 'docker']

        # Default is to convert to opposite kind
        conversion = "singularity"
        if self.name == "singularity":
            conversion = "docker"

        # Unless the user asks for a specific type
        if convert_to is not None and convert_to in acceptable:
            conversion = convert_to
        return conversion

Response:
a helper function to return the conversion type based on user
           preference and input recipe.


Instruction:
How would you explain what the following Python 3 function does
def _write_script(path, lines, chmod=True):
        '''write a script with some lines content to path in the image. This
           is done by way of adding echo statements to the install section.

           Parameters
           ==========
           path: the path to the file to write
           lines: the lines to echo to the file
           chmod: If true, change permission to make u+x

        '''
        if len(lines) > 0:
            lastline = lines.pop()
        for line in lines:
            self.install.append('echo "%s" >> %s' %path)
        self.install.append(lastline)

        if chmod is True:
            self.install.append('chmod u+x %s' %path)

Response: write a script with some lines content to path in the image


Instruction:
Implement a Python 3 function for
getting the state of an OciImage if it exists

Response:
def state(self, container_id=None, sudo=None, sync_socket=None):

    ''' get the state of an OciImage, if it exists. The optional states that
        can be returned are created, running, stopped or (not existing).

        Equivalent command line example:
           singularity oci state <container_ID>

        Parameters
        ==========
        container_id: the id to get the state of.
        sudo: Add sudo to the command. If the container was created by root,
              you need sudo to interact and get its state.
        sync_socket: the path to the unix socket for state synchronization

        Returns
        =======
        state: a parsed json of the container state, if exists. If the
               container is not found, None is returned.
    '''
    sudo = self._get_sudo(sudo)
    container_id = self.get_container_id(container_id)

    # singularity oci state
    cmd = self._init_command('state')

    if sync_socket != None:
        cmd = cmd + ['--sync-socket', sync_socket]

    # Finally, add the container_id
    cmd.append(container_id)

    # Get the instance state
    result = self._run_command(cmd, sudo=sudo, quiet=True)

    if result != None:

        # If successful, a string is returned to parse
        if isinstance(result, str):
            return json.loads(result)


Instruction:
Can you tell what is the following Python 3 function doing
def _state_command(self, container_id=None, command='start', sudo=None):

    ''' A generic state command to wrap pause, resume, kill, etc., where the
        only difference is the command. This function will be unwrapped if the
        child functions get more complicated (with additional arguments).

        Equivalent command line example:
           singularity oci <command> <container_ID>

        Parameters
        ==========
        container_id: the id to start.
        command: one of start, resume, pause, kill, defaults to start.
        sudo: Add sudo to the command. If the container was created by root,
              you need sudo to interact and get its state.

        Returns
        =======
        return_code: the return code to indicate if the container was started.
    '''
    sudo = self._get_sudo(sudo)
    container_id = self.get_container_id(container_id)

    # singularity oci state
    cmd = self._init_command(command)

    # Finally, add the container_id
    cmd.append(container_id)

    # Run the command, return return code
    return self._run_and_return(cmd, sudo)

Response: A generic state command to wrap pause resume kill etc.


Instruction:
Can you create a Python 3 function that
stops a started OciImage container

Response:
def kill(self, container_id=None, sudo=None, signal=None):

    ''' stop (kill) a started OciImage container, if it exists

        Equivalent command line example:
           singularity oci kill <container_ID>

        Parameters
        ==========
        container_id: the id to stop.
        signal: signal sent to the container (default SIGTERM)
        sudo: Add sudo to the command. If the container was created by root,
              you need sudo to interact and get its state.

        Returns
        =======
        return_code: the return code to indicate if the container was killed.
    '''
    sudo = self._get_sudo(sudo)
    container_id = self.get_container_id(container_id)

    # singularity oci state
    cmd = self._init_command('kill')

    # Finally, add the container_id
    cmd.append(container_id)

    # Add the signal, if defined
    if signal != None:
        cmd = cmd + ['--signal', signal]

    # Run the command, return return code
    return self._run_and_return(cmd, sudo)