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) dat...
<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() ...
<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 na...
<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(...
<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 _...
<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 retu...
<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): U...
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.....
<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 messa...
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 CON...
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')) ...
<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 a...
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 f...
<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].ta...
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._ser...
<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 ...
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 paramete...
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...
<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...
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 sl...
<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...
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...
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 %= (se...
<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 obje...
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: n...
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._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 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.' ...
<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 ...
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):...
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, filte...
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': {'libra...
<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, filterTel...
# 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) ...
<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 = 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 _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...
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) ...
<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 ...
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, ...
<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: ...
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(...
<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 pat...
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: # Jus...
<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, no...
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): i...
<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 pa...
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, Muta...
<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...
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: ...
<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 o...
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 give...
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) ...
<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 g...
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...
<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 c...
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...
<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)),...
<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 = flo...
<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 ...
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 o...
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, 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 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 sho...
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': retur...
<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) retur...
<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 12345678901234567890123456789012345678901234567890123456...
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)))...
<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, ...
<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":...
<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 gen...
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, eac...
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 onl...
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"): ...
<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 Ac...
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 ...
<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...
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) ...
<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.__d...
<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 ...
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) ...
<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...
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: ...
<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_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...
<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)