Convert iTunes playstate to API representation.
506254
def playstate(state):
    """"""
    # pylint: disable=too-many-return-statements
    if state is None:
        return const.PLAY_STATE_NO_MEDIA
    if state == 0:
        return const.PLAY_STATE_IDLE
    if state == 1:
        return const.PLAY_STATE_LOADING
    if state == 3:
        return const.PLAY_STATE_PAUSED
    if state == 4:
        return const.PLAY_STATE_PLAYING
    if state == 5:
        return const.PLAY_STATE_FAST_FORWARD
    if state == 6:
        return const.PLAY_STATE_FAST_BACKWARD

    raise exceptions.UnknownPlayState('Unknown playstate: ' + str(state))
987465
def _update_media_data(self):
        
        # Use different query URL based on selected source
        if self._input_func in self._netaudio_func_list:
            try:
                root = self.get_status_xml(self._urls.netaudiostatus)
            except (ValueError, requests.exceptions.RequestException):
                return False

            # Get the relevant tags from XML structure
            for child in root:
                if child.tag == "szLine":
                    if (self._title != html.unescape(child[1].text) if (
                            child[1].text is not None) else None or
                            self._artist != html.unescape(child[2].text) if (
                                child[2].text is not None) else None or
                            self._album != html.unescape(child[4].text) if (
                                child[4].text is not None) else None):
                        # Refresh cover with a new time stamp for media URL
                        # when track is changing
                        self._image_url = (ALBUM_COVERS_URL.format(
                            host=self._host, port=self._receiver_port,
                            time=int(time.time())))
                        # On track change assume device is PLAYING
                        self._state = STATE_PLAYING
                    self._title = html.unescape(child[1].text) if (
                        child[1].text is not None) else None
                    self._artist = html.unescape(child[2].text) if (
                        child[2].text is not None) else None
                    self._album = html.unescape(child[4].text)if (
                        child[4].text is not None) else None
                    self._band = None
                    self._frequency = None
                    self._station = None

        elif self._input_func == "Tuner" or self._input_func == "TUNER":
            try:
                root = self.get_status_xml(self._urls.tunerstatus)
            except (ValueError, requests.exceptions.RequestException):
                return False

            # Get the relevant tags from XML structure
            for child in root:
                if child.tag == "Band":
                    self._band = child[0].text
                elif child.tag == "Frequency":
                    self._frequency = child[0].text

            self._title = None
            self._artist = None
            self._album = None
            self._station = None

            # Assume Tuner is always PLAYING
            self._state = STATE_PLAYING

            # No special cover, using a static one
            self._image_url = (
                STATIC_ALBUM_URL.format(
                    host=self._host, port=self._receiver_port))

        elif self._input_func == "HD Radio" or self._input_func == "HDRADIO":
            try:
                root = self.get_status_xml(self._urls.hdtunerstatus)
            except (ValueError, requests.exceptions.RequestException):
                return False

            # Get the relevant tags from XML structure
            for child in root:
                if child.tag == "Artist":
                    self._artist = html.unescape(child[0].text) if (
                        child[0].text is not None) else None
                elif child.tag == "Title":
                    self._title = html.unescape(child[0].text) if (
                        child[0].text is not None) else None
                elif child.tag == "Album":
                    self._album = html.unescape(child[0].text) if (
                        child[0].text is not None) else None
                elif child.tag == "Band":
                    self._band = html.unescape(child[0].text) if (
                        child[0].text is not None) else None
                elif child.tag == "Frequency":
                    self._frequency = html.unescape(child[0].text) if (
                        child[0].text is not None) else None
                elif child.tag == "StationNameSh":
                    self._station = html.unescape(child[0].text) if (
                        child[0].text is not None) else None

            # Assume Tuner is always PLAYING
            self._state = STATE_PLAYING

            # No special cover, using a static one
            self._image_url = (
                STATIC_ALBUM_URL.format(
                    host=self._host, port=self._receiver_port))

        # No behavior implemented, so reset all variables for that source
        else:
            self._band = None
            self._frequency = None
            self._title = None
            self._artist = None
            self._album = None
            self._station = None
            # Assume PLAYING_DEVICE is always PLAYING
            self._state = STATE_PLAYING
            # No special cover, using a static one
            self._image_url = (
                STATIC_ALBUM_URL.format(
                    host=self._host, port=self._receiver_port))

        # Test if image URL is accessable
        if self._image_available is None and self._image_url is not None:
            try:
                imgres = requests.get(self._image_url, timeout=self.timeout)
            except requests.exceptions.RequestException:
                # No result set image URL to None
                self._image_url = None
            else:
                if imgres.status_code == 200:
                    self._image_available = True
                else:
                    _LOGGER.info('No album art available for your receiver')
                    # No image available. Save this status.
                    self._image_available = False
                    #  Set image URL to None.
                    self._image_url = None
        # Already tested that image URL is not accessible
        elif self._image_available is False:
            self._image_url = None

        # Finished
        return True
