code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
part = '/library/sections/%s?%s' % (self.key, urlencode(kwargs)) self._server.query(part, method=self._server._session.put) # Reload this way since the self.key dont have a full path, but is simply a id. for s in self._server.library.sections(): if s.key == self.key: return s
def edit(self, **kwargs)
Edit a library (Note: agent is required). See :class:`~plexapi.library.Library` for example usage. Parameters: kwargs (dict): Dict of settings to edit.
7.876451
7.01737
1.122422
key = '/library/sections/%s/all' % self.key return self.fetchItem(key, title__iexact=title)
def get(self, title)
Returns the media item with the specified title. Parameters: title (str): Title of the item to return.
14.360346
16.215364
0.885601
sortStr = '' if sort is not None: sortStr = '?sort=' + sort key = '/library/sections/%s/all%s' % (self.key, sortStr) return self.fetchItems(key, **kwargs)
def all(self, sort=None, **kwargs)
Returns a list of media from this library section. Parameters: sort (string): The sort string
4.798523
4.562701
1.051685
key = '/library/sections/%s/analyze' % self.key self._server.query(key, method=self._server._session.put)
def analyze(self)
Run an analysis on all of the items in this library section. See See :func:`~plexapi.base.PlexPartialObject.analyze` for more details.
15.8709
5.925337
2.67848
key = '/library/sections/%s/emptyTrash' % self.key self._server.query(key, method=self._server._session.put)
def emptyTrash(self)
If a section has items in the Trash, use this option to empty the Trash.
12.729152
8.318329
1.530253
key = '/library/sections/%s/refresh' % self.key self._server.query(key, method=self._server._session.delete)
def cancelUpdate(self)
Cancel update of this Library Section.
14.284185
9.481707
1.506499
key = '/library/sections/%s/indexes' % self.key self._server.query(key, method=self._server._session.delete)
def deleteMediaPreviews(self)
Delete the preview thumbnails for items in this library. This cannot be undone. Recreating media preview files can take hours or even days.
13.068472
11.579129
1.128623
# TODO: Should this be moved to base? if category in kwargs: raise BadRequest('Cannot include kwarg equal to specified category: %s' % category) args = {} for subcategory, value in kwargs.items(): args[category] = self._cleanSearchFilter(subcategory, value) if libtype is not None: args['type'] = utils.searchType(libtype) key = '/library/sections/%s/%s%s' % (self.key, category, utils.joinArgs(args)) return self.fetchItems(key, cls=FilterChoice)
def listChoices(self, category, libtype=None, **kwargs)
Returns a list of :class:`~plexapi.library.FilterChoice` objects for the specified category and libtype. kwargs can be any of the same kwargs in :func:`plexapi.library.LibraySection.search()` to help narrow down the choices to only those that matter in your current context. Parameters: category (str): Category to list choices for (genre, contentRating, etc). libtype (int): Library type of item filter. **kwargs (dict): Additional kwargs to narrow down the choices. Raises: :class:`plexapi.exceptions.BadRequest`: Cannot include kwarg equal to specified category.
6.255132
4.042127
1.547485
# cleanup the core arguments args = {} for category, value in kwargs.items(): args[category] = self._cleanSearchFilter(category, value, libtype) if title is not None: args['title'] = title if sort is not None: args['sort'] = self._cleanSearchSort(sort) if libtype is not None: args['type'] = utils.searchType(libtype) # iterate over the results results, subresults = [], '_init' args['X-Plex-Container-Start'] = 0 args['X-Plex-Container-Size'] = min(X_PLEX_CONTAINER_SIZE, maxresults) while subresults and maxresults > len(results): key = '/library/sections/%s/all%s' % (self.key, utils.joinArgs(args)) subresults = self.fetchItems(key) results += subresults[:maxresults - len(results)] args['X-Plex-Container-Start'] += args['X-Plex-Container-Size'] return results
def search(self, title=None, sort=None, maxresults=999999, libtype=None, **kwargs)
Search the library. If there are many results, they will be fetched from the server in batches of X_PLEX_CONTAINER_SIZE amounts. If you're only looking for the first <num> results, it would be wise to set the maxresults option to that amount so this functions doesn't iterate over all results on the server. Parameters: title (str): General string query to search for (optional). sort (str): column:dir; column can be any of {addedAt, originallyAvailableAt, lastViewedAt, titleSort, rating, mediaHeight, duration}. dir can be asc or desc (optional). maxresults (int): Only return the specified number of results (optional). libtype (str): Filter results to a spcifiec libtype (movie, show, episode, artist, album, track; optional). **kwargs (dict): Any of the available filters for the current library section. Partial string matches allowed. Multiple matches OR together. Negative filtering also possible, just add an exclamation mark to the end of filter name, e.g. `resolution!=1x1`. * unwatched: Display or hide unwatched content (True, False). [all] * duplicate: Display or hide duplicate items (True, False). [movie] * actor: List of actors to search ([actor_or_id, ...]). [movie] * collection: List of collections to search within ([collection_or_id, ...]). [all] * contentRating: List of content ratings to search within ([rating_or_key, ...]). [movie,tv] * country: List of countries to search within ([country_or_key, ...]). [movie,music] * decade: List of decades to search within ([yyy0, ...]). [movie] * director: List of directors to search ([director_or_id, ...]). [movie] * genre: List Genres to search within ([genere_or_id, ...]). [all] * network: List of TV networks to search within ([resolution_or_key, ...]). [tv] * resolution: List of video resolutions to search within ([resolution_or_key, ...]). [movie] * studio: List of studios to search within ([studio_or_key, ...]). [music] * year: List of years to search within ([yyyy, ...]). [all] Raises: :class:`plexapi.exceptions.BadRequest`: when applying unknown filter
3.141452
3.030058
1.036763
from plexapi.sync import SyncItem if not self.allowSync: raise BadRequest('The requested library is not allowed to sync') args = {} for category, value in kwargs.items(): args[category] = self._cleanSearchFilter(category, value, libtype) if sort is not None: args['sort'] = self._cleanSearchSort(sort) if libtype is not None: args['type'] = utils.searchType(libtype) myplex = self._server.myPlexAccount() sync_item = SyncItem(self._server, None) sync_item.title = title if title else self.title sync_item.rootTitle = self.title sync_item.contentType = self.CONTENT_TYPE sync_item.metadataType = self.METADATA_TYPE sync_item.machineIdentifier = self._server.machineIdentifier key = '/library/sections/%s/all' % self.key sync_item.location = 'library://%s/directory/%s' % (self.uuid, quote_plus(key + utils.joinArgs(args))) sync_item.policy = policy sync_item.mediaSettings = mediaSettings return myplex.sync(client=client, clientId=clientId, sync_item=sync_item)
def sync(self, policy, mediaSettings, client=None, clientId=None, title=None, sort=None, libtype=None, **kwargs)
Add current library section as sync item for specified device. See description of :func:`~plexapi.library.LibrarySection.search()` for details about filtering / sorting and :func:`plexapi.myplex.MyPlexAccount.sync()` for possible exceptions. Parameters: policy (:class:`plexapi.sync.Policy`): policy of syncing the media (how many items to sync and process watched media or not), generated automatically when method called on specific LibrarySection object. mediaSettings (:class:`plexapi.sync.MediaSettings`): Transcoding settings used for the media, generated automatically when method called on specific LibrarySection object. client (:class:`plexapi.myplex.MyPlexDevice`): sync destination, see :func:`plexapi.myplex.MyPlexAccount.sync`. clientId (str): sync destination, see :func:`plexapi.myplex.MyPlexAccount.sync`. title (str): descriptive title for the new :class:`plexapi.sync.SyncItem`, if empty the value would be generated from metadata of current media. sort (str): formatted as `column:dir`; column can be any of {`addedAt`, `originallyAvailableAt`, `lastViewedAt`, `titleSort`, `rating`, `mediaHeight`, `duration`}. dir can be `asc` or `desc`. libtype (str): Filter results to a specific libtype (`movie`, `show`, `episode`, `artist`, `album`, `track`). Returns: :class:`plexapi.sync.SyncItem`: an instance of created syncItem. Raises: :class:`plexapi.exceptions.BadRequest`: when the library is not allowed to sync Example: .. code-block:: python from plexapi import myplex from plexapi.sync import Policy, MediaSettings, VIDEO_QUALITY_3_MBPS_720p c = myplex.MyPlexAccount() target = c.device('Plex Client') sync_items_wd = c.syncItems(target.clientIdentifier) srv = c.resource('Server Name').connect() section = srv.library.section('Movies') policy = Policy('count', unwatched=True, value=1) media_settings = MediaSettings.create(VIDEO_QUALITY_3_MBPS_720p) section.sync(target, policy, media_settings, title='Next best movie', sort='rating:desc')
3.481426
3.18014
1.09474
from plexapi.sync import Policy, MediaSettings kwargs['mediaSettings'] = MediaSettings.createVideo(videoQuality) kwargs['policy'] = Policy.create(limit, unwatched) return super(MovieSection, self).sync(**kwargs)
def sync(self, videoQuality, limit=None, unwatched=False, **kwargs)
Add current Movie library section as sync item for specified device. See description of :func:`plexapi.library.LibrarySection.search()` for details about filtering / sorting and :func:`plexapi.library.LibrarySection.sync()` for details on syncing libraries and possible exceptions. Parameters: videoQuality (int): idx of quality of the video, one of VIDEO_QUALITY_* values defined in :mod:`plexapi.sync` module. limit (int): maximum count of movies to sync, unlimited if `None`. unwatched (bool): if `True` watched videos wouldn't be synced. Returns: :class:`plexapi.sync.SyncItem`: an instance of created syncItem. Example: .. code-block:: python from plexapi import myplex from plexapi.sync import VIDEO_QUALITY_3_MBPS_720p c = myplex.MyPlexAccount() target = c.device('Plex Client') sync_items_wd = c.syncItems(target.clientIdentifier) srv = c.resource('Server Name').connect() section = srv.library.section('Movies') section.sync(VIDEO_QUALITY_3_MBPS_720p, client=target, limit=1, unwatched=True, title='Next best movie', sort='rating:desc')
5.702942
5.850381
0.974798
return self.search(sort='addedAt:desc', libtype=libtype, maxresults=maxresults)
def recentlyAdded(self, libtype='episode', maxresults=50)
Returns a list of recently added episodes from this library section. Parameters: maxresults (int): Max number of items to return (default 50).
5.206177
9.913404
0.525165
from plexapi.sync import Policy, MediaSettings kwargs['mediaSettings'] = MediaSettings.createMusic(bitrate) kwargs['policy'] = Policy.create(limit) return super(MusicSection, self).sync(**kwargs)
def sync(self, bitrate, limit=None, **kwargs)
Add current Music library section as sync item for specified device. See description of :func:`plexapi.library.LibrarySection.search()` for details about filtering / sorting and :func:`plexapi.library.LibrarySection.sync()` for details on syncing libraries and possible exceptions. Parameters: bitrate (int): maximum bitrate for synchronized music, better use one of MUSIC_BITRATE_* values from the module :mod:`plexapi.sync`. limit (int): maximum count of tracks to sync, unlimited if `None`. Returns: :class:`plexapi.sync.SyncItem`: an instance of created syncItem. Example: .. code-block:: python from plexapi import myplex from plexapi.sync import AUDIO_BITRATE_320_KBPS c = myplex.MyPlexAccount() target = c.device('Plex Client') sync_items_wd = c.syncItems(target.clientIdentifier) srv = c.resource('Server Name').connect() section = srv.library.section('Music') section.sync(AUDIO_BITRATE_320_KBPS, client=target, limit=100, sort='addedAt:desc', title='New music')
6.537036
6.9421
0.941651
return self.search(libtype='photoalbum', title=title, **kwargs)
def searchAlbums(self, title, **kwargs)
Search for an album. See :func:`~plexapi.library.LibrarySection.search()` for usage.
9.052578
6.517747
1.388912
return self.search(libtype='photo', title=title, **kwargs)
def searchPhotos(self, title, **kwargs)
Search for a photo. See :func:`~plexapi.library.LibrarySection.search()` for usage.
7.522377
4.886683
1.539362
from plexapi.sync import Policy, MediaSettings kwargs['mediaSettings'] = MediaSettings.createPhoto(resolution) kwargs['policy'] = Policy.create(limit) return super(PhotoSection, self).sync(**kwargs)
def sync(self, resolution, limit=None, **kwargs)
Add current Music library section as sync item for specified device. See description of :func:`plexapi.library.LibrarySection.search()` for details about filtering / sorting and :func:`plexapi.library.LibrarySection.sync()` for details on syncing libraries and possible exceptions. Parameters: resolution (str): maximum allowed resolution for synchronized photos, see PHOTO_QUALITY_* values in the module :mod:`plexapi.sync`. limit (int): maximum count of tracks to sync, unlimited if `None`. Returns: :class:`plexapi.sync.SyncItem`: an instance of created syncItem. Example: .. code-block:: python from plexapi import myplex from plexapi.sync import PHOTO_QUALITY_HIGH c = myplex.MyPlexAccount() target = c.device('Plex Client') sync_items_wd = c.syncItems(target.clientIdentifier) srv = c.resource('Server Name').connect() section = srv.library.section('Photos') section.sync(PHOTO_QUALITY_HIGH, client=target, limit=100, sort='addedAt:desc', title='Fresh photos')
8.340396
7.94963
1.049155
self._data = data self.fastKey = data.attrib.get('fastKey') self.key = data.attrib.get('key') self.thumb = data.attrib.get('thumb') self.title = data.attrib.get('title') self.type = data.attrib.get('type')
def _loadData(self, data)
Load attribute values from Plex XML response.
2.98471
2.285633
1.305857
starttime = time.time() try: device = cls(baseurl=url, token=token, timeout=timeout) runtime = int(time.time() - starttime) results[i] = (url, token, device, runtime) if X_PLEX_ENABLE_FAST_CONNECT and job_is_done_event: job_is_done_event.set() except Exception as err: runtime = int(time.time() - starttime) log.error('%s: %s', url, err) results[i] = (url, token, None, runtime)
def _connect(cls, url, token, timeout, results, i, job_is_done_event=None)
Connects to the specified cls with url and token. Stores the connection information to results[i] in a threadsafe way. Arguments: cls: the class which is responsible for establishing connection, basically it's :class:`~plexapi.client.PlexClient` or :class:`~plexapi.server.PlexServer` url (str): url which should be passed as `baseurl` argument to cls.__init__() token (str): authentication token which should be passed as `baseurl` argument to cls.__init__() timeout (int): timeout which should be passed as `baseurl` argument to cls.__init__() results (list): pre-filled list for results i (int): index of current job, should be less than len(results) job_is_done_event (:class:`~threading.Event`): is X_PLEX_ENABLE_FAST_CONNECT is True then the event would be set as soon the connection is established
3.042795
2.355564
1.291748
# At this point we have a list of result tuples containing (url, token, PlexServer, runtime) # or (url, token, None, runtime) in the case a connection could not be established. for url, token, result, runtime in results: okerr = 'OK' if result else 'ERR' log.info('%s connection %s (%ss): %s?X-Plex-Token=%s', ctype, okerr, runtime, url, token) results = [r[2] for r in results if r and r[2] is not None] if results: log.info('Connecting to %s: %s?X-Plex-Token=%s', ctype, results[0]._baseurl, results[0]._token) return results[0] raise NotFound('Unable to connect to %s: %s' % (ctype.lower(), name))
def _chooseConnection(ctype, name, results)
Chooses the first (best) connection from the given _connect results.
4.148326
4.131224
1.00414
self._data = data self._token = logfilter.add_secret(data.attrib.get('authenticationToken')) self._webhooks = [] self.authenticationToken = self._token self.certificateVersion = data.attrib.get('certificateVersion') self.cloudSyncDevice = data.attrib.get('cloudSyncDevice') self.email = data.attrib.get('email') self.guest = utils.cast(bool, data.attrib.get('guest')) self.home = utils.cast(bool, data.attrib.get('home')) self.homeSize = utils.cast(int, data.attrib.get('homeSize')) self.id = data.attrib.get('id') self.locale = data.attrib.get('locale') self.mailing_list_status = data.attrib.get('mailing_list_status') self.maxHomeSize = utils.cast(int, data.attrib.get('maxHomeSize')) self.queueEmail = data.attrib.get('queueEmail') self.queueUid = data.attrib.get('queueUid') self.restricted = utils.cast(bool, data.attrib.get('restricted')) self.scrobbleTypes = data.attrib.get('scrobbleTypes') self.secure = utils.cast(bool, data.attrib.get('secure')) self.thumb = data.attrib.get('thumb') self.title = data.attrib.get('title') self.username = data.attrib.get('username') self.uuid = data.attrib.get('uuid') subscription = data.find('subscription') self.subscriptionActive = utils.cast(bool, subscription.attrib.get('active')) self.subscriptionStatus = subscription.attrib.get('status') self.subscriptionPlan = subscription.attrib.get('plan') self.subscriptionFeatures = [] for feature in subscription.iter('feature'): self.subscriptionFeatures.append(feature.attrib.get('id')) roles = data.find('roles') self.roles = [] if roles: for role in roles.iter('role'): self.roles.append(role.attrib.get('id')) entitlements = data.find('entitlements') self.entitlements = [] for entitlement in entitlements.iter('entitlement'): self.entitlements.append(entitlement.attrib.get('id')) # TODO: Fetch missing MyPlexAccount attributes self.profile_settings = None self.services = None self.joined_at = None
def _loadData(self, data)
Load attribute values from Plex XML response.
2.396419
2.280022
1.051051
for device in self.devices(): if device.name.lower() == name.lower(): return device raise NotFound('Unable to find device %s' % name)
def device(self, name)
Returns the :class:`~plexapi.myplex.MyPlexDevice` that matches the name specified. Parameters: name (str): Name to match against.
3.549256
3.943036
0.900133
data = self.query(MyPlexDevice.key) return [MyPlexDevice(self, elem) for elem in data]
def devices(self)
Returns a list of all :class:`~plexapi.myplex.MyPlexDevice` objects connected to the server.
9.195364
4.745049
1.937886
for resource in self.resources(): if resource.name.lower() == name.lower(): return resource raise NotFound('Unable to find resource %s' % name)
def resource(self, name)
Returns the :class:`~plexapi.myplex.MyPlexResource` that matches the name specified. Parameters: name (str): Name to match against.
3.398226
3.968923
0.856209
data = self.query(MyPlexResource.key) return [MyPlexResource(self, elem) for elem in data]
def resources(self)
Returns a list of all :class:`~plexapi.myplex.MyPlexResource` objects connected to the server.
9.776494
4.81893
2.028769
username = user.username if isinstance(user, MyPlexUser) else user machineId = server.machineIdentifier if isinstance(server, PlexServer) else server sectionIds = self._getSectionIds(machineId, sections) params = { 'server_id': machineId, 'shared_server': {'library_section_ids': sectionIds, 'invited_email': username}, 'sharing_settings': { 'allowSync': ('1' if allowSync else '0'), 'allowCameraUpload': ('1' if allowCameraUpload else '0'), 'allowChannels': ('1' if allowChannels else '0'), 'filterMovies': self._filterDictToStr(filterMovies or {}), 'filterTelevision': self._filterDictToStr(filterTelevision or {}), 'filterMusic': self._filterDictToStr(filterMusic or {}), }, } headers = {'Content-Type': 'application/json'} url = self.FRIENDINVITE.format(machineId=machineId) return self.query(url, self._session.post, json=params, headers=headers)
def inviteFriend(self, user, server, sections=None, allowSync=False, allowCameraUpload=False, allowChannels=False, filterMovies=None, filterTelevision=None, filterMusic=None)
Share library content with the specified user. Parameters: user (str): MyPlexUser, username, email of the user to be added. server (PlexServer): PlexServer object or machineIdentifier containing the library sections to share. sections ([Section]): Library sections, names or ids to be shared (default None shares all sections). allowSync (Bool): Set True to allow user to sync content. allowCameraUpload (Bool): Set True to allow user to upload photos. allowChannels (Bool): Set True to allow user to utilize installed channels. filterMovies (Dict): Dict containing key 'contentRating' and/or 'label' each set to a list of values to be filtered. ex: {'contentRating':['G'], 'label':['foo']} filterTelevision (Dict): Dict containing key 'contentRating' and/or 'label' each set to a list of values to be filtered. ex: {'contentRating':['G'], 'label':['foo']} filterMusic (Dict): Dict containing key 'label' set to a list of values to be filtered. ex: {'label':['foo']}
2.69788
2.4924
1.082442
user = self.user(user) url = self.FRIENDUPDATE if user.friend else self.REMOVEINVITE url = url.format(userId=user.id) return self.query(url, self._session.delete)
def removeFriend(self, user)
Remove the specified user from all sharing. Parameters: user (str): MyPlexUser, username, email of the user to be added.
7.379428
8.339893
0.884835
# Update friend servers response_filters = '' response_servers = '' user = user if isinstance(user, MyPlexUser) else self.user(user) machineId = server.machineIdentifier if isinstance(server, PlexServer) else server sectionIds = self._getSectionIds(machineId, sections) headers = {'Content-Type': 'application/json'} # Determine whether user has access to the shared server. user_servers = [s for s in user.servers if s.machineIdentifier == machineId] if user_servers and sectionIds: serverId = user_servers[0].id params = {'server_id': machineId, 'shared_server': {'library_section_ids': sectionIds}} url = self.FRIENDSERVERS.format(machineId=machineId, serverId=serverId) else: params = {'server_id': machineId, 'shared_server': {'library_section_ids': sectionIds, "invited_id": user.id}} url = self.FRIENDINVITE.format(machineId=machineId) # Remove share sections, add shares to user without shares, or update shares if not user_servers or sectionIds: if removeSections is True: response_servers = self.query(url, self._session.delete, json=params, headers=headers) elif 'invited_id' in params.get('shared_server', ''): response_servers = self.query(url, self._session.post, json=params, headers=headers) else: response_servers = self.query(url, self._session.put, json=params, headers=headers) else: log.warning('Section name, number of section object is required changing library sections') # Update friend filters url = self.FRIENDUPDATE.format(userId=user.id) params = {} if isinstance(allowSync, bool): params['allowSync'] = '1' if allowSync else '0' if isinstance(allowCameraUpload, bool): params['allowCameraUpload'] = '1' if allowCameraUpload else '0' if isinstance(allowChannels, bool): params['allowChannels'] = '1' if allowChannels else '0' if isinstance(filterMovies, dict): params['filterMovies'] = self._filterDictToStr(filterMovies or {}) # '1' if allowChannels else '0' if isinstance(filterTelevision, dict): params['filterTelevision'] = self._filterDictToStr(filterTelevision or {}) if isinstance(allowChannels, dict): params['filterMusic'] = self._filterDictToStr(filterMusic or {}) if params: url += joinArgs(params) response_filters = self.query(url, self._session.put) return response_servers, response_filters
def updateFriend(self, user, server, sections=None, removeSections=False, allowSync=None, allowCameraUpload=None, allowChannels=None, filterMovies=None, filterTelevision=None, filterMusic=None)
Update the specified user's share settings. Parameters: user (str): MyPlexUser, username, email of the user to be added. server (PlexServer): PlexServer object or machineIdentifier containing the library sections to share. sections: ([Section]): Library sections, names or ids to be shared (default None shares all sections). removeSections (Bool): Set True to remove all shares. Supersedes sections. allowSync (Bool): Set True to allow user to sync content. allowCameraUpload (Bool): Set True to allow user to upload photos. allowChannels (Bool): Set True to allow user to utilize installed channels. filterMovies (Dict): Dict containing key 'contentRating' and/or 'label' each set to a list of values to be filtered. ex: {'contentRating':['G'], 'label':['foo']} filterTelevision (Dict): Dict containing key 'contentRating' and/or 'label' each set to a list of values to be filtered. ex: {'contentRating':['G'], 'label':['foo']} filterMusic (Dict): Dict containing key 'label' set to a list of values to be filtered. ex: {'label':['foo']}
3.027499
2.867797
1.055688
for user in self.users(): # Home users don't have email, username etc. if username.lower() == user.title.lower(): return user elif (user.username and user.email and user.id and username.lower() in (user.username.lower(), user.email.lower(), str(user.id))): return user raise NotFound('Unable to find user %s' % username)
def user(self, username)
Returns the :class:`~plexapi.myplex.MyPlexUser` that matches the email or username specified. Parameters: username (str): Username, email or id of the user to return.
5.148738
4.15355
1.2396
friends = [MyPlexUser(self, elem) for elem in self.query(MyPlexUser.key)] requested = [MyPlexUser(self, elem, self.REQUESTED) for elem in self.query(self.REQUESTED)] return friends + requested
def users(self)
Returns a list of all :class:`~plexapi.myplex.MyPlexUser` objects connected to your account. This includes both friends and pending invites. You can reference the user.friend to distinguish between the two.
7.074222
5.343433
1.323909
if not sections: return [] # Get a list of all section ids for looking up each section. allSectionIds = {} machineIdentifier = server.machineIdentifier if isinstance(server, PlexServer) else server url = self.PLEXSERVERS.replace('{machineId}', machineIdentifier) data = self.query(url, self._session.get) for elem in data[0]: allSectionIds[elem.attrib.get('id', '').lower()] = elem.attrib.get('id') allSectionIds[elem.attrib.get('title', '').lower()] = elem.attrib.get('id') allSectionIds[elem.attrib.get('key', '').lower()] = elem.attrib.get('id') log.debug(allSectionIds) # Convert passed in section items to section ids from above lookup sectionIds = [] for section in sections: sectionKey = section.key if isinstance(section, LibrarySection) else section sectionIds.append(allSectionIds[sectionKey.lower()]) return sectionIds
def _getSectionIds(self, server, sections)
Converts a list of section objects or names to sectionIds needed for library sharing.
3.512334
3.353789
1.047273
values = [] for key, vals in filterDict.items(): if key not in ('contentRating', 'label'): raise BadRequest('Unknown filter key: %s', key) values.append('%s=%s' % (key, '%2C'.join(vals))) return '|'.join(values)
def _filterDictToStr(self, filterDict)
Converts friend filters to a string representation for transport.
4.636137
4.359494
1.063457
params = {} if playback is not None: params['optOutPlayback'] = int(playback) if library is not None: params['optOutLibraryStats'] = int(library) url = 'https://plex.tv/api/v2/user/privacy' return self.query(url, method=self._session.put, data=params)
def optOut(self, playback=None, library=None)
Opt in or out of sharing stuff with plex. See: https://www.plex.tv/about/privacy-legal/
3.525741
3.087982
1.141762
if client: clientId = client.clientIdentifier elif clientId is None: clientId = X_PLEX_IDENTIFIER data = self.query(SyncList.key.format(clientId=clientId)) return SyncList(self, data)
def syncItems(self, client=None, clientId=None)
Returns an instance of :class:`plexapi.sync.SyncList` for specified client. Parameters: client (:class:`~plexapi.myplex.MyPlexDevice`): a client to query SyncItems for. clientId (str): an identifier of a client to query SyncItems for. If both `client` and `clientId` provided the client would be preferred. If neither `client` nor `clientId` provided the clientId would be set to current clients`s identifier.
8.044926
5.617346
1.432158
if not client and not clientId: clientId = X_PLEX_IDENTIFIER if not client: for device in self.devices(): if device.clientIdentifier == clientId: client = device break if not client: raise BadRequest('Unable to find client by clientId=%s', clientId) if 'sync-target' not in client.provides: raise BadRequest('Received client doesn`t provides sync-target') params = { 'SyncItem[title]': sync_item.title, 'SyncItem[rootTitle]': sync_item.rootTitle, 'SyncItem[metadataType]': sync_item.metadataType, 'SyncItem[machineIdentifier]': sync_item.machineIdentifier, 'SyncItem[contentType]': sync_item.contentType, 'SyncItem[Policy][scope]': sync_item.policy.scope, 'SyncItem[Policy][unwatched]': str(int(sync_item.policy.unwatched)), 'SyncItem[Policy][value]': str(sync_item.policy.value if hasattr(sync_item.policy, 'value') else 0), 'SyncItem[Location][uri]': sync_item.location, 'SyncItem[MediaSettings][audioBoost]': str(sync_item.mediaSettings.audioBoost), 'SyncItem[MediaSettings][maxVideoBitrate]': str(sync_item.mediaSettings.maxVideoBitrate), 'SyncItem[MediaSettings][musicBitrate]': str(sync_item.mediaSettings.musicBitrate), 'SyncItem[MediaSettings][photoQuality]': str(sync_item.mediaSettings.photoQuality), 'SyncItem[MediaSettings][photoResolution]': sync_item.mediaSettings.photoResolution, 'SyncItem[MediaSettings][subtitleSize]': str(sync_item.mediaSettings.subtitleSize), 'SyncItem[MediaSettings][videoQuality]': str(sync_item.mediaSettings.videoQuality), 'SyncItem[MediaSettings][videoResolution]': sync_item.mediaSettings.videoResolution, } url = SyncList.key.format(clientId=client.clientIdentifier) data = self.query(url, method=self._session.post, headers={ 'Content-type': 'x-www-form-urlencoded', }, params=params) return SyncItem(self, data, None, clientIdentifier=client.clientIdentifier)
def sync(self, sync_item, client=None, clientId=None)
Adds specified sync item for the client. It's always easier to use methods defined directly in the media objects, e.g. :func:`plexapi.video.Video.sync`, :func:`plexapi.audio.Audio.sync`. Parameters: client (:class:`~plexapi.myplex.MyPlexDevice`): a client for which you need to add SyncItem to. clientId (str): an identifier of a client for which you need to add SyncItem to. sync_item (:class:`plexapi.sync.SyncItem`): prepared SyncItem object with all fields set. If both `client` and `clientId` provided the client would be preferred. If neither `client` nor `clientId` provided the clientId would be set to current clients`s identifier. Returns: :class:`plexapi.sync.SyncItem`: an instance of created syncItem. Raises: :class:`plexapi.exceptions.BadRequest`: when client with provided clientId wasn`t found. :class:`plexapi.exceptions.BadRequest`: provided client doesn`t provides `sync-target`.
2.516849
2.229516
1.128877
response = self._session.get('https://plex.tv/api/claim/token.json', headers=self._headers(), timeout=TIMEOUT) if response.status_code not in (200, 201, 204): # pragma: no cover codename = codes.get(response.status_code)[0] errtext = response.text.replace('\n', ' ') log.warning('BadRequest (%s) %s %s; %s' % (response.status_code, codename, response.url, errtext)) raise BadRequest('(%s) %s %s; %s' % (response.status_code, codename, response.url, errtext)) return response.json()['token']
def claimToken(self)
Returns a str, a new "claim-token", which you can use to register your new Plex Server instance to your account. See: https://hub.docker.com/r/plexinc/pms-docker/, https://www.plex.tv/claim/
3.10104
2.983124
1.039527
self._data = data self.friend = self._initpath == self.key self.allowCameraUpload = utils.cast(bool, data.attrib.get('allowCameraUpload')) self.allowChannels = utils.cast(bool, data.attrib.get('allowChannels')) self.allowSync = utils.cast(bool, data.attrib.get('allowSync')) self.email = data.attrib.get('email') self.filterAll = data.attrib.get('filterAll') self.filterMovies = data.attrib.get('filterMovies') self.filterMusic = data.attrib.get('filterMusic') self.filterPhotos = data.attrib.get('filterPhotos') self.filterTelevision = data.attrib.get('filterTelevision') self.home = utils.cast(bool, data.attrib.get('home')) self.id = utils.cast(int, data.attrib.get('id')) self.protected = utils.cast(bool, data.attrib.get('protected')) self.recommendationsPlaylistId = data.attrib.get('recommendationsPlaylistId') self.restricted = data.attrib.get('restricted') self.thumb = data.attrib.get('thumb') self.title = data.attrib.get('title', '') self.username = data.attrib.get('username', '') self.servers = self.findItems(data, MyPlexServerShare)
def _loadData(self, data)
Load attribute values from Plex XML response.
2.714917
2.49869
1.086536
self._data = data self.id = utils.cast(int, data.attrib.get('id')) self.serverId = utils.cast(int, data.attrib.get('serverId')) self.machineIdentifier = data.attrib.get('machineIdentifier') self.name = data.attrib.get('name') self.lastSeenAt = utils.toDatetime(data.attrib.get('lastSeenAt')) self.numLibraries = utils.cast(int, data.attrib.get('numLibraries')) self.allLibraries = utils.cast(bool, data.attrib.get('allLibraries')) self.owned = utils.cast(bool, data.attrib.get('owned')) self.pending = utils.cast(bool, data.attrib.get('pending'))
def _loadData(self, data)
Load attribute values from Plex XML response.
2.329038
1.902335
1.224305
# Sort connections from (https, local) to (http, remote) # Only check non-local connections unless we own the resource connections = sorted(self.connections, key=lambda c: c.local, reverse=True) owned_or_unowned_non_local = lambda x: self.owned or (not self.owned and not x.local) https = [c.uri for c in connections if owned_or_unowned_non_local(c)] http = [c.httpuri for c in connections if owned_or_unowned_non_local(c)] cls = PlexServer if 'server' in self.provides else PlexClient # Force ssl, no ssl, or any (default) if ssl is True: connections = https elif ssl is False: connections = http else: connections = https + http # Try connecting to all known resource connections in parellel, but # only return the first server (in order) that provides a response. listargs = [[cls, url, self.accessToken, timeout] for url in connections] log.info('Testing %s resource connections..', len(listargs)) results = utils.threaded(_connect, listargs) return _chooseConnection('Resource', self.name, results)
def connect(self, ssl=None, timeout=None)
Returns a new :class:`~server.PlexServer` or :class:`~client.PlexClient` object. Often times there is more than one address specified for a server or client. This function will prioritize local connections before remote and HTTPS before HTTP. After trying to connect to all available addresses for this resource and assuming at least one connection was successful, the PlexServer object is built and returned. Parameters: ssl (optional): Set True to only connect to HTTPS connections. Set False to only connect to HTTP connections. Set None (default) to connect to any HTTP or HTTPS connection. Raises: :class:`plexapi.exceptions.NotFound`: When unable to connect to any addresses for this resource.
7.085119
6.52917
1.085148
cls = PlexServer if 'server' in self.provides else PlexClient listargs = [[cls, url, self.token, timeout] for url in self.connections] log.info('Testing %s device connections..', len(listargs)) results = utils.threaded(_connect, listargs) return _chooseConnection('Device', self.name, results)
def connect(self, timeout=None)
Returns a new :class:`~plexapi.client.PlexClient` or :class:`~plexapi.server.PlexServer` Sometimes there is more than one address specified for a server or client. After trying to connect to all available addresses for this client and assuming at least one connection was successful, the PlexClient object is built and returned. Raises: :class:`plexapi.exceptions.NotFound`: When unable to connect to any addresses for this device.
13.099417
10.157586
1.289619
key = 'https://plex.tv/devices/%s.xml' % self.id self._server.query(key, self._server._session.delete)
def delete(self)
Remove this device from your account.
9.625417
7.576221
1.270477
if 'sync-target' not in self.provides: raise BadRequest('Requested syncList for device which do not provides sync-target') return self._server.syncItems(client=self)
def syncItems(self)
Returns an instance of :class:`plexapi.sync.SyncList` for current device. Raises: :class:`plexapi.exceptions.BadRequest`: when the device doesn`t provides `sync-target`.
22.617655
10.267769
2.202782
key = self.firstAttr('thumb', 'parentThumb', 'granparentThumb') return self._server.url(key, includeToken=True) if key else None
def thumbUrl(self)
Return url to for the thumbnail image.
18.749662
16.620363
1.128114
args = {} args['includeChapters'] = includeChapters args['includeRelated'] = includeRelated args['repeat'] = repeat args['shuffle'] = shuffle if item.type == 'playlist': args['playlistID'] = item.ratingKey args['type'] = item.playlistType else: uuid = item.section().uuid args['key'] = item.key args['type'] = item.listType args['uri'] = 'library://%s/item/%s' % (uuid, item.key) path = '/playQueues%s' % utils.joinArgs(args) data = server.query(path, method=server._session.post) c = cls(server, data, initpath=path) # we manually add a key so we can pass this to playMedia # since the data, does not contain a key. c.key = item.key return c
def create(cls, server, item, shuffle=0, repeat=0, includeChapters=1, includeRelated=1)
Create and returns a new :class:`~plexapi.playqueue.PlayQueue`. Paramaters: server (:class:`~plexapi.server.PlexServer`): Server you are connected to. item (:class:`~plexapi.media.Media` or class:`~plexapi.playlist.Playlist`): A media or Playlist. shuffle (int, optional): Start the playqueue shuffled. repeat (int, optional): Start the playqueue shuffled. includeChapters (int, optional): include Chapters. includeRelated (int, optional): include Related.
4.574521
4.238341
1.079319
deleted = 0 print('%s Cleaning %s to %s episodes.' % (datestr(), show.title, keep)) sort = lambda x:x.originallyAvailableAt or x.addedAt items = sorted(show.episodes(), key=sort, reverse=True) for episode in items[keep:]: delete_episode(episode) deleted += 1 return deleted
def keep_episodes(show, keep)
Delete all but last count episodes in show.
4.753673
4.369187
1.087999
deleted = 0 print('%s Cleaning %s to latest season.' % (datestr(), show.title)) for season in show.seasons()[:-1]: for episode in season.episodes(): delete_episode(episode) deleted += 1 return deleted
def keep_season(show, keep)
Keep only the latest season.
5.672973
5.146847
1.102223
try: os.makedirs(name, mode) except OSError: if not os.path.isdir(name) or not exist_ok: raise
def makedirs(name, mode=0o777, exist_ok=False)
Mimicks os.makedirs() from Python 3.
2.003907
2.108084
0.950582
if not email_messages: return with self._lock: try: stream_created = self.open() for message in email_messages: self.write_to_stream(message) self.stream.flush() # flush after each message if stream_created: self.close() except Exception: if not self.fail_silently: raise
def echo_to_output_stream(self, email_messages)
Write all messages to the stream in a thread-safe way.
3.442162
3.134326
1.098215
def set_prop(attachment, prop_name, value): if SENDGRID_VERSION < '6': setattr(attachment, prop_name, value) else: if prop_name == "filename": prop_name = "name" setattr(attachment, 'file_{}'.format(prop_name), value) sg_attch = Attachment() if isinstance(django_attch, MIMEBase): filename = django_attch.get_filename() if not filename: ext = mimetypes.guess_extension(django_attch.get_content_type()) filename = "part-{0}{1}".format(uuid.uuid4().hex, ext) set_prop(sg_attch, "filename", filename) # todo: Read content if stream? set_prop(sg_attch, "content", django_attch.get_payload().replace("\n", "")) set_prop(sg_attch, "type", django_attch.get_content_type()) content_id = django_attch.get("Content-ID") if content_id: # Strip brackets since sendgrid's api adds them if content_id.startswith("<") and content_id.endswith(">"): content_id = content_id[1:-1] # These 2 properties did not change in v6, so we set them the usual way sg_attch.content_id = content_id sg_attch.disposition = "inline" else: filename, content, mimetype = django_attch set_prop(sg_attch, "filename", filename) # Convert content from chars to bytes, in both Python 2 and 3. # todo: Read content if stream? if isinstance(content, str): content = content.encode('utf-8') set_prop(sg_attch, "content", base64.b64encode(content).decode()) set_prop(sg_attch, "type", mimetype) return sg_attch
def _create_sg_attachment(self, django_attch)
Handles the conversion between a django attachment object and a sendgrid attachment object. Due to differences between sendgrid's API versions, use this method when constructing attachments to ensure that attachments get properly instantiated.
2.617781
2.493454
1.049861
result = [] #for elem in path[:-1]: cur = obj for elem in path[:-1]: if ((issubclass(cur.__class__, MutableMapping) and elem in cur)): result.append([elem, cur[elem].__class__]) cur = cur[elem] elif (issubclass(cur.__class__, MutableSequence) and int(elem) < len(cur)): elem = int(elem) result.append([elem, cur[elem].__class__]) cur = cur[elem] else: result.append([elem, dict]) try: try: result.append([path[-1], cur[path[-1]].__class__]) except TypeError: result.append([path[-1], cur[int(path[-1])].__class__]) except (KeyError, IndexError): result.append([path[-1], path[-1].__class__]) return result
def path_types(obj, path)
Given a list of path name elements, return anew list of [name, type] path components, given the reference object.
2.213232
2.095089
1.056391
validated = [] for elem in path: key = elem[0] strkey = str(key) if (regex and (not regex.findall(strkey))): raise dpath.exceptions.InvalidKeyName("{} at {} does not match the expression {}" "".format(strkey, validated, regex.pattern)) validated.append(strkey)
def validate(path, regex=None)
Validate that all the keys in the given list of path components are valid, given that they do not contain the separator, and match any optional regex given.
6.29466
5.741589
1.096327
if isinstance(obj, MutableMapping): # Python 3 support if PY3: iteritems = obj.items() string_class = str else: # Default to PY2 iteritems = obj.iteritems() string_class = basestring for (k, v) in iteritems: if issubclass(k.__class__, (string_class)): if (not k) and (not dpath.options.ALLOW_EMPTY_STRING_KEYS): raise dpath.exceptions.InvalidKeyName("Empty string keys not allowed without " "dpath.options.ALLOW_EMPTY_STRING_KEYS=True") elif (skip and k[0] == '+'): continue newpath = path + [[k, v.__class__]] validate(newpath) if dirs: yield newpath for child in paths(v, dirs, leaves, newpath, skip): yield child elif isinstance(obj, MutableSequence): for (i, v) in enumerate(obj): newpath = path + [[i, v.__class__]] if dirs: yield newpath for child in paths(obj[i], dirs, leaves, newpath, skip): yield child elif leaves: yield path + [[obj, obj.__class__]] elif not dirs: yield path
def paths(obj, dirs=True, leaves=True, path=[], skip=False)
Yield all paths of the object. Arguments: obj -- An object to get paths from. Keyword Arguments: dirs -- Yield intermediate paths. leaves -- Yield the paths with leaf objects. path -- A list of keys representing the path. skip -- Skip special keys beginning with '+'.
3.148318
3.154193
0.998137
path_len = len(path) glob_len = len(glob) ss = -1 ss_glob = glob if '**' in glob: ss = glob.index('**') if '**' in glob[ss + 1:]: raise dpath.exceptions.InvalidGlob("Invalid glob. Only one '**' is permitted per glob.") if path_len >= glob_len: # Just right or more stars. more_stars = ['*'] * (path_len - glob_len + 1) ss_glob = glob[:ss] + more_stars + glob[ss + 1:] elif path_len == glob_len - 1: # Need one less star. ss_glob = glob[:ss] + glob[ss + 1:] if path_len == len(ss_glob): # Python 3 support if PY3: return all(map(fnmatch.fnmatch, list(map(str, paths_only(path))), list(map(str, ss_glob)))) else: # Default to Python 2 return all(map(fnmatch.fnmatch, map(str, paths_only(path)), map(str, ss_glob))) return False
def match(path, glob)
Match the path with the glob. Arguments: path -- A list of keys representing the path. glob -- A list of globs to match against the path.
3.347693
3.428583
0.976407
cur = obj traversed = [] def _presence_test_dict(obj, elem): return (elem[0] in obj) def _create_missing_dict(obj, elem): obj[elem[0]] = elem[1]() def _presence_test_list(obj, elem): return (int(str(elem[0])) < len(obj)) def _create_missing_list(obj, elem): idx = int(str(elem[0])) while (len(obj)-1) < idx: obj.append(None) def _accessor_dict(obj, elem): return obj[elem[0]] def _accessor_list(obj, elem): return obj[int(str(elem[0]))] def _assigner_dict(obj, elem, value): obj[elem[0]] = value def _assigner_list(obj, elem, value): obj[int(str(elem[0]))] = value elem = None for elem in path: elem_value = elem[0] elem_type = elem[1] tester = None creator = None accessor = None assigner = None if issubclass(obj.__class__, (MutableMapping)): tester = _presence_test_dict creator = _create_missing_dict accessor = _accessor_dict assigner = _assigner_dict elif issubclass(obj.__class__, MutableSequence): if not str(elem_value).isdigit(): raise TypeError("Can only create integer indexes in lists, " "not {}, in {}".format(type(obj), traversed ) ) tester = _presence_test_list creator = _create_missing_list accessor = _accessor_list assigner = _assigner_list else: raise TypeError("Unable to path into elements of type {} " "at {}".format(obj, traversed)) if (not tester(obj, elem)) and (create_missing): creator(obj, elem) elif (not tester(obj, elem)): raise dpath.exceptions.PathNotFound( "{} does not exist in {}".format( elem, traversed ) ) traversed.append(elem_value) if len(traversed) < len(path): obj = accessor(obj, elem) if elem is None: return if (afilter and afilter(accessor(obj, elem))) or (not afilter): assigner(obj, elem, value)
def set(obj, path, value, create_missing=True, afilter=None)
Set the value of the given path in the object. Path must be a list of specific path elements, not a glob. You can use dpath.util.set for globs, but the paths must slready exist. If create_missing is True (the default behavior), then any missing path components in the dictionary are made silently. Otherwise, if False, an exception is thrown if path components are missing.
2.431985
2.540226
0.957389
index = 0 path_count = len(path) - 1 target = obj head = type(target)() tail = head up = None for pair in path: key = pair[0] target = target[key] if view: if isinstance(tail, MutableMapping): if issubclass(pair[1], (MutableSequence, MutableMapping)) and index != path_count: tail[key] = pair[1]() else: tail[key] = target up = tail tail = tail[key] elif issubclass(tail.__class__, MutableSequence): if issubclass(pair[1], (MutableSequence, MutableMapping)) and index != path_count: tail.append(pair[1]()) else: tail.append(target) up = tail tail = tail[-1] if not issubclass(target.__class__, (MutableSequence, MutableMapping)): if (afilter and (not afilter(target))): raise dpath.exceptions.FilteredValue index += 1 if view: return head else: return target
def get(obj, path, view=False, afilter=None)
Get the value of the given path. Arguments: obj -- Object to look in. path -- A list of keys representing the path. Keyword Arguments: view -- Return a view of the object.
2.854551
3.057146
0.933731
pathlist = __safe_path__(path, separator) pathobj = dpath.path.path_types(obj, pathlist) return dpath.path.set(obj, pathobj, value, create_missing=True)
def new(obj, path, value, separator="/")
Set the element at the terminus of path to value, and create it if it does not exist (as opposed to 'set' that can only change existing keys). path will NOT be treated like a glob. If it has globbing characters in it, they will become part of the resulting keys
7.177568
7.714063
0.930452
deleted = 0 paths = [] globlist = __safe_path__(glob, separator) for path in _inner_search(obj, globlist, separator): # These are yielded back, don't mess up the dict. paths.append(path) for path in paths: cur = obj prev = None for item in path: prev = cur try: cur = cur[item[0]] except AttributeError as e: # This only happens when we delete X/Y and the next # item in the paths is X/Y/Z pass if (not afilter) or (afilter and afilter(prev[item[0]])): prev.pop(item[0]) deleted += 1 if not deleted: raise dpath.exceptions.PathNotFound("Could not find {0} to delete it".format(glob)) return deleted
def delete(obj, glob, separator="/", afilter=None)
Given a path glob, delete all elements that match the glob. Returns the number of deleted objects. Raises PathNotFound if no paths are found to delete.
5.540024
5.641544
0.982005
changed = 0 globlist = __safe_path__(glob, separator) for path in _inner_search(obj, globlist, separator): changed += 1 dpath.path.set(obj, path, value, create_missing=False, afilter=afilter) return changed
def set(obj, glob, value, separator="/", afilter=None)
Given a path glob, set all existing elements in the document to the given value. Returns the number of elements changed.
6.380233
5.948278
1.072619
ret = None found = False for item in search(obj, glob, yielded=True, separator=separator): if ret is not None: raise ValueError("dpath.util.get() globs must match only one leaf : %s" % glob) ret = item[1] found = True if found is False: raise KeyError(glob) return ret
def get(obj, glob, separator="/")
Given an object which contains only one possible match for the given glob, return the value for the leaf matching the given glob. If more than one leaf matches the glob, ValueError is raised. If the glob is not found, KeyError is raised.
4.843939
4.87417
0.993798
return [x[1] for x in dpath.util.search(obj, glob, yielded=True, separator=separator, afilter=afilter, dirs=dirs)]
def values(obj, glob, separator="/", afilter=None, dirs=True)
Given an object and a path glob, return an array of all values which match the glob. The arguments to this function are identical to those of search(), and it is primarily a shorthand for a list comprehension over a yielded search call.
4.697939
3.354512
1.400483
def _search_view(obj, glob, separator, afilter, dirs): view = {} globlist = __safe_path__(glob, separator) for path in _inner_search(obj, globlist, separator, dirs=dirs): try: val = dpath.path.get(obj, path, afilter=afilter, view=True) merge(view, val) except dpath.exceptions.FilteredValue: pass return view def _search_yielded(obj, glob, separator, afilter, dirs): globlist = __safe_path__(glob, separator) for path in _inner_search(obj, globlist, separator, dirs=dirs): try: val = dpath.path.get(obj, path, view=False, afilter=afilter) yield (separator.join(map(str, dpath.path.paths_only(path))), val) except dpath.exceptions.FilteredValue: pass if afilter is not None: dirs = False if yielded: return _search_yielded(obj, glob, separator, afilter, dirs) return _search_view(obj, glob, separator, afilter, dirs)
def search(obj, glob, yielded=False, separator="/", afilter=None, dirs = True)
Given a path glob, return a dictionary containing all keys that matched the given glob. If 'yielded' is true, then a dictionary will not be returned. Instead tuples will be yielded in the form of (path, value) for every element in the document that matched the glob.
2.601866
2.651923
0.981124
for path in dpath.path.paths(obj, dirs, leaves, skip=True): if dpath.path.match(path, glob): yield path
def _inner_search(obj, glob, separator, dirs=True, leaves=False)
Search the object paths that match the glob.
6.403387
5.095206
1.256747
if afilter: # Having merge do its own afiltering is dumb, let search do the # heavy lifting for us. src = search(src, '**', afilter=afilter) return merge(dst, src) def _check_typesafe(obj1, obj2, key, path): if not key in obj1: return elif ( (flags & MERGE_TYPESAFE == MERGE_TYPESAFE) and (type(obj1[key]) != type(obj2[key]))): raise TypeError("Cannot merge objects of type {0} and {1} at {2}" "".format(type(obj1[key]), type(obj2[key]), path)) elif ( (flags & MERGE_TYPESAFE != MERGE_TYPESAFE) and (type(obj1[key]) != type(obj2[key]))): obj1.pop(key) if isinstance(src, MutableMapping): for (i, v) in enumerate(src): _check_typesafe(dst, src, v, separator.join([_path, str(v)])) if not v in dst: dst[v] = src[v] else: if not isinstance(src[v], (MutableMapping, MutableSequence)): dst[v] = src[v] else: merge(dst[v], src[v], afilter=afilter, flags=flags, _path=separator.join([_path, str(v)]), separator=separator) elif isinstance(src, MutableSequence): for (i, v) in enumerate(src): _check_typesafe(dst, src, i, separator.join([_path, str(i)])) dsti = i if ( flags & MERGE_ADDITIVE): dsti = len(dst) if dsti >= len(dst): dst += [None] * (dsti - (len(dst) - 1)) if dst[dsti] == None: dst[dsti] = src[i] else: if not isinstance(src[i], (MutableMapping, MutableSequence)): dst[dsti] = src[i] else: merge(dst[i], src[i], afilter=afilter, flags=flags, _path=separator.join([_path, str(i)]), separator=separator)
def merge(dst, src, separator="/", afilter=None, flags=MERGE_ADDITIVE, _path="")
Merge source into destination. Like dict.update() but performs deep merging. flags is an OR'ed combination of MERGE_ADDITIVE, MERGE_REPLACE, or MERGE_TYPESAFE. * MERGE_ADDITIVE : List objects are combined onto one long list (NOT a set). This is the default flag. * MERGE_REPLACE : Instead of combining list objects, when 2 list objects are at an equal depth of merge, replace the destination with the source. * MERGE_TYPESAFE : When 2 keys at equal levels are of different types, raise a TypeError exception. By default, the source replaces the destination in this situation.
2.340805
2.209358
1.059495
reversed_morsetab = {symbol: character for character, symbol in list(getattr(encoding, 'morsetab').items())} encoding_type = encoding_type.lower() allowed_encoding_type = ['default', 'binary'] if encoding_type == 'default': # For spacing the words letters = 0 words = 0 index = {} for i in range(len(code)): if code[i:i + 3] == ' ' * 3: if code[i:i + 7] == ' ' * 7: words += 1 letters += 1 index[words] = letters elif code[i + 4] and code[i - 1] != ' ': # Check for ' ' letters += 1 message = [reversed_morsetab[i] for i in code.split()] for i, (word, letter) in enumerate(list(index.items())): message.insert(letter + i, ' ') return ''.join(message) elif encoding_type == 'binary': lst = list(map(lambda word: word.split('0' * 3), code.split('0' * 7))) # list of list of character (each sub list being a word) for i, word in enumerate(lst): for j, bin_letter in enumerate(word): lst[i][j] = binary_lookup[bin_letter] lst[i] = "".join(lst[i]) s = " ".join(lst) return s else: raise NotImplementedError("encoding_type must be in %s" % allowed_encoding_type)
def decode(code, encoding_type='default')
Converts a string of morse code into English message The encoded message can also be decoded using the same morse chart backwards. >>> code = '... --- ...' >>> decode(code) 'SOS'
3.994851
4.024278
0.992688
"grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx" args = [iter(iterable)] * n return zip_longest(fillvalue=fillvalue, *args)
def grouper(n, iterable, fillvalue=None)
grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx
2.146338
2.617927
0.819862
''' create a generator which computes the samples. essentially it creates a sequence of the sum of each function in the channel at each sample in the file for each channel. ''' return islice(izip(*(imap(sum, izip(*channel)) for channel in channels)), nsamples)
def compute_samples(channels, nsamples=None)
create a generator which computes the samples. essentially it creates a sequence of the sum of each function in the channel at each sample in the file for each channel.
13.131832
3.06629
4.282645
"Write samples to a wavefile." if nframes is None: nframes = 0 w = wave.open(f, 'wb') w.setparams((nchannels, sampwidth, framerate, nframes, 'NONE', 'not compressed')) max_amplitude = float(int((2 ** (sampwidth * 8)) / 2) - 1) # split the samples into chunks (to reduce memory consumption and improve performance) for chunk in grouper(bufsize, samples): frames = b''.join(b''.join(struct.pack('h', int(max_amplitude * sample)) for sample in channels) for channels in chunk if channels is not None) w.writeframesraw(frames) w.close()
def write_wavefile(f, samples, nframes=None, nchannels=2, sampwidth=2, framerate=44100, bufsize=2048)
Write samples to a wavefile.
3.016433
2.94927
1.022773
omega = 2.0 * pi * float(frequency) sine = sin(omega * (float(i) / float(framerate))) return float(amplitude) * sine
def sine_wave(i, frequency=FREQUENCY, framerate=FRAMERATE, amplitude=AMPLITUDE)
Returns value of a sine wave at a given frequency and framerate for a given sample i
3.297199
3.168473
1.040627
lst_bin = _encode_binary(message) if amplitude > 1.0: amplitude = 1.0 if amplitude < 0.0: amplitude = 0.0 seconds_per_dot = _seconds_per_dot(word_ref) # =1.2 for i in count(skip_frame): bit = morse_bin(i=i, lst_bin=lst_bin, wpm=wpm, framerate=framerate, default_value=0.0, seconds_per_dot=seconds_per_dot) sine = sine_wave(i=i, frequency=frequency, framerate=framerate, amplitude=amplitude) yield sine * bit
def generate_wave(message, wpm=WPM, framerate=FRAMERATE, skip_frame=0, amplitude=AMPLITUDE, frequency=FREQUENCY, word_ref=WORD)
Generate binary Morse code of message at a given code speed wpm and framerate Parameters ---------- word : string wpm : int or float - word per minute framerate : nb of samples / seconds word_spaced : bool - calculate with spaces between 2 words (default is False) skip_frame : int - nb of frame to skip Returns ------- value : float
4.14147
4.602896
0.899753
try: return lst_bin[int(float(wpm) * float(i) / (seconds_per_dot * float(framerate)))] except IndexError: return default_value
def morse_bin(i, lst_bin, wpm=WPM, framerate=FRAMERATE, default_value=0.0, seconds_per_dot=1.2)
Returns value of a morse bin list at a given framerate and code speed (wpm) for a given sample i
3.510655
3.218861
1.090651
bit = morse_bin(i=i, lst_bin=lst_bin, wpm=wpm, framerate=framerate, default_value=0.0, seconds_per_dot=seconds_per_dot) sine = sine_wave(i=i, frequency=frequency, framerate=framerate, amplitude=amplitude) return bit * sine
def calculate_wave(i, lst_bin, wpm=WPM, frequency=FREQUENCY, framerate=FRAMERATE, amplitude=AMPLITUDE, seconds_per_dot=SECONDS_PER_DOT)
Returns product of a sin wave and morse code (dit, dah, silent)
3.303522
3.06038
1.079448
samp_nb = samples_nb(message=message, wpm=wpm, framerate=framerate, word_spaced=False) import sounddevice as sd lst_bin = _encode_binary(message) amplitude = _limit_value(amplitude) seconds_per_dot = _seconds_per_dot(word_ref) # 1.2 a = [calculate_wave(i, lst_bin, wpm, frequency, framerate, amplitude, seconds_per_dot) for i in range(samp_nb)] sd.play(a, framerate, blocking=True)
def preview_wave(message, wpm=WPM, frequency=FREQUENCY, framerate=FRAMERATE, amplitude=AMPLITUDE, word_ref=WORD)
Listen (preview) wave sounddevice is required http://python-sounddevice.readthedocs.org/ $ pip install sounddevice
5.619273
5.905925
0.951464
def to_string(i, s): if i == 0 and s == ' ': return ' ' return s return letter_sep.join([to_string(i, s) for i, s in enumerate(_encode_morse(message))])
def _encode_to_morse_string(message, letter_sep)
>>> message = "SOS" >>> _encode_to_morse_string(message, letter_sep=' '*3) '... --- ...' >>> message = " SOS" >>> _encode_to_morse_string(message, letter_sep=' '*3) ' ... --- ...'
4.149083
4.478416
0.926462
l = _encode_morse(message) s = ' '.join(l) l = list(s) bin_conv = {'.': [on], '-': [on] * 3, ' ': [off]} l = map(lambda symb: [off] + bin_conv[symb], l) lst = [item for sublist in l for item in sublist] # flatten list return lst[1:]
def _encode_binary(message, on=1, off=0)
>>> message = "SOS" >>> _encode_binary(message) [1, 0, 1, 0, 1, 0, 0, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 0, 0, 1, 0, 1, 0, 1] >>> _encode_binary(message, on='1', off='0') ['1', '0', '1', '0', '1', '0', '0', '0', '1', '1', '1', '0', '1', '1', '1', '0', '1', '1', '1', '0', '0', '0', '1', '0', '1', '0', '1']
5.30239
5.584228
0.94953
def to_string(i, s): if i == 0 and s == off: return off * 4 return s return ''.join(to_string(i, s) for i, s in enumerate(_encode_binary(message, on=on, off=off)))
def _encode_to_binary_string(message, on, off)
>>> message = "SOS" >>> _encode_to_binary_string(message, on='1', off='0') '101010001110111011100010101' >>> message = " SOS" >>> _encode_to_binary_string(message, on='1', off='0') '0000000101010001110111011100010101'
5.20392
5.254568
0.990361
if strip: message = message.strip() # No trailing or leading spaces encoding_type = encoding_type.lower() allowed_encoding_type = ['default', 'binary'] if encoding_type == 'default': return _encode_to_morse_string(message, letter_sep) elif encoding_type == 'binary': return _encode_to_binary_string(message, on='1', off='0') else: raise NotImplementedError("encoding_type must be in %s" % allowed_encoding_type)
def encode(message, encoding_type='default', letter_sep=' ' * 3, strip=True)
Converts a string of message into morse Two types of marks are there. One is short mark, dot(.) or "dit" and other is long mark, dash(-) or "dah". After every dit or dah, there is a one dot duration or one unit log gap. Between every letter, there is a short gap (three units long). Between every word, there is a medium gap (seven units long). When encoding is changed to binary, the short mark(dot) is denoted by 1 and the long mark(dash) is denoted by 111. The intra character gap between letters is represented by 0. The short gap is represented by 000 and the medium gap by 0000000. >>> message = "SOS" >>> encode(message) '... --- ...' >>> message = " SOS" >>> encode(message, strip=False) ' ... --- ...' Parameters ---------- message : String encoding : Type of encoding Supported types are default(morse) and binary. Returns ------- encoded_message : String
3.235435
3.332961
0.970739
l = [0] + l + [0] y = [] x = [] for i, bit in enumerate(l): y.append(bit) y.append(bit) x.append((i - 1) * duration) x.append(i * duration) return x, y
def _create_x_y(l, duration=1)
Create 2 lists x: time (as unit of dot (dit) y: bits from a list of bit >>> l = [1, 0, 1, 0, 1, 0, 0, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 0, 0, 1, 0, 1, 0, 1] >>> x, y = _create_x_y(l) >>> x [-1, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22, 23, 23, 24, 24, 25, 25, 26, 26, 27, 27, 28] >>> y [0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0]
2.687015
2.89794
0.927215
lst_bin = _encode_binary(message) x, y = _create_x_y(lst_bin, duration) ax = _create_ax(ax) ax.plot(x, y, linewidth=2.0) delta_y = 0.1 ax.set_ylim(-delta_y, 1 + delta_y) ax.set_yticks([0, 1]) delta_x = 0.5 * duration ax.set_xlim(-delta_x, len(lst_bin) * duration + delta_x) return ax
def plot(message, duration=1, ax=None)
Plot a message Returns: ax a Matplotlib Axe
3.110419
3.285979
0.946573
message = (word_space + word) * N message = message[len(word_space):] return message
def _repeat_word(word, N, word_space=" ")
Return a repeated string >>> word = "PARIS" >>> _repeat_word(word, 5) 'PARIS PARIS PARIS PARIS PARIS' >>> _repeat_word(word, 5, word_space="") 'PARISPARISPARISPARISPARIS'
4.573348
9.531692
0.479804
message = _repeat_word(message, N) if word_spaced: message = message + " E" lst_bin = _encode_binary(message) N = len(lst_bin) if word_spaced: N -= 1 # E is one "dit" so we remove it return N
def mlength(message, N=1, word_spaced=True)
Returns Morse length >>> message = "PARIS" >>> mlength(message) 50 >>> mlength(message, 5) 250
7.875262
10.601647
0.742834
N = mlength(word_ref) * wpm output = output.lower() allowed_output = ['decimal', 'float', 'timedelta'] if output == 'decimal': import decimal duration = 60 * 1000 / decimal.Decimal(N) elif output == 'float': duration = 60 * 1000 / float(N) elif output == 'timedelta': import datetime duration = datetime.timedelta(seconds=(60 / float(N))) else: raise NotImplementedError("output must be in %s" % allowed_output) return duration
def wpm_to_duration(wpm, output='timedelta', word_ref=WORD)
Convert from WPM (word per minutes) to element duration Parameters ---------- wpm : int or float - word per minute output : String - type of output 'timedelta' 'float' 'decimal' word_ref : string - reference word (PARIS by default) Returns ------- duration : timedelta or float or decimal.Decimal - duration of an element >>> wpm_to_duration(5, output='decimal') Decimal('240') >>> wpm_to_duration(5, output='float') 240.0 >>> wpm_to_duration(5, output='timedelta') datetime.timedelta(0, 0, 240000) >>> wpm_to_duration(15, output='decimal') Decimal('80') >>> wpm_to_duration(13, output='decimal') Decimal('92.30769230769230769230769231') >>> wpm_to_duration(5.01, output='timedelta') datetime.timedelta(0, 0, 239521)
2.897107
3.279554
0.883384
elt_duration = wpm_to_duration(wpm, output=output, word_ref=word_ref) word_length = mlength(message, word_spaced=word_spaced) return word_length * elt_duration
def duration(message, wpm, output='timedelta', word_ref=WORD, word_spaced=False)
Calculate duration to send a message at a given code speed (calculated using reference word PARIS) Parameters ---------- word : string wpm : int or float - word per minute output : String - type of output 'timedelta' 'float' 'decimal' word : string - reference word (PARIS by default) word_spaced : bool - calculate with spaces between 2 words (default is False) Returns ------- duration : timedelta or float or decimal.Decimal - duration of the word `word` >>> duration(_repeat_word('PARIS', 5), 5, word_spaced=True) datetime.timedelta(0, 60) >>> duration('PARIS', 15) datetime.timedelta(0, 3, 440000) >>> duration('SOS', 15) datetime.timedelta(0, 2, 160000)
4.431416
7.224977
0.613347
return int(duration(message, wpm, output='float', word_spaced=word_spaced) / 1000.0 * framerate)
def samples_nb(message, wpm, framerate=FRAMERATE, word_spaced=False)
Calculate the number of samples for a given word at a given framerate (samples / seconds) >>> samples_nb('SOS', 15) 23814
5.379374
7.62218
0.705753
seconds_per_dot = _seconds_per_dot(word_ref) if element_duration is None and wpm is None: # element_duration = 1 # wpm = seconds_per_dot / element_duration wpm = WPM element_duration = wpm_to_duration(wpm, output='float', word_ref=WORD) / 1000.0 return element_duration, wpm elif element_duration is not None and wpm is None: wpm = seconds_per_dot / element_duration return element_duration, wpm elif element_duration is None and wpm is not None: element_duration = wpm_to_duration(wpm, output='float', word_ref=WORD) / 1000.0 return element_duration, wpm else: raise NotImplementedError("Can't set both element_duration and wpm")
def _get_speed(element_duration, wpm, word_ref=WORD)
Returns element duration when element_duration and/or code speed is given wpm >>> _get_speed(0.2, None) (0.2, 5.999999999999999) >>> _get_speed(None, 15) (0.08, 15) >>> _get_speed(None, None) (0.08, 15)
2.289218
2.375079
0.963849
lst = range(1, N + 1) return "".join(list(map(lambda i: str(i % 10), lst)))
def _numbers_units(N)
>>> _numbers_units(45) '123456789012345678901234567890123456789012345'
5.089118
4.53611
1.121912
N = N // 10 lst = range(1, N + 1) return "".join(map(lambda i: "%10s" % i, lst))
def _numbers_decades(N)
>>> _numbers_decades(45) ' 1 2 3 4'
5.028756
4.661253
1.078842
s_bin = mtalk.encode(c, encoding_type='binary', letter_sep=' ') N = len(s_bin) if align == ALIGN.LEFT: s_align = "<" elif align == ALIGN.RIGHT: s_align = ">" elif align == ALIGN.CENTER: s_align = "^" else: raise NotImplementedError("align '%s' not allowed" % align) s = "{0:" + padding + s_align + str(N) + "}" return s.format(c)
def _char_to_string_binary(c, align=ALIGN.LEFT, padding='-')
>>> _char_to_string_binary('O', align=ALIGN.LEFT) 'O----------' >>> _char_to_string_binary('O', align=ALIGN.RIGHT) '----------O' >>> _char_to_string_binary('O', align=ALIGN.CENTER) '-----O-----'
4.240354
4.817955
0.880115
s = _encode_to_binary_string(message, on="=", off=".") N = len(s) s += '\n' + _numbers_decades(N) s += '\n' + _numbers_units(N) s += '\n' s += '\n' + _timing_char(message) return s
def _timing_representation(message)
Returns timing representation of a message like 1 2 3 4 5 6 7 8 12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789 M------ O---------- R------ S---- E C---------- O---------- D------ E ===.===...===.===.===...=.===.=...=.=.=...=.......===.=.===.=...===.===.===...===.=.=...= spoken reprentation: M O R S E C O D E -- --- .-. ... . (space) -.-. --- -.. .
6.415025
7.522196
0.852813
s = '' inter_symb = ' ' inter_char = ' ' * 3 inter_word = inter_symb * 7 for i, word in enumerate(_split_message(message)): if i >= 1: s += inter_word for j, c in enumerate(word): if j != 0: s += inter_char s += _char_to_string_binary(c, align=ALIGN.LEFT) return s
def _timing_char(message)
>>> message = 'MORSE CODE' >>> _timing_char(message) 'M------ O---------- R------ S---- E C---------- O---------- D------ E'
4.780751
4.797036
0.996605
s = '' inter_char = ' ' inter_word = inter_char * 9 for i, word in enumerate(lst_lst_char): if i >= 1: s += inter_word for j, c in enumerate(word): if j != 0: s += inter_char s += _char_to_string_morse(c) return s
def _spoken_representation_L1(lst_lst_char)
>>> lst = [['M', 'O', 'R', 'S', 'E'], ['C', 'O', 'D', 'E']] >>> _spoken_representation_L1(lst) 'M O R S E C O D E' >>> lst = [[], ['M', 'O', 'R', 'S', 'E'], ['C', 'O', 'D', 'E']] >>> _spoken_representation_L1(lst) ' M O R S E C O D E'
3.416668
3.754213
0.910089
s = '' inter_char = ' ' inter_word = ' (space) ' for i, word in enumerate(lst_lst_char): if i >= 1: s += inter_word for j, c in enumerate(word): if j != 0: s += inter_char s += mtalk.encoding.morsetab[c] return s
def _spoken_representation_L2(lst_lst_char)
>>> lst = [['M', 'O', 'R', 'S', 'E'], ['C', 'O', 'D', 'E']] >>> _spoken_representation_L2(lst) '-- --- .-. ... . (space) -.-. --- -.. .'
5.091529
4.909507
1.037075
lst_lst_char = _split_message(message) s = _spoken_representation_L1(lst_lst_char) s += '\n' + _spoken_representation_L2(lst_lst_char) return s
def _spoken_representation(message)
Returns 2 lines of spoken representation of a message like: M O R S E C O D E (space) -- --- .-. ... . (space) -.-. --- -.. .
4.290999
4.525802
0.948119
fmt = "{0:>8s}: '{1}'" key = "text" if strip: print(fmt.format(key, message.strip())) else: print(fmt.format(key, message.strip())) print(fmt.format("morse", mtalk.encode(message, strip=strip))) print(fmt.format("bin", mtalk.encode(message, encoding_type='binary', strip=strip))) print("") print("{0:>8s}:".format("timing")) print(_timing_representation(message)) print("") print("{0:>8s}:".format("spoken reprentation")) print(_spoken_representation(message)) print("") print("code speed : %s wpm" % wpm) print("element_duration : %s s" % element_duration) print("reference word : %r" % word_ref) print("")
def display(message, wpm, element_duration, word_ref, strip=False)
Display text message morse code binary morse code
3.699764
3.55893
1.039572
if value > upper: return(upper) if value < lower: return(lower) return value
def _limit_value(value, upper=1.0, lower=0.0)
Returs value (such as amplitude) to upper and lower value >>> _limit_value(0.5) 0.5 >>> _limit_value(1.5) 1.0 >>> _limit_value(-1.5) 0.0
3.4168
5.549575
0.615687
''' take a field_name_label and return the id''' if self.is_child: try: return self._children[label] except KeyError: self._children[label] = ChildFieldPicklist(self.parent, label, self.field_name) return self._children[label] else: return get_label_value(label, self._picklist)
def lookup(self, label)
take a field_name_label and return the id
5.590404
4.265857
1.310499
''' take a field_name_id and return the label ''' label = get_value_label(value, self._picklist, condition=condition) return label
def reverse_lookup(self, value, condition=is_active)
take a field_name_id and return the label
13.500394
6.772853
1.99331
'type: wrapper :atws.Wrapper' fields = wrapper.new('GetFieldInfo') fields.psObjectType = entity_type return wrapper.GetFieldInfo(fields)
def get_field_info(wrapper,entity_type)
type: wrapper :atws.Wrapper
30.970671
10.273293
3.014678
item = { "info": {"key": key or title, "synonyms": synonyms or []}, "title": title, "description": description, "image": { "imageUri": img_url or "", "accessibilityText": alt_text or "{} img".format(title), }, } return item
def build_item( title, key=None, synonyms=None, description=None, img_url=None, alt_text=None )
Builds an item that may be added to List or Carousel
3.152592
3.099729
1.017054
chips = [] for r in replies: chips.append({"title": r}) # NOTE: both of these formats work in the dialogflow console, # but only the first (suggestions) appears in actual Google Assistant # native chips for GA self._messages.append( {"platform": "ACTIONS_ON_GOOGLE", "suggestions": {"suggestions": chips}} ) # # quick replies for other platforms # self._messages.append( # { # "platform": "ACTIONS_ON_GOOGLE", # "quickReplies": {"title": None, "quickReplies": replies}, # } # ) return self
def suggest(self, *replies)
Use suggestion chips to hint at responses to continue or pivot the conversation
5.80833
5.165233
1.124505
self._messages.append( { "platform": "ACTIONS_ON_GOOGLE", "linkOutSuggestion": {"destinationName": name, "uri": url}, } ) return self
def link_out(self, name, url)
Presents a chip similar to suggestion, but instead links to a url
5.285056
5.497053
0.961435
list_card = _ListSelector( self._speech, display_text=self._display_text, title=title, items=items ) return list_card
def build_list(self, title=None, items=None)
Presents the user with a vertical list of multiple items. Allows the user to select a single item. Selection generates a user query containing the title of the list item *Note* Returns a completely new object, and does not modify the existing response object Therefore, to add items, must be assigned to new variable or call the method directly after initializing list example usage: simple = ask('I speak this text') mylist = simple.build_list('List Title') mylist.add_item('Item1', 'key1') mylist.add_item('Item2', 'key2') return mylist Arguments: title {str} -- Title displayed at top of list card Returns: _ListSelector -- [_Response object exposing the add_item method]
9.044607
6.546038
1.381692