text_prompt stringlengths 157 13.1k | code_prompt stringlengths 7 19.8k ⌀ |
|---|---|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def tag_helper(tag, items, locked=True, remove=False):
""" Simple tag helper for editing a object. """ |
if not isinstance(items, list):
items = [items]
data = {}
if not remove:
for i, item in enumerate(items):
tagname = '%s[%s].tag.tag' % (tag, i)
data[tagname] = item
if remove:
tagname = '%s[].tag.tag-' % tag
data[tagname] = ','.join(items)
data['%s.locked' % tag] = 1 if locked else 0
return data |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def choose(msg, items, attr):
# pragma: no cover """ Command line helper to display a list of choices, asking the user to choose one of the options. """ |
# Return the first item if there is only one choice
if len(items) == 1:
return items[0]
# Print all choices to the command line
print()
for index, i in enumerate(items):
name = attr(i) if callable(attr) else getattr(i, attr)
print(' %s: %s' % (index, name))
print()
# Request choice from the user
while True:
try:
inp = input('%s: ' % msg)
if any(s in inp for s in (':', '::', '-')):
idx = slice(*map(lambda x: int(x.strip()) if x.strip() else None, inp.split(':')))
return items[idx]
else:
return items[int(inp)]
except (ValueError, IndexError):
pass |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _find_server(account, servername=None):
""" Find and return a PlexServer object. """ |
servers = servers = [s for s in account.resources() if 'server' in s.provides]
# If servername specified find and return it
if servername is not None:
for server in servers:
if server.name == servername:
return server.connect()
raise SystemExit('Unknown server name: %s' % servername)
# If servername not specified; allow user to choose
return utils.choose('Choose a Server', servers, 'name').connect() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def backup_watched(plex, opts):
""" Backup watched status to the specified filepath. """ |
data = defaultdict(lambda: dict())
for section in _iter_sections(plex, opts):
print('Fetching watched status for %s..' % section.title)
skey = section.title.lower()
for item in _iter_items(section):
if not opts.watchedonly or item.isWatched:
ikey = _item_key(item)
data[skey][ikey] = item.isWatched
import pprint; pprint.pprint(item.__dict__); break
print('Writing backup file to %s' % opts.filepath)
with open(opts.filepath, 'w') as handle:
json.dump(dict(data), handle, sort_keys=True, indent=2) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def restore_watched(plex, opts):
""" Restore watched status from the specified filepath. """ |
with open(opts.filepath, 'r') as handle:
source = json.load(handle)
# Find the differences
differences = defaultdict(lambda: dict())
for section in _iter_sections(plex, opts):
print('Finding differences in %s..' % section.title)
skey = section.title.lower()
for item in _iter_items(section):
ikey = _item_key(item)
sval = source.get(skey,{}).get(ikey)
if sval is None:
raise SystemExit('%s not found' % ikey)
if (sval is not None and item.isWatched != sval) and (not opts.watchedonly or sval):
differences[skey][ikey] = {'isWatched':sval, 'item':item}
print('Applying %s differences to destination' % len(differences))
import pprint; pprint.pprint(differences) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _onMessage(self, ws, message):
""" Called when websocket message is recieved. """ |
try:
data = json.loads(message)['NotificationContainer']
log.debug('Alert: %s %s %s', *data)
if self._callback:
self._callback(data)
except Exception as err: # pragma: no cover
log.error('AlertListener Msg Error: %s', err) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _cast(self, value):
""" Cast the specifief value to the type of this setting. """ |
if self.type != 'text':
value = utils.cast(self.TYPES.get(self.type)['cast'], value)
return value |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _getEnumValues(self, data):
""" Returns a list of dictionary of valis value for this setting. """ |
enumstr = data.attrib.get('enumValues')
if not enumstr:
return None
if ':' in enumstr:
return {self._cast(k): v for k, v in [kv.split(':') for kv in enumstr.split('|')]}
return enumstr.split('|') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _headers(self, **kwargs):
""" Returns dict containing base headers for all requests to the server. """ |
headers = BASE_HEADERS.copy()
if self._token:
headers['X-Plex-Token'] = self._token
headers.update(kwargs)
return headers |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def library(self):
""" Library to browse or search your media. """ |
if not self._library:
try:
data = self.query(Library.key)
self._library = Library(self, data)
except BadRequest:
data = self.query('/library/sections/')
# Only the owner has access to /library
# so just return the library without the data.
return Library(self, data)
return self._library |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def settings(self):
""" Returns a list of all server settings. """ |
if not self._settings:
data = self.query(Settings.key)
self._settings = Settings(self, data)
return self._settings |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def downloadDatabases(self, savepath=None, unpack=False):
""" Download databases. Parameters: savepath (str):
Defaults to current working dir. unpack (bool):
Unpack the zip file. """ |
url = self.url('/diagnostics/databases')
filepath = utils.download(url, self._token, None, savepath, self._session, unpack=unpack)
return filepath |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def installUpdate(self):
""" Install the newest version of Plex Media Server. """ |
# We can add this but dunno how useful this is since it sometimes
# requires user action using a gui.
part = '/updater/apply'
release = self.check_for_update(force=True, download=True)
if release and release.version != self.version:
# figure out what method this is..
return self.query(part, method=self._session.put) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def startAlertListener(self, callback=None):
""" Creates a websocket connection to the Plex Server to optionally recieve notifications. These often include messages from Plex about media scans as well as updates to currently running Transcode Sessions. NOTE: You need websocket-client installed in order to use this feature. >> pip install websocket-client Parameters: callback (func):
Callback function to call on recieved messages. raises: :class:`plexapi.exception.Unsupported`: Websocket-client not installed. """ |
notifier = AlertListener(self, callback)
notifier.start()
return notifier |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def url(self, key, includeToken=None):
""" Build a URL string with proper token argument. Token will be appended to the URL if either includeToken is True or CONFIG.log.show_secrets is 'true'. """ |
if self._token and (includeToken or self._showSecrets):
delim = '&' if '?' in key else '?'
return '%s%s%sX-Plex-Token=%s' % (self._baseurl, key, delim, self._token)
return '%s%s' % (self._baseurl, key) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def thumbUrl(self):
""" Return the first first thumbnail url starting on the most specific thumbnail for that item. """ |
thumb = self.firstAttr('thumb', 'parentThumb', 'granparentThumb')
return self._server.url(thumb, includeToken=True) if thumb else None |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def artUrl(self):
""" Return the first first art url starting on the most specific for that item.""" |
art = self.firstAttr('art', 'grandparentArt')
return self._server.url(art, includeToken=True) if art else None |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def url(self, part):
""" Returns the full url for something. Typically used for getting a specific image. """ |
return self._server.url(part, includeToken=True) if part else None |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def markWatched(self):
""" Mark video as watched. """ |
key = '/:/scrobble?key=%s&identifier=com.plexapp.plugins.library' % self.ratingKey
self._server.query(key)
self.reload() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def markUnwatched(self):
""" Mark video unwatched. """ |
key = '/:/unscrobble?key=%s&identifier=com.plexapp.plugins.library' % self.ratingKey
self._server.query(key)
self.reload() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _asDict(self):
""" Returns all configuration values as a dictionary. """ |
config = defaultdict(dict)
for section in self._sections:
for name, value in self._sections[section].items():
if name != '__name__':
config[section.lower()][name.lower()] = value
return dict(config) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def parse(server, data, initpath):
# pragma: no cover seems to be dead code. """ Factory method returns a new MediaPartStream from xml data. """ |
STREAMCLS = {1: VideoStream, 2: AudioStream, 3: SubtitleStream}
stype = cast(int, data.attrib.get('streamType'))
cls = STREAMCLS.get(stype, MediaPartStream)
return cls(server, data, initpath) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def delete(self):
""" Removes current SyncItem """ |
url = SyncList.key.format(clientId=self.clientIdentifier)
url += '/' + str(self.id)
self._server.query(url, self._server._session.delete) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _buildItem(self, elem, cls=None, initpath=None):
""" Factory function to build objects based on registered PLEXOBJECTS. """ |
# cls is specified, build the object and return
initpath = initpath or self._initpath
if cls is not None:
return cls(self._server, elem, initpath)
# cls is not specified, try looking it up in PLEXOBJECTS
etype = elem.attrib.get('type', elem.attrib.get('streamType'))
ehash = '%s.%s' % (elem.tag, etype) if etype else elem.tag
ecls = utils.PLEXOBJECTS.get(ehash, utils.PLEXOBJECTS.get(elem.tag))
# log.debug('Building %s as %s', elem.tag, ecls.__name__)
if ecls is not None:
return ecls(self._server, elem, initpath)
raise UnknownType("Unknown library type <%s type='%s'../>" % (elem.tag, etype)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fetchItem(self, ekey, cls=None, **kwargs):
""" Load the specified key to find and build the first item with the specified tag and attrs. If no tag or attrs are specified then the first item in the result set is returned. Parameters: ekey (str or int):
Path in Plex to fetch items from. If an int is passed in, the key will be translated to /library/metadata/<key>. This allows fetching an item only knowing its key-id. cls (:class:`~plexapi.base.PlexObject`):
If you know the class of the items to be fetched, passing this in will help the parser ensure it only returns those items. By default we convert the xml elements with the best guess PlexObjects based on tag and type attrs. etag (str):
Only fetch items with the specified tag. **kwargs (dict):
Optionally add attribute filters on the items to fetch. For example, passing in viewCount=0 will only return matching items. Filtering is done before the Python objects are built to help keep things speedy. Note: Because some attribute names are already used as arguments to this function, such as 'tag', you may still reference the attr tag byappending an underscore. For example, passing in _tag='foobar' will return all items where tag='foobar'. Also Note: Case very much matters when specifying kwargs -- Optionally, operators can be specified by append it to the end of the attribute name for more complex lookups. For example, passing in viewCount__gte=0 will return all items where viewCount >= 0. Available operations include: * __contains: Value contains specified arg. * __endswith: Value ends with specified arg. * __exact: Value matches specified arg. * __exists (bool):
Value is or is not present in the attrs. * __gt: Value is greater than specified arg. * __gte: Value is greater than or equal to specified arg. * __icontains: Case insensative value contains specified arg. * __iendswith: Case insensative value ends with specified arg. * __iexact: Case insensative value matches specified arg. * __in: Value is in a specified list or tuple. * __iregex: Case insensative value matches the specified regular expression. * __istartswith: Case insensative value starts with specified arg. * __lt: Value is less than specified arg. * __lte: Value is less than or equal to specified arg. * __regex: Value matches the specified regular expression. * __startswith: Value starts with specified arg. """ |
if isinstance(ekey, int):
ekey = '/library/metadata/%s' % ekey
for elem in self._server.query(ekey):
if self._checkAttrs(elem, **kwargs):
return self._buildItem(elem, cls, ekey)
clsname = cls.__name__ if cls else 'None'
raise NotFound('Unable to find elem: cls=%s, attrs=%s' % (clsname, kwargs)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def firstAttr(self, *attrs):
""" Return the first attribute in attrs that is not None. """ |
for attr in attrs:
value = self.__dict__.get(attr)
if value is not None:
return value |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def reload(self, key=None):
""" Reload the data for this object from self.key. """ |
key = key or self._details_key or self.key
if not key:
raise Unsupported('Cannot reload an object not built from a URL.')
self._initpath = key
data = self._server.query(key)
self._loadData(data[0])
return self |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def edit(self, **kwargs):
""" Edit an object. Parameters: kwargs (dict):
Dict of settings to edit. Example: {'type': 1, 'id': movie.ratingKey, 'collection[0].tag.tag': 'Super', 'collection.locked': 0} """ |
if 'id' not in kwargs:
kwargs['id'] = self.ratingKey
if 'type' not in kwargs:
kwargs['type'] = utils.searchType(self.type)
part = '/library/sections/%s/all?%s' % (self.librarySectionID,
urlencode(kwargs))
self._server.query(part, method=self._server._session.put) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _edit_tags(self, tag, items, locked=True, remove=False):
""" Helper to edit and refresh a tags. Parameters: tag (str):
tag name items (list):
list of tags to add locked (bool):
lock this field. remove (bool):
If this is active remove the tags in items. """ |
if not isinstance(items, list):
items = [items]
value = getattr(self, tag + 's')
existing_cols = [t.tag for t in value if t and remove is False]
d = tag_helper(tag, existing_cols + items, locked, remove)
self.edit(**d)
self.refresh() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getStreamURL(self, **params):
""" Returns a stream url that may be used by external applications such as VLC. Parameters: **params (dict):
optional parameters to manipulate the playback when accessing the stream. A few known parameters include: maxVideoBitrate, videoResolution offset, copyts, protocol, mediaIndex, platform. Raises: :class:`plexapi.exceptions.Unsupported`: When the item doesn't support fetching a stream URL. """ |
if self.TYPE not in ('movie', 'episode', 'track'):
raise Unsupported('Fetching stream URL for %s is unsupported.' % self.TYPE)
mvb = params.get('maxVideoBitrate')
vr = params.get('videoResolution', '')
params = {
'path': self.key,
'offset': params.get('offset', 0),
'copyts': params.get('copyts', 1),
'protocol': params.get('protocol'),
'mediaIndex': params.get('mediaIndex', 0),
'X-Plex-Platform': params.get('platform', 'Chrome'),
'maxVideoBitrate': max(mvb, 64) if mvb else None,
'videoResolution': vr if re.match('^\d+x\d+$', vr) else None
}
# remove None values
params = {k: v for k, v in params.items() if v is not None}
streamtype = 'audio' if self.TYPE in ('track', 'album') else 'video'
# sort the keys since the randomness fucks with my tests..
sorted_params = sorted(params.items(), key=lambda val: val[0])
return self._server.url('/%s/:/transcode/universal/start.m3u8?%s' %
(streamtype, urlencode(sorted_params)), includeToken=True) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def split(self):
"""Split a duplicate.""" |
key = '%s/split' % self.key
return self._server.query(key, method=self._server._session.put) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def unmatch(self):
"""Unmatch a media file.""" |
key = '%s/unmatch' % self.key
return self._server.query(key, method=self._server._session.put) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def download(self, savepath=None, keep_original_name=False, **kwargs):
""" Downloads this items media to the specified location. Returns a list of filepaths that have been saved to disk. Parameters: savepath (str):
Title of the track to return. keep_original_name (bool):
Set True to keep the original filename as stored in the Plex server. False will create a new filename with the format "<Artist> - <Album> <Track>". kwargs (dict):
If specified, a :func:`~plexapi.audio.Track.getStreamURL()` will be returned and the additional arguments passed in will be sent to that function. If kwargs is not specified, the media items will be downloaded and saved to disk. """ |
filepaths = []
locations = [i for i in self.iterParts() if i]
for location in locations:
filename = location.file
if keep_original_name is False:
filename = '%s.%s' % (self._prettyfilename(), location.container)
# So this seems to be a alot slower but allows transcode.
if kwargs:
download_url = self.getStreamURL(**kwargs)
else:
download_url = self._server.url('%s?download=1' % location.key)
filepath = utils.download(download_url, self._server._token, filename=filename,
savepath=savepath, session=self._server._session)
if filepath:
filepaths.append(filepath)
return filepaths |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def stop(self, reason=''):
""" Stop playback for a media item. """ |
key = '/status/sessions/terminate?sessionId=%s&reason=%s' % (self.session[0].id, quote_plus(reason))
return self._server.query(key) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def updateProgress(self, time, state='stopped'):
""" Set the watched progress for this video. Note that setting the time to 0 will not work. Use `markWatched` or `markUnwatched` to achieve that goal. Parameters: time (int):
milliseconds watched state (string):
state of the video, default 'stopped' """ |
key = '/:/progress?key=%s&identifier=com.plexapp.plugins.library&time=%d&state=%s' % (self.ratingKey,
time, state)
self._server.query(key)
self.reload() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def updateTimeline(self, time, state='stopped', duration=None):
""" Set the timeline progress for this video. Parameters: time (int):
milliseconds watched state (string):
state of the video, default 'stopped' duration (int):
duration of the item """ |
durationStr = '&duration='
if duration is not None:
durationStr = durationStr + str(duration)
else:
durationStr = durationStr + str(self.duration)
key = '/:/timeline?ratingKey=%s&key=%s&identifier=com.plexapp.plugins.library&time=%d&state=%s%s'
key %= (self.ratingKey, self.key, time, state, durationStr)
self._server.query(key)
self.reload() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def all(self, **kwargs):
""" Returns a list of all media from all library sections. This may be a very large dataset to retrieve. """ |
items = []
for section in self.sections():
for item in section.all(**kwargs):
items.append(item)
return items |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def search(self, title=None, libtype=None, **kwargs):
""" Searching within a library section is much more powerful. It seems certain attributes on the media objects can be targeted to filter this search down a bit, but I havent found the documentation for it. Example: "studio=Comedy%20Central" or "year=1999" "title=Kung Fu" all work. Other items such as actor=<id> seem to work, but require you already know the id of the actor. TLDR: This is untested but seems to work. Use library section search when you can. """ |
args = {}
if title:
args['title'] = title
if libtype:
args['type'] = utils.searchType(libtype)
for attr, value in kwargs.items():
args[attr] = value
key = '/library/all%s' % utils.joinArgs(args)
return self.fetchItems(key) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add(self, name='', type='', agent='', scanner='', location='', language='en', *args, **kwargs):
""" Simplified add for the most common options. Parameters: name (str):
Name of the library agent (str):
Example com.plexapp.agents.imdb type (str):
movie, show, # check me location (str):
/path/to/files language (str):
Two letter language fx en kwargs (dict):
Advanced options should be passed as a dict. where the id is the key. **Photo Preferences** * **agent** (str):
com.plexapp.agents.none * **enableAutoPhotoTags** (bool):
Tag photos. Default value false. * **enableBIFGeneration** (bool):
Enable video preview thumbnails. Default value true. * **includeInGlobal** (bool):
Include in dashboard. Default value true. * **scanner** (str):
Plex Photo Scanner **Movie Preferences** * **agent** (str):
com.plexapp.agents.none, com.plexapp.agents.imdb, com.plexapp.agents.themoviedb * **enableBIFGeneration** (bool):
Enable video preview thumbnails. Default value true. * **enableCinemaTrailers** (bool):
Enable Cinema Trailers. Default value true. * **includeInGlobal** (bool):
Include in dashboard. Default value true. * **scanner** (str):
Plex Movie Scanner, Plex Video Files Scanner **IMDB Movie Options** (com.plexapp.agents.imdb) * **title** (bool):
Localized titles. Default value false. * **extras** (bool):
Find trailers and extras automatically (Plex Pass required). Default value true. * **only_trailers** (bool):
Skip extras which aren't trailers. Default value false. * **redband** (bool):
Use red band (restricted audiences) trailers when available. Default value false. * **native_subs** (bool):
Include extras with subtitles in Library language. Default value false. * **cast_list** (int):
Cast List Source: Default value 1 Possible options: 0:IMDb,1:The Movie Database. * **ratings** (int):
Ratings Source, Default value 0 Possible options: 0:Rotten Tomatoes, 1:IMDb, 2:The Movie Database. * **summary** (int):
Plot Summary Source: Default value 1 Possible options: 0:IMDb,1:The Movie Database. * **country** (int):
Default value 46 Possible options 0:Argentina, 1:Australia, 2:Austria, 3:Belgium, 4:Belize, 5:Bolivia, 6:Brazil, 7:Canada, 8:Chile, 9:Colombia, 10:Costa Rica, 11:Czech Republic, 12:Denmark, 13:Dominican Republic, 14:Ecuador, 15:El Salvador, 16:France, 17:Germany, 18:Guatemala, 19:Honduras, 20:Hong Kong SAR, 21:Ireland, 22:Italy, 23:Jamaica, 24:Korea, 25:Liechtenstein, 26:Luxembourg, 27:Mexico, 28:Netherlands, 29:New Zealand, 30:Nicaragua, 31:Panama, 32:Paraguay, 33:Peru, 34:Portugal, 35:Peoples Republic of China, 36:Puerto Rico, 37:Russia, 38:Singapore, 39:South Africa, 40:Spain, 41:Sweden, 42:Switzerland, 43:Taiwan, 44:Trinidad, 45:United Kingdom, 46:United States, 47:Uruguay, 48:Venezuela. * **collections** (bool):
Use collection info from The Movie Database. Default value false. * **localart** (bool):
Prefer artwork based on library language. Default value true. * **adult** (bool):
Include adult content. Default value false. * **usage** (bool):
Send anonymous usage data to Plex. Default value true. **TheMovieDB Movie Options** (com.plexapp.agents.themoviedb) * **collections** (bool):
Use collection info from The Movie Database. Default value false. * **localart** (bool):
Prefer artwork based on library language. Default value true. * **adult** (bool):
Include adult content. Default value false. * **country** (int):
Country (used for release date and content rating). Default value 47 Possible options 0:, 1:Argentina, 2:Australia, 3:Austria, 4:Belgium, 5:Belize, 6:Bolivia, 7:Brazil, 8:Canada, 9:Chile, 10:Colombia, 11:Costa Rica, 12:Czech Republic, 13:Denmark, 14:Dominican Republic, 15:Ecuador, 16:El Salvador, 17:France, 18:Germany, 19:Guatemala, 20:Honduras, 21:Hong Kong SAR, 22:Ireland, 23:Italy, 24:Jamaica, 25:Korea, 26:Liechtenstein, 27:Luxembourg, 28:Mexico, 29:Netherlands, 30:New Zealand, 31:Nicaragua, 32:Panama, 33:Paraguay, 34:Peru, 35:Portugal, 36:Peoples Republic of China, 37:Puerto Rico, 38:Russia, 39:Singapore, 40:South Africa, 41:Spain, 42:Sweden, 43:Switzerland, 44:Taiwan, 45:Trinidad, 46:United Kingdom, 47:United States, 48:Uruguay, 49:Venezuela. **Show Preferences** * **agent** (str):
com.plexapp.agents.none, com.plexapp.agents.thetvdb, com.plexapp.agents.themoviedb * **enableBIFGeneration** (bool):
Enable video preview thumbnails. Default value true. * **episodeSort** (int):
Episode order. Default -1 Possible options: 0:Oldest first, 1:Newest first. * **flattenSeasons** (int):
Seasons. Default value 0 Possible options: 0:Show,1:Hide. * **includeInGlobal** (bool):
Include in dashboard. Default value true. * **scanner** (str):
Plex Series Scanner **TheTVDB Show Options** (com.plexapp.agents.thetvdb) * **extras** (bool):
Find trailers and extras automatically (Plex Pass required). Default value true. * **native_subs** (bool):
Include extras with subtitles in Library language. Default value false. **TheMovieDB Show Options** (com.plexapp.agents.themoviedb) * **collections** (bool):
Use collection info from The Movie Database. Default value false. * **localart** (bool):
Prefer artwork based on library language. Default value true. * **adult** (bool):
Include adult content. Default value false. * **country** (int):
Country (used for release date and content rating). Default value 47 options 0:, 1:Argentina, 2:Australia, 3:Austria, 4:Belgium, 5:Belize, 6:Bolivia, 7:Brazil, 8:Canada, 9:Chile, 10:Colombia, 11:Costa Rica, 12:Czech Republic, 13:Denmark, 14:Dominican Republic, 15:Ecuador, 16:El Salvador, 17:France, 18:Germany, 19:Guatemala, 20:Honduras, 21:Hong Kong SAR, 22:Ireland, 23:Italy, 24:Jamaica, 25:Korea, 26:Liechtenstein, 27:Luxembourg, 28:Mexico, 29:Netherlands, 30:New Zealand, 31:Nicaragua, 32:Panama, 33:Paraguay, 34:Peru, 35:Portugal, 36:Peoples Republic of China, 37:Puerto Rico, 38:Russia, 39:Singapore, 40:South Africa, 41:Spain, 42:Sweden, 43:Switzerland, 44:Taiwan, 45:Trinidad, 46:United Kingdom, 47:United States, 48:Uruguay, 49:Venezuela. **Other Video Preferences** * **agent** (str):
com.plexapp.agents.none, com.plexapp.agents.imdb, com.plexapp.agents.themoviedb * **enableBIFGeneration** (bool):
Enable video preview thumbnails. Default value true. * **enableCinemaTrailers** (bool):
Enable Cinema Trailers. Default value true. * **includeInGlobal** (bool):
Include in dashboard. Default value true. * **scanner** (str):
Plex Movie Scanner, Plex Video Files Scanner **IMDB Other Video Options** (com.plexapp.agents.imdb) * **title** (bool):
Localized titles. Default value false. * **extras** (bool):
Find trailers and extras automatically (Plex Pass required). Default value true. * **only_trailers** (bool):
Skip extras which aren't trailers. Default value false. * **redband** (bool):
Use red band (restricted audiences) trailers when available. Default value false. * **native_subs** (bool):
Include extras with subtitles in Library language. Default value false. * **cast_list** (int):
Cast List Source: Default value 1 Possible options: 0:IMDb,1:The Movie Database. * **ratings** (int):
Ratings Source Default value 0 Possible options: 0:Rotten Tomatoes,1:IMDb,2:The Movie Database. * **summary** (int):
Plot Summary Source: Default value 1 Possible options: 0:IMDb,1:The Movie Database. * **country** (int):
Country: Default value 46 Possible options: 0:Argentina, 1:Australia, 2:Austria, 3:Belgium, 4:Belize, 5:Bolivia, 6:Brazil, 7:Canada, 8:Chile, 9:Colombia, 10:Costa Rica, 11:Czech Republic, 12:Denmark, 13:Dominican Republic, 14:Ecuador, 15:El Salvador, 16:France, 17:Germany, 18:Guatemala, 19:Honduras, 20:Hong Kong SAR, 21:Ireland, 22:Italy, 23:Jamaica, 24:Korea, 25:Liechtenstein, 26:Luxembourg, 27:Mexico, 28:Netherlands, 29:New Zealand, 30:Nicaragua, 31:Panama, 32:Paraguay, 33:Peru, 34:Portugal, 35:Peoples Republic of China, 36:Puerto Rico, 37:Russia, 38:Singapore, 39:South Africa, 40:Spain, 41:Sweden, 42:Switzerland, 43:Taiwan, 44:Trinidad, 45:United Kingdom, 46:United States, 47:Uruguay, 48:Venezuela. * **collections** (bool):
Use collection info from The Movie Database. Default value false. * **localart** (bool):
Prefer artwork based on library language. Default value true. * **adult** (bool):
Include adult content. Default value false. * **usage** (bool):
Send anonymous usage data to Plex. Default value true. **TheMovieDB Other Video Options** (com.plexapp.agents.themoviedb) * **collections** (bool):
Use collection info from The Movie Database. Default value false. * **localart** (bool):
Prefer artwork based on library language. Default value true. * **adult** (bool):
Include adult content. Default value false. * **country** (int):
Country (used for release date and content rating). Default value 47 Possible options 0:, 1:Argentina, 2:Australia, 3:Austria, 4:Belgium, 5:Belize, 6:Bolivia, 7:Brazil, 8:Canada, 9:Chile, 10:Colombia, 11:Costa Rica, 12:Czech Republic, 13:Denmark, 14:Dominican Republic, 15:Ecuador, 16:El Salvador, 17:France, 18:Germany, 19:Guatemala, 20:Honduras, 21:Hong Kong SAR, 22:Ireland, 23:Italy, 24:Jamaica, 25:Korea, 26:Liechtenstein, 27:Luxembourg, 28:Mexico, 29:Netherlands, 30:New Zealand, 31:Nicaragua, 32:Panama, 33:Paraguay, 34:Peru, 35:Portugal, 36:Peoples Republic of China, 37:Puerto Rico, 38:Russia, 39:Singapore, 40:South Africa, 41:Spain, 42:Sweden, 43:Switzerland, 44:Taiwan, 45:Trinidad, 46:United Kingdom, 47:United States, 48:Uruguay, 49:Venezuela. """ |
part = '/library/sections?name=%s&type=%s&agent=%s&scanner=%s&language=%s&location=%s' % (
quote_plus(name), type, agent, quote_plus(scanner), language, quote_plus(location)) # noqa E126
if kwargs:
part += urlencode(kwargs)
return self._server.query(part, method=self._server._session.post) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def delete(self):
""" Delete a library section. """ |
try:
return self._server.query('/library/sections/%s' % self.key, method=self._server._session.delete)
except BadRequest: # pragma: no cover
msg = 'Failed to delete library %s' % self.key
msg += 'You may need to allow this permission in your Plex settings.'
log.error(msg)
raise |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get(self, title):
""" Returns the media item with the specified title. Parameters: title (str):
Title of the item to return. """ |
key = '/library/sections/%s/all' % self.key
return self.fetchItem(key, title__iexact=title) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def all(self, sort=None, **kwargs):
""" Returns a list of media from this library section. Parameters: sort (string):
The sort string """ |
sortStr = ''
if sort is not None:
sortStr = '?sort=' + sort
key = '/library/sections/%s/all%s' % (self.key, sortStr)
return self.fetchItems(key, **kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def emptyTrash(self):
""" If a section has items in the Trash, use this option to empty the Trash. """ |
key = '/library/sections/%s/emptyTrash' % self.key
self._server.query(key, method=self._server._session.put) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cancelUpdate(self):
""" Cancel update of this Library Section. """ |
key = '/library/sections/%s/refresh' % self.key
self._server.query(key, method=self._server._session.delete) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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. """ |
key = '/library/sections/%s/indexes' % self.key
self._server.query(key, method=self._server._session.delete) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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). """ |
return self.search(sort='addedAt:desc', libtype=libtype, maxresults=maxresults) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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']} """ |
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def removeFriend(self, user):
""" Remove the specified user from all sharing. Parameters: user (str):
MyPlexUser, username, email of the user to be added. """ |
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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']} """ |
# 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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _getSectionIds(self, server, sections):
""" Converts a list of section objects or names to sectionIds needed for library sharing. """ |
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _filterDictToStr(self, filterDict):
""" Converts friend filters to a string representation for transport. """ |
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def delete(self):
""" Remove this device from your account. """ |
key = 'https://plex.tv/devices/%s.xml' % self.id
self._server.query(key, self._server._session.delete) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def thumbUrl(self):
""" Return url to for the thumbnail image. """ |
key = self.firstAttr('thumb', 'parentThumb', 'granparentThumb')
return self._server.url(key, includeToken=True) if key else None |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def keep_episodes(show, keep):
""" Delete all but last count episodes in show. """ |
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def keep_season(show, keep):
""" Keep only the latest season. """ |
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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. """ |
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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. """ |
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 '+'. """ |
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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. """ |
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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. """ |
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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. """ |
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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. """ |
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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. """ |
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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. """ |
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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. """ |
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _inner_search(obj, glob, separator, dirs=True, leaves=False):
"""Search the object paths that match the glob.""" |
for path in dpath.path.paths(obj, dirs, leaves, skip=True):
if dpath.path.match(path, glob):
yield path |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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. 'SOS' """ |
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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.
'''
return islice(izip(*(imap(sum, izip(*channel)) for channel in channels)), nsamples) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def write_wavefile(f, samples, nframes=None, nchannels=2, sampwidth=2, framerate=44100, bufsize=2048):
"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() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 """ |
omega = 2.0 * pi * float(frequency)
sine = sin(omega * (float(i) / float(framerate)))
return float(amplitude) * sine |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 """ |
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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. Parameters message : String encoding : Type of encoding Supported types are default(morse) and binary. Returns ------- encoded_message : String """ |
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def plot(message, duration=1, ax=None):
""" Plot a message Returns: ax a Matplotlib Axe """ |
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def mlength(message, N=1, word_spaced=True):
""" Returns Morse length 50 250 """ |
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _timing_representation(message):
""" Returns timing representation of a message like 1 2 3 4 5 6 7 8 12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789 spoken reprentation: M O R S E C O D E """ |
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def display(message, wpm, element_duration, word_ref, strip=False):
""" Display text message morse code binary morse code """ |
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("") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def lookup(self, label):
''' 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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def reverse_lookup(self, value, condition=is_active):
''' take a field_name_id and return the label '''
label = get_value_label(value, self._picklist, condition=condition)
return label |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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""" |
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def suggest(self, *replies):
"""Use suggestion chips to hint at responses to continue or pivot the conversation""" |
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def link_out(self, name, url):
"""Presents a chip similar to suggestion, but instead links to a url""" |
self._messages.append(
{
"platform": "ACTIONS_ON_GOOGLE",
"linkOutSuggestion": {"destinationName": name, "uri": url},
}
)
return self |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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] """ |
list_card = _ListSelector(
self._speech, display_text=self._display_text, title=title, items=items
)
return list_card |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_item(self, title, key, synonyms=None, description=None, img_url=None):
"""Adds item to a list or carousel card. A list must contain at least 2 items, each requiring a title and object key. Arguments: title {str} -- Name of the item object key {str} -- Key refering to the item. This string will be used to send a query to your app if selected Keyword Arguments: synonyms {list} -- Words and phrases the user may send to select the item (default: {None}) description {str} -- A description of the item (default: {None}) img_url {str} -- URL of the image to represent the item (default: {None}) """ |
item = build_item(title, key, synonyms, description, img_url)
self._items.append(item)
return self |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_intent(self, intent_id):
"""Returns the intent object with the given intent_id""" |
endpoint = self._intent_uri(intent_id=intent_id)
return self._get(endpoint) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def post_intent(self, intent_json):
"""Sends post request to create a new intent""" |
endpoint = self._intent_uri()
return self._post(endpoint, data=intent_json) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def put_intent(self, intent_id, intent_json):
"""Send a put request to update the intent with intent_id""" |
endpoint = self._intent_uri(intent_id)
return self._put(endpoint, intent_json) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def find_assistant():
# Taken from Flask-ask courtesy of @voutilad """ Find our instance of Assistant, navigating Local's and possible blueprints. Note: This only supports returning a reference to the first instance of Assistant found. """ |
if hasattr(current_app, "assist"):
return getattr(current_app, "assist")
else:
if hasattr(current_app, "blueprints"):
blueprints = getattr(current_app, "blueprints")
for blueprint_name in blueprints:
if hasattr(blueprints[blueprint_name], "assist"):
return getattr(blueprints[blueprint_name], "assist") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def action( self, intent_name, is_fallback=False, mapping={}, convert={}, default={}, with_context=[], events=[], *args, **kw ):
"""Decorates an intent_name's Action view function. The wrapped function is called when a request with the given intent_name is recieved along with all required parameters. """ |
def decorator(f):
action_funcs = self._intent_action_funcs.get(intent_name, [])
action_funcs.append(f)
self._intent_action_funcs[intent_name] = action_funcs
self._intent_mappings[intent_name] = mapping
self._intent_converts[intent_name] = convert
self._intent_defaults[intent_name] = default
self._intent_fallbacks[intent_name] = is_fallback
self._intent_events[intent_name] = events
self._register_context_to_func(intent_name, with_context)
@wraps(f)
def wrapper(*args, **kw):
self._flask_assitant_view_func(*args, **kw)
return f
return decorator |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def prompt_for(self, next_param, intent_name):
"""Decorates a function to prompt for an action's required parameter. The wrapped function is called if next_param was not recieved with the given intent's request and is required for the fulfillment of the intent's action. Arguments: next_param {str} -- name of the parameter required for action function intent_name {str} -- name of the intent the dependent action belongs to """ |
def decorator(f):
prompts = self._intent_prompts.get(intent_name)
if prompts:
prompts[next_param] = f
else:
self._intent_prompts[intent_name] = {}
self._intent_prompts[intent_name][next_param] = f
@wraps(f)
def wrapper(*args, **kw):
self._flask_assitant_view_func(*args, **kw)
return f
return decorator |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _context_views(self):
"""Returns view functions for which the context requirements are met""" |
possible_views = []
for func in self._func_contexts:
if self._context_satified(func):
logger.debug("{} context conditions satisified".format(func.__name__))
possible_views.append(func)
return possible_views |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_assistant(filename):
"""Imports a module from filename as a string, returns the contained Assistant object""" |
agent_name = os.path.splitext(filename)[0]
try:
agent_module = import_with_3(
agent_name, os.path.join(os.getcwd(), filename))
except ImportError:
agent_module = import_with_2(
agent_name, os.path.join(os.getcwd(), filename))
for name, obj in agent_module.__dict__.items():
if isinstance(obj, Assistant):
return obj |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _annotate_params(self, word):
"""Annotates a given word for the UserSays data field of an Intent object. Annotations are created using the entity map within the user_says.yaml template. """ |
annotation = {}
annotation['text'] = word
annotation['meta'] = '@' + self.entity_map[word]
annotation['alias'] = self.entity_map[word].replace('sys.', '')
annotation['userDefined'] = True
self.data.append(annotation) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def app_intents(self):
"""Returns a list of Intent objects created from the assistant's acion functions""" |
from_app = []
for intent_name in self.assist._intent_action_funcs:
intent = self.build_intent(intent_name)
from_app.append(intent)
return from_app |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def build_intent(self, intent_name):
"""Builds an Intent object of the given name""" |
# TODO: contexts
is_fallback = self.assist._intent_fallbacks[intent_name]
contexts = self.assist._required_contexts[intent_name]
events = self.assist._intent_events[intent_name]
new_intent = Intent(intent_name, fallback_intent=is_fallback, contexts=contexts, events=events)
self.build_action(new_intent)
self.build_user_says(new_intent) # TODO
return new_intent |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def parse_params(self, intent_name):
"""Parses params from an intent's action decorator and view function. Returns a list of parameter field dicts to be included in the intent object's response field. """ |
params = []
action_func = self.assist._intent_action_funcs[intent_name][0]
argspec = inspect.getargspec(action_func)
param_entity_map = self.assist._intent_mappings.get(intent_name)
args, defaults = argspec.args, argspec.defaults
default_map = {}
if defaults:
default_map = dict(zip(args[-len(defaults):], defaults))
# import ipdb; ipdb.set_trace()
for arg in args:
param_info = {}
param_entity = param_entity_map.get(arg, arg)
param_name = param_entity.replace('sys.', '')
# param_name = arg
param_info['name'] = param_name
param_info['value'] = '$' + param_name
param_info['dataType'] = '@' + param_entity
param_info['prompts'] = [] # TODO: fill in provided prompts
param_info['required'] = arg not in default_map
param_info['isList'] = isinstance(default_map.get(arg), list)
if param_info['isList']:
param_info['defaultValue'] = ''
else:
param_info['defaultValue'] = default_map.get(arg, '')
params.append(param_info)
return params |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def push_intent(self, intent):
"""Registers or updates an intent and returns the intent_json with an ID""" |
if intent.id:
print('Updating {} intent'.format(intent.name))
self.update(intent)
else:
print('Registering {} intent'.format(intent.name))
intent = self.register(intent)
return intent |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def register(self, intent):
"""Registers a new intent and returns the Intent object with an ID""" |
response = self.api.post_intent(intent.serialize)
print(response)
print()
if response['status']['code'] == 200:
intent.id = response['id']
elif response['status']['code'] == 409: # intent already exists
intent.id = next(i.id for i in self.api.agent_intents if i.name == intent.name)
self.update(intent)
return intent |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def register(self, entity):
"""Registers a new entity and returns the entity object with an ID""" |
response = self.api.post_entity(entity.serialize)
print(response)
print()
if response['status']['code'] == 200:
entity.id = response['id']
if response['status']['code'] == 409: # entity already exists
entity.id = next(i.id for i in self.api.agent_entities if i.name == entity.name)
self.update(entity)
return entity |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def push_entity(self, entity):
"""Registers or updates an entity and returns the entity_json with an ID""" |
if entity.id:
print('Updating {} entity'.format(entity.name))
self.update(entity)
else:
print('Registering {} entity'.format(entity.name))
entity = self.register(entity)
return entity |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def set_state(self, entity_id, new_state, **kwargs):
"Updates or creates the current state of an entity."
return remote.set_state(self.api, new_state, **kwargs) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.