326305
function getGoToTrackState({
  prevState,
  index,
  track,
  shouldPlay = true,
  shouldForceLoad = false
}) {
  const isNewTrack = prevState.activeTrackIndex !== index;
  const shouldLoadAsNew = Boolean(isNewTrack || shouldForceLoad);
  const currentTime = track.startingTime || 0;
  return {
    duration: getInitialDuration(track),
    activeTrackIndex: index,
    trackLoading: shouldLoadAsNew,
    mediaCannotPlay: prevState.mediaCannotPlay && !shouldLoadAsNew,
    currentTime: convertToNumberWithinIntervalBounds(currentTime, 0),
    loop: shouldLoadAsNew ? false : prevState.loop,
    shouldRequestPlayOnNextUpdate: Boolean(shouldPlay),
    awaitingPlayAfterTrackLoad: Boolean(shouldPlay),
    awaitingForceLoad: Boolean(shouldForceLoad),
    maxKnownTime: shouldLoadAsNew ? 0 : prevState.maxKnownTime
  };
}
124588
async def set_playstate(self, state, pos=0):
        
        url = '{}/Sessions/{}/Playing/{}'.format(
            self.server.construct_url(API_URL), self.session_id, state)
        params = {'api_key': self.server.api_key}

        if state == 'seek':
            params['SeekPositionTicks'] = int(pos * 10000000)
            params['static'] = 'true'

        _LOGGER.debug('Playstate URL: %s', url)

        post = await self.server.api_post(url, params)
        if post is None:
            _LOGGER.debug('Error sending command.')
        else:
            _LOGGER.debug('Post response: %s', post)
1320193
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)
222432
def _from_dict(cls, _dict):
        """"""
        args = {}
        if 'duration' in _dict:
            args['duration'] = _dict.get('duration')
        if 'name' in _dict:
            args['name'] = _dict.get('name')
        if 'details' in _dict:
            args['details'] = AudioDetails._from_dict(_dict.get('details'))
        if 'status' in _dict:
            args['status'] = _dict.get('status')
        if 'container' in _dict:
            args['container'] = AudioResource._from_dict(_dict.get('container'))
        if 'audio' in _dict:
            args['audio'] = [
                AudioResource._from_dict(x) for x in (_dict.get('audio'))
            ]
        return cls(**args)
305054
def play(media_to_play = "playlist", options = {})
      start_the_machine
      check_for_playback_status

      media = case true
              when media_to_play.is_a?(Media) then media_to_play
              when media_to_play == "playlist" && playlist.any?
                playlist.next
              else Media.new(media_to_play)
              end

      content = {
        "Content-Location" => media,
        "Start-Position" => options.fetch(:time, 0.0)
      }

      data = content.map { |k, v| "#{k}: #{v}" }.join("\r\n")

      response = persistent.async.post("/play", data + "\r\n", {
        "Content-Type" => "text/parameters"
      })

      timers.reset
    end
324941
def short_play(self, **kwargs):
        
        # options in URL arguments
        config = self._config_from_url()
        outputs = self.run(kwargs, config)
        return jsonify(outputs)
534299
def to_api_repr(self):
        
        resource = {}

        if self.etag is not None:
            resource["etag"] = self.etag

        if self.version is not None:
            resource["version"] = self.version

        if self._bindings:
            bindings = resource["bindings"] = []
            for role, members in sorted(self._bindings.items()):
                if members:
                    bindings.append({"role": role, "members": sorted(set(members))})

            if not bindings:
                del resource["bindings"]

        return resource
1278065
def render_to_response(self, context, **response_kwargs):
        '''
        
        '''
        switcher = {
            'json': self.return_json_response,
            'opml': self.return_opml_response,
            'md': self.return_md_response,
            'textbundle': self.not_implemented,
            'xlsx': self.not_implemented,
        }
        if self.format not in switcher.keys():
            return self.not_implemented(context, **response_kwargs)
        return switcher[self.format](context, **response_kwargs)
169160
def createPlaylist(name,description,tracks,extras=nil)
      method = 'createPlaylist'
      type = Playlist
      args = {:name=>name,:description=>description,
        :tracks=>Rdio::keys(tracks)}
      args[:extras] = extras if extras
      return_object type,method,args,true
    end
1204429
def inverse(self, encoded, downbeat=None, duration=None):
        ''''''

        ann = jams.Annotation(namespace=self.namespace, duration=duration)

        beat_times = np.asarray([t for t, _ in self.decode_events(encoded,
                                                                  transition=self.beat_transition,
                                                                  p_init=self.beat_p_init,
                                                                  p_state=self.beat_p_state) if _])
        beat_frames = time_to_frames(beat_times,
                                     sr=self.sr,
                                     hop_length=self.hop_length)

        if downbeat is not None:
            downbeat_times = set([t for t, _ in self.decode_events(downbeat,
                                                                   transition=self.down_transition,
                                                                   p_init=self.down_p_init,
                                                                   p_state=self.down_p_state) if _])
            pickup_beats = len([t for t in beat_times
                                if t < min(downbeat_times)])
        else:
            downbeat_times = set()
            pickup_beats = 0

        value = - pickup_beats - 1
        for beat_t, beat_f in zip(beat_times, beat_frames):
            if beat_t in downbeat_times:
                value = 1
            else:
                value += 1
            confidence = encoded[beat_f]
            ann.append(time=beat_t,
                       duration=0,
                       value=value,
                       confidence=confidence)

        return ann
93400
async def play_url(self, url, position=0):
        """"""
        headers = {'User-Agent': 'MediaControl/1.0',
                   'Content-Type': 'application/x-apple-binary-plist'}
        body = {'Content-Location': url, 'Start-Position': position}

        address = self._url(self.port, 'play')
        _LOGGER.debug('AirPlay %s to %s', url, address)

        resp = None
        try:
            # pylint: disable=no-member
            resp = await self.session.post(
                address, headers=headers,
                data=plistlib.dumps(body, fmt=plistlib.FMT_BINARY),
                timeout=TIMEOUT)
            await self._wait_for_media_to_end()
        finally:
            if resp is not None:
                resp.close()
961562
def play(song, artist=None, album=None):
	""""""

	if not settings.platformCompatible():
		return False

	if song and not artist and not album:
		(output, error) = subprocess.Popen(["osascript", "-e", DEFAULT_ITUNES_PLAY % (song, song, song)], stdout=subprocess.PIPE).communicate()
		if output:
			speech.speak("Playing " + output)
		else:
			speech.speak("Unable to find " + song + " in your library.")

	elif song and artist and not album:
		(output, error) = subprocess.Popen(["osascript", "-e", ITUNES_SONG_AND_ARTIST % (song, artist, song, artist)], stdout=subprocess.PIPE).communicate()
		if output:
			speech.speak("Playing " + output)
		else:
			speech.speak("Unable to find " + song + " in your library.")

	elif album and artist and not song:
		(output, error) = subprocess.Popen(["osascript", "-e", ITUNES_ALBUM_AND_ARTIST % (artist, album)], stdout=subprocess.PIPE).communicate()
		if output:
			speech.speak("Playing " + output)
		else:
			speech.speak("Unable to find " + song + " in your library.")

	elif album and not artist and not song:
		(output, error) = subprocess.Popen(["osascript", "-e", ITUNES_ALBUM % (album)], stdout=subprocess.PIPE).communicate()
		if output:
			speech.speak("Playing " + output)
		else:
			speech.speak("Unable to find " + song + " in your library.")

	elif artist and not album and not song:
		(output, error) = subprocess.Popen(["osascript", "-e", ITUNES_ARTIST % (artist)], stdout=subprocess.PIPE).communicate()
		if output:
			speech.speak("Playing " + output)
		else:
			speech.speak("Unable to find " + song + " in your library.")
668147
def isplaybook(obj):
    '''
    
    '''
    return isinstance(obj, Iterable) and (not isinstance(obj, string_types) and not isinstance(obj, Mapping))
294577
def play(device_id = nil, params = {})
      url = "me/player/play"
      url = device_id.nil? ? url : "#{url}?device_id=#{device_id}"

      User.oauth_put(@user.id, url, params.to_json)
    end
1239510
def convert_if_not(cls, phases_or_groups):
    """"""
    if isinstance(phases_or_groups, PhaseGroup):
      return mutablerecords.CopyRecord(phases_or_groups)

    flattened = flatten_phases_and_groups(phases_or_groups)
    return cls(main=flattened)