repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
52
3.87M
func_code_tokens
listlengths
15
672k
func_documentation_string
stringlengths
1
47.2k
func_documentation_tokens
listlengths
1
3.92k
split_name
stringclasses
1 value
func_code_url
stringlengths
85
339
rytilahti/python-songpal
songpal/device.py
Device.set_bluetooth_settings
async def set_bluetooth_settings(self, target: str, value: str) -> None: """Set bluetooth settings.""" params = {"settings": [{"target": target, "value": value}]} return await self.services["avContent"]["setBluetoothSettings"](params)
python
async def set_bluetooth_settings(self, target: str, value: str) -> None: """Set bluetooth settings.""" params = {"settings": [{"target": target, "value": value}]} return await self.services["avContent"]["setBluetoothSettings"](params)
[ "async", "def", "set_bluetooth_settings", "(", "self", ",", "target", ":", "str", ",", "value", ":", "str", ")", "->", "None", ":", "params", "=", "{", "\"settings\"", ":", "[", "{", "\"target\"", ":", "target", ",", "\"value\"", ":", "value", "}", "]", "}", "return", "await", "self", ".", "services", "[", "\"avContent\"", "]", "[", "\"setBluetoothSettings\"", "]", "(", "params", ")" ]
Set bluetooth settings.
[ "Set", "bluetooth", "settings", "." ]
train
https://github.com/rytilahti/python-songpal/blob/0443de6b3d960b9067a851d82261ca00e46b4618/songpal/device.py#L295-L298
rytilahti/python-songpal
songpal/device.py
Device.set_custom_eq
async def set_custom_eq(self, target: str, value: str) -> None: """Set custom EQ settings.""" params = {"settings": [{"target": target, "value": value}]} return await self.services["audio"]["setCustomEqualizerSettings"](params)
python
async def set_custom_eq(self, target: str, value: str) -> None: """Set custom EQ settings.""" params = {"settings": [{"target": target, "value": value}]} return await self.services["audio"]["setCustomEqualizerSettings"](params)
[ "async", "def", "set_custom_eq", "(", "self", ",", "target", ":", "str", ",", "value", ":", "str", ")", "->", "None", ":", "params", "=", "{", "\"settings\"", ":", "[", "{", "\"target\"", ":", "target", ",", "\"value\"", ":", "value", "}", "]", "}", "return", "await", "self", ".", "services", "[", "\"audio\"", "]", "[", "\"setCustomEqualizerSettings\"", "]", "(", "params", ")" ]
Set custom EQ settings.
[ "Set", "custom", "EQ", "settings", "." ]
train
https://github.com/rytilahti/python-songpal/blob/0443de6b3d960b9067a851d82261ca00e46b4618/songpal/device.py#L304-L307
rytilahti/python-songpal
songpal/device.py
Device.get_supported_playback_functions
async def get_supported_playback_functions( self, uri="" ) -> List[SupportedFunctions]: """Return list of inputs and their supported functions.""" return [ SupportedFunctions.make(**x) for x in await self.services["avContent"]["getSupportedPlaybackFunction"]( uri=uri ) ]
python
async def get_supported_playback_functions( self, uri="" ) -> List[SupportedFunctions]: """Return list of inputs and their supported functions.""" return [ SupportedFunctions.make(**x) for x in await self.services["avContent"]["getSupportedPlaybackFunction"]( uri=uri ) ]
[ "async", "def", "get_supported_playback_functions", "(", "self", ",", "uri", "=", "\"\"", ")", "->", "List", "[", "SupportedFunctions", "]", ":", "return", "[", "SupportedFunctions", ".", "make", "(", "*", "*", "x", ")", "for", "x", "in", "await", "self", ".", "services", "[", "\"avContent\"", "]", "[", "\"getSupportedPlaybackFunction\"", "]", "(", "uri", "=", "uri", ")", "]" ]
Return list of inputs and their supported functions.
[ "Return", "list", "of", "inputs", "and", "their", "supported", "functions", "." ]
train
https://github.com/rytilahti/python-songpal/blob/0443de6b3d960b9067a851d82261ca00e46b4618/songpal/device.py#L309-L318
rytilahti/python-songpal
songpal/device.py
Device.get_playback_settings
async def get_playback_settings(self) -> List[Setting]: """Get playback settings such as shuffle and repeat.""" return [ Setting.make(**x) for x in await self.services["avContent"]["getPlaybackModeSettings"]({}) ]
python
async def get_playback_settings(self) -> List[Setting]: """Get playback settings such as shuffle and repeat.""" return [ Setting.make(**x) for x in await self.services["avContent"]["getPlaybackModeSettings"]({}) ]
[ "async", "def", "get_playback_settings", "(", "self", ")", "->", "List", "[", "Setting", "]", ":", "return", "[", "Setting", ".", "make", "(", "*", "*", "x", ")", "for", "x", "in", "await", "self", ".", "services", "[", "\"avContent\"", "]", "[", "\"getPlaybackModeSettings\"", "]", "(", "{", "}", ")", "]" ]
Get playback settings such as shuffle and repeat.
[ "Get", "playback", "settings", "such", "as", "shuffle", "and", "repeat", "." ]
train
https://github.com/rytilahti/python-songpal/blob/0443de6b3d960b9067a851d82261ca00e46b4618/songpal/device.py#L320-L325
rytilahti/python-songpal
songpal/device.py
Device.set_playback_settings
async def set_playback_settings(self, target, value) -> None: """Set playback settings such a shuffle and repeat.""" params = {"settings": [{"target": target, "value": value}]} return await self.services["avContent"]["setPlaybackModeSettings"](params)
python
async def set_playback_settings(self, target, value) -> None: """Set playback settings such a shuffle and repeat.""" params = {"settings": [{"target": target, "value": value}]} return await self.services["avContent"]["setPlaybackModeSettings"](params)
[ "async", "def", "set_playback_settings", "(", "self", ",", "target", ",", "value", ")", "->", "None", ":", "params", "=", "{", "\"settings\"", ":", "[", "{", "\"target\"", ":", "target", ",", "\"value\"", ":", "value", "}", "]", "}", "return", "await", "self", ".", "services", "[", "\"avContent\"", "]", "[", "\"setPlaybackModeSettings\"", "]", "(", "params", ")" ]
Set playback settings such a shuffle and repeat.
[ "Set", "playback", "settings", "such", "a", "shuffle", "and", "repeat", "." ]
train
https://github.com/rytilahti/python-songpal/blob/0443de6b3d960b9067a851d82261ca00e46b4618/songpal/device.py#L327-L330
rytilahti/python-songpal
songpal/device.py
Device.get_schemes
async def get_schemes(self) -> List[Scheme]: """Return supported uri schemes.""" return [ Scheme.make(**x) for x in await self.services["avContent"]["getSchemeList"]() ]
python
async def get_schemes(self) -> List[Scheme]: """Return supported uri schemes.""" return [ Scheme.make(**x) for x in await self.services["avContent"]["getSchemeList"]() ]
[ "async", "def", "get_schemes", "(", "self", ")", "->", "List", "[", "Scheme", "]", ":", "return", "[", "Scheme", ".", "make", "(", "*", "*", "x", ")", "for", "x", "in", "await", "self", ".", "services", "[", "\"avContent\"", "]", "[", "\"getSchemeList\"", "]", "(", ")", "]" ]
Return supported uri schemes.
[ "Return", "supported", "uri", "schemes", "." ]
train
https://github.com/rytilahti/python-songpal/blob/0443de6b3d960b9067a851d82261ca00e46b4618/songpal/device.py#L332-L337
rytilahti/python-songpal
songpal/device.py
Device.get_source_list
async def get_source_list(self, scheme: str = "") -> List[Source]: """Return available sources for playback.""" res = await self.services["avContent"]["getSourceList"](scheme=scheme) return [Source.make(**x) for x in res]
python
async def get_source_list(self, scheme: str = "") -> List[Source]: """Return available sources for playback.""" res = await self.services["avContent"]["getSourceList"](scheme=scheme) return [Source.make(**x) for x in res]
[ "async", "def", "get_source_list", "(", "self", ",", "scheme", ":", "str", "=", "\"\"", ")", "->", "List", "[", "Source", "]", ":", "res", "=", "await", "self", ".", "services", "[", "\"avContent\"", "]", "[", "\"getSourceList\"", "]", "(", "scheme", "=", "scheme", ")", "return", "[", "Source", ".", "make", "(", "*", "*", "x", ")", "for", "x", "in", "res", "]" ]
Return available sources for playback.
[ "Return", "available", "sources", "for", "playback", "." ]
train
https://github.com/rytilahti/python-songpal/blob/0443de6b3d960b9067a851d82261ca00e46b4618/songpal/device.py#L339-L342
rytilahti/python-songpal
songpal/device.py
Device.get_content_count
async def get_content_count(self, source: str): """Return file listing for source.""" params = {"uri": source, "type": None, "target": "all", "view": "flat"} return ContentInfo.make( **await self.services["avContent"]["getContentCount"](params) )
python
async def get_content_count(self, source: str): """Return file listing for source.""" params = {"uri": source, "type": None, "target": "all", "view": "flat"} return ContentInfo.make( **await self.services["avContent"]["getContentCount"](params) )
[ "async", "def", "get_content_count", "(", "self", ",", "source", ":", "str", ")", ":", "params", "=", "{", "\"uri\"", ":", "source", ",", "\"type\"", ":", "None", ",", "\"target\"", ":", "\"all\"", ",", "\"view\"", ":", "\"flat\"", "}", "return", "ContentInfo", ".", "make", "(", "*", "*", "await", "self", ".", "services", "[", "\"avContent\"", "]", "[", "\"getContentCount\"", "]", "(", "params", ")", ")" ]
Return file listing for source.
[ "Return", "file", "listing", "for", "source", "." ]
train
https://github.com/rytilahti/python-songpal/blob/0443de6b3d960b9067a851d82261ca00e46b4618/songpal/device.py#L344-L349
rytilahti/python-songpal
songpal/device.py
Device.get_contents
async def get_contents(self, uri) -> List[Content]: """Request content listing recursively for the given URI. :param uri: URI for the source. :return: List of Content objects. """ contents = [ Content.make(**x) for x in await self.services["avContent"]["getContentList"](uri=uri) ] contentlist = [] for content in contents: if content.contentKind == "directory" and content.index >= 0: # print("got directory %s" % content.uri) res = await self.get_contents(content.uri) contentlist.extend(res) else: contentlist.append(content) # print("%s%s" % (' ' * depth, content)) return contentlist
python
async def get_contents(self, uri) -> List[Content]: """Request content listing recursively for the given URI. :param uri: URI for the source. :return: List of Content objects. """ contents = [ Content.make(**x) for x in await self.services["avContent"]["getContentList"](uri=uri) ] contentlist = [] for content in contents: if content.contentKind == "directory" and content.index >= 0: # print("got directory %s" % content.uri) res = await self.get_contents(content.uri) contentlist.extend(res) else: contentlist.append(content) # print("%s%s" % (' ' * depth, content)) return contentlist
[ "async", "def", "get_contents", "(", "self", ",", "uri", ")", "->", "List", "[", "Content", "]", ":", "contents", "=", "[", "Content", ".", "make", "(", "*", "*", "x", ")", "for", "x", "in", "await", "self", ".", "services", "[", "\"avContent\"", "]", "[", "\"getContentList\"", "]", "(", "uri", "=", "uri", ")", "]", "contentlist", "=", "[", "]", "for", "content", "in", "contents", ":", "if", "content", ".", "contentKind", "==", "\"directory\"", "and", "content", ".", "index", ">=", "0", ":", "# print(\"got directory %s\" % content.uri)", "res", "=", "await", "self", ".", "get_contents", "(", "content", ".", "uri", ")", "contentlist", ".", "extend", "(", "res", ")", "else", ":", "contentlist", ".", "append", "(", "content", ")", "# print(\"%s%s\" % (' ' * depth, content))", "return", "contentlist" ]
Request content listing recursively for the given URI. :param uri: URI for the source. :return: List of Content objects.
[ "Request", "content", "listing", "recursively", "for", "the", "given", "URI", "." ]
train
https://github.com/rytilahti/python-songpal/blob/0443de6b3d960b9067a851d82261ca00e46b4618/songpal/device.py#L351-L371
rytilahti/python-songpal
songpal/device.py
Device.get_volume_information
async def get_volume_information(self) -> List[Volume]: """Get the volume information.""" res = await self.services["audio"]["getVolumeInformation"]({}) volume_info = [Volume.make(services=self.services, **x) for x in res] if len(volume_info) < 1: logging.warning("Unable to get volume information") elif len(volume_info) > 1: logging.debug("The device seems to have more than one volume setting.") return volume_info
python
async def get_volume_information(self) -> List[Volume]: """Get the volume information.""" res = await self.services["audio"]["getVolumeInformation"]({}) volume_info = [Volume.make(services=self.services, **x) for x in res] if len(volume_info) < 1: logging.warning("Unable to get volume information") elif len(volume_info) > 1: logging.debug("The device seems to have more than one volume setting.") return volume_info
[ "async", "def", "get_volume_information", "(", "self", ")", "->", "List", "[", "Volume", "]", ":", "res", "=", "await", "self", ".", "services", "[", "\"audio\"", "]", "[", "\"getVolumeInformation\"", "]", "(", "{", "}", ")", "volume_info", "=", "[", "Volume", ".", "make", "(", "services", "=", "self", ".", "services", ",", "*", "*", "x", ")", "for", "x", "in", "res", "]", "if", "len", "(", "volume_info", ")", "<", "1", ":", "logging", ".", "warning", "(", "\"Unable to get volume information\"", ")", "elif", "len", "(", "volume_info", ")", ">", "1", ":", "logging", ".", "debug", "(", "\"The device seems to have more than one volume setting.\"", ")", "return", "volume_info" ]
Get the volume information.
[ "Get", "the", "volume", "information", "." ]
train
https://github.com/rytilahti/python-songpal/blob/0443de6b3d960b9067a851d82261ca00e46b4618/songpal/device.py#L373-L381
rytilahti/python-songpal
songpal/device.py
Device.get_sound_settings
async def get_sound_settings(self, target="") -> List[Setting]: """Get the current sound settings. :param str target: settings target, defaults to all. """ res = await self.services["audio"]["getSoundSettings"]({"target": target}) return [Setting.make(**x) for x in res]
python
async def get_sound_settings(self, target="") -> List[Setting]: """Get the current sound settings. :param str target: settings target, defaults to all. """ res = await self.services["audio"]["getSoundSettings"]({"target": target}) return [Setting.make(**x) for x in res]
[ "async", "def", "get_sound_settings", "(", "self", ",", "target", "=", "\"\"", ")", "->", "List", "[", "Setting", "]", ":", "res", "=", "await", "self", ".", "services", "[", "\"audio\"", "]", "[", "\"getSoundSettings\"", "]", "(", "{", "\"target\"", ":", "target", "}", ")", "return", "[", "Setting", ".", "make", "(", "*", "*", "x", ")", "for", "x", "in", "res", "]" ]
Get the current sound settings. :param str target: settings target, defaults to all.
[ "Get", "the", "current", "sound", "settings", "." ]
train
https://github.com/rytilahti/python-songpal/blob/0443de6b3d960b9067a851d82261ca00e46b4618/songpal/device.py#L383-L389
rytilahti/python-songpal
songpal/device.py
Device.get_soundfield
async def get_soundfield(self) -> List[Setting]: """Get the current sound field settings.""" res = await self.services["audio"]["getSoundSettings"]({"target": "soundField"}) return Setting.make(**res[0])
python
async def get_soundfield(self) -> List[Setting]: """Get the current sound field settings.""" res = await self.services["audio"]["getSoundSettings"]({"target": "soundField"}) return Setting.make(**res[0])
[ "async", "def", "get_soundfield", "(", "self", ")", "->", "List", "[", "Setting", "]", ":", "res", "=", "await", "self", ".", "services", "[", "\"audio\"", "]", "[", "\"getSoundSettings\"", "]", "(", "{", "\"target\"", ":", "\"soundField\"", "}", ")", "return", "Setting", ".", "make", "(", "*", "*", "res", "[", "0", "]", ")" ]
Get the current sound field settings.
[ "Get", "the", "current", "sound", "field", "settings", "." ]
train
https://github.com/rytilahti/python-songpal/blob/0443de6b3d960b9067a851d82261ca00e46b4618/songpal/device.py#L391-L394
rytilahti/python-songpal
songpal/device.py
Device.set_sound_settings
async def set_sound_settings(self, target: str, value: str): """Change a sound setting.""" params = {"settings": [{"target": target, "value": value}]} return await self.services["audio"]["setSoundSettings"](params)
python
async def set_sound_settings(self, target: str, value: str): """Change a sound setting.""" params = {"settings": [{"target": target, "value": value}]} return await self.services["audio"]["setSoundSettings"](params)
[ "async", "def", "set_sound_settings", "(", "self", ",", "target", ":", "str", ",", "value", ":", "str", ")", ":", "params", "=", "{", "\"settings\"", ":", "[", "{", "\"target\"", ":", "target", ",", "\"value\"", ":", "value", "}", "]", "}", "return", "await", "self", ".", "services", "[", "\"audio\"", "]", "[", "\"setSoundSettings\"", "]", "(", "params", ")" ]
Change a sound setting.
[ "Change", "a", "sound", "setting", "." ]
train
https://github.com/rytilahti/python-songpal/blob/0443de6b3d960b9067a851d82261ca00e46b4618/songpal/device.py#L400-L403
rytilahti/python-songpal
songpal/device.py
Device.get_speaker_settings
async def get_speaker_settings(self) -> List[Setting]: """Return speaker settings.""" speaker_settings = await self.services["audio"]["getSpeakerSettings"]({}) return [Setting.make(**x) for x in speaker_settings]
python
async def get_speaker_settings(self) -> List[Setting]: """Return speaker settings.""" speaker_settings = await self.services["audio"]["getSpeakerSettings"]({}) return [Setting.make(**x) for x in speaker_settings]
[ "async", "def", "get_speaker_settings", "(", "self", ")", "->", "List", "[", "Setting", "]", ":", "speaker_settings", "=", "await", "self", ".", "services", "[", "\"audio\"", "]", "[", "\"getSpeakerSettings\"", "]", "(", "{", "}", ")", "return", "[", "Setting", ".", "make", "(", "*", "*", "x", ")", "for", "x", "in", "speaker_settings", "]" ]
Return speaker settings.
[ "Return", "speaker", "settings", "." ]
train
https://github.com/rytilahti/python-songpal/blob/0443de6b3d960b9067a851d82261ca00e46b4618/songpal/device.py#L405-L408
rytilahti/python-songpal
songpal/device.py
Device.set_speaker_settings
async def set_speaker_settings(self, target: str, value: str): """Set speaker settings.""" params = {"settings": [{"target": target, "value": value}]} return await self.services["audio"]["setSpeakerSettings"](params)
python
async def set_speaker_settings(self, target: str, value: str): """Set speaker settings.""" params = {"settings": [{"target": target, "value": value}]} return await self.services["audio"]["setSpeakerSettings"](params)
[ "async", "def", "set_speaker_settings", "(", "self", ",", "target", ":", "str", ",", "value", ":", "str", ")", ":", "params", "=", "{", "\"settings\"", ":", "[", "{", "\"target\"", ":", "target", ",", "\"value\"", ":", "value", "}", "]", "}", "return", "await", "self", ".", "services", "[", "\"audio\"", "]", "[", "\"setSpeakerSettings\"", "]", "(", "params", ")" ]
Set speaker settings.
[ "Set", "speaker", "settings", "." ]
train
https://github.com/rytilahti/python-songpal/blob/0443de6b3d960b9067a851d82261ca00e46b4618/songpal/device.py#L410-L413
rytilahti/python-songpal
songpal/device.py
Device.listen_notifications
async def listen_notifications(self, fallback_callback=None): """Listen for notifications from the device forever. Use :func:on_notification: to register what notifications to listen to. """ tasks = [] async def handle_notification(notification): if type(notification) not in self.callbacks: if not fallback_callback: _LOGGER.debug("No callbacks for %s", notification) # _LOGGER.debug("Existing callbacks for: %s" % self.callbacks) else: await fallback_callback(notification) return for cb in self.callbacks[type(notification)]: await cb(notification) for serv in self.services.values(): tasks.append( asyncio.ensure_future( serv.listen_all_notifications(handle_notification) ) ) try: print(await asyncio.gather(*tasks)) except Exception as ex: # TODO: do a slightly restricted exception handling? # Notify about disconnect await handle_notification(ConnectChange(connected=False, exception=ex)) return
python
async def listen_notifications(self, fallback_callback=None): """Listen for notifications from the device forever. Use :func:on_notification: to register what notifications to listen to. """ tasks = [] async def handle_notification(notification): if type(notification) not in self.callbacks: if not fallback_callback: _LOGGER.debug("No callbacks for %s", notification) # _LOGGER.debug("Existing callbacks for: %s" % self.callbacks) else: await fallback_callback(notification) return for cb in self.callbacks[type(notification)]: await cb(notification) for serv in self.services.values(): tasks.append( asyncio.ensure_future( serv.listen_all_notifications(handle_notification) ) ) try: print(await asyncio.gather(*tasks)) except Exception as ex: # TODO: do a slightly restricted exception handling? # Notify about disconnect await handle_notification(ConnectChange(connected=False, exception=ex)) return
[ "async", "def", "listen_notifications", "(", "self", ",", "fallback_callback", "=", "None", ")", ":", "tasks", "=", "[", "]", "async", "def", "handle_notification", "(", "notification", ")", ":", "if", "type", "(", "notification", ")", "not", "in", "self", ".", "callbacks", ":", "if", "not", "fallback_callback", ":", "_LOGGER", ".", "debug", "(", "\"No callbacks for %s\"", ",", "notification", ")", "# _LOGGER.debug(\"Existing callbacks for: %s\" % self.callbacks)", "else", ":", "await", "fallback_callback", "(", "notification", ")", "return", "for", "cb", "in", "self", ".", "callbacks", "[", "type", "(", "notification", ")", "]", ":", "await", "cb", "(", "notification", ")", "for", "serv", "in", "self", ".", "services", ".", "values", "(", ")", ":", "tasks", ".", "append", "(", "asyncio", ".", "ensure_future", "(", "serv", ".", "listen_all_notifications", "(", "handle_notification", ")", ")", ")", "try", ":", "print", "(", "await", "asyncio", ".", "gather", "(", "*", "tasks", ")", ")", "except", "Exception", "as", "ex", ":", "# TODO: do a slightly restricted exception handling?", "# Notify about disconnect", "await", "handle_notification", "(", "ConnectChange", "(", "connected", "=", "False", ",", "exception", "=", "ex", ")", ")", "return" ]
Listen for notifications from the device forever. Use :func:on_notification: to register what notifications to listen to.
[ "Listen", "for", "notifications", "from", "the", "device", "forever", "." ]
train
https://github.com/rytilahti/python-songpal/blob/0443de6b3d960b9067a851d82261ca00e46b4618/songpal/device.py#L438-L469
rytilahti/python-songpal
songpal/device.py
Device.stop_listen_notifications
async def stop_listen_notifications(self): """Stop listening on notifications.""" _LOGGER.debug("Stopping listening for notifications..") for serv in self.services.values(): await serv.stop_listen_notifications() return True
python
async def stop_listen_notifications(self): """Stop listening on notifications.""" _LOGGER.debug("Stopping listening for notifications..") for serv in self.services.values(): await serv.stop_listen_notifications() return True
[ "async", "def", "stop_listen_notifications", "(", "self", ")", ":", "_LOGGER", ".", "debug", "(", "\"Stopping listening for notifications..\"", ")", "for", "serv", "in", "self", ".", "services", ".", "values", "(", ")", ":", "await", "serv", ".", "stop_listen_notifications", "(", ")", "return", "True" ]
Stop listening on notifications.
[ "Stop", "listening", "on", "notifications", "." ]
train
https://github.com/rytilahti/python-songpal/blob/0443de6b3d960b9067a851d82261ca00e46b4618/songpal/device.py#L471-L477
rytilahti/python-songpal
songpal/device.py
Device.get_notifications
async def get_notifications(self) -> List[Notification]: """Get available notifications, which can then be subscribed to. Call :func:activate: to enable notifications, and :func:listen_notifications: to loop forever for notifications. :return: List of Notification objects """ notifications = [] for serv in self.services: for notification in self.services[serv].notifications: notifications.append(notification) return notifications
python
async def get_notifications(self) -> List[Notification]: """Get available notifications, which can then be subscribed to. Call :func:activate: to enable notifications, and :func:listen_notifications: to loop forever for notifications. :return: List of Notification objects """ notifications = [] for serv in self.services: for notification in self.services[serv].notifications: notifications.append(notification) return notifications
[ "async", "def", "get_notifications", "(", "self", ")", "->", "List", "[", "Notification", "]", ":", "notifications", "=", "[", "]", "for", "serv", "in", "self", ".", "services", ":", "for", "notification", "in", "self", ".", "services", "[", "serv", "]", ".", "notifications", ":", "notifications", ".", "append", "(", "notification", ")", "return", "notifications" ]
Get available notifications, which can then be subscribed to. Call :func:activate: to enable notifications, and :func:listen_notifications: to loop forever for notifications. :return: List of Notification objects
[ "Get", "available", "notifications", "which", "can", "then", "be", "subscribed", "to", "." ]
train
https://github.com/rytilahti/python-songpal/blob/0443de6b3d960b9067a851d82261ca00e46b4618/songpal/device.py#L479-L491
rytilahti/python-songpal
songpal/device.py
Device.raw_command
async def raw_command(self, service: str, method: str, params: Any): """Call an arbitrary method with given parameters. This is useful for debugging and trying out commands before implementing them properly. :param service: Service, use list(self.services) to get a list of availables. :param method: Method to call. :param params: Parameters as a python object (e.g., dict, list) :return: Raw JSON response from the device. """ _LOGGER.info("Calling %s.%s(%s)", service, method, params) return await self.services[service][method](params)
python
async def raw_command(self, service: str, method: str, params: Any): """Call an arbitrary method with given parameters. This is useful for debugging and trying out commands before implementing them properly. :param service: Service, use list(self.services) to get a list of availables. :param method: Method to call. :param params: Parameters as a python object (e.g., dict, list) :return: Raw JSON response from the device. """ _LOGGER.info("Calling %s.%s(%s)", service, method, params) return await self.services[service][method](params)
[ "async", "def", "raw_command", "(", "self", ",", "service", ":", "str", ",", "method", ":", "str", ",", "params", ":", "Any", ")", ":", "_LOGGER", ".", "info", "(", "\"Calling %s.%s(%s)\"", ",", "service", ",", "method", ",", "params", ")", "return", "await", "self", ".", "services", "[", "service", "]", "[", "method", "]", "(", "params", ")" ]
Call an arbitrary method with given parameters. This is useful for debugging and trying out commands before implementing them properly. :param service: Service, use list(self.services) to get a list of availables. :param method: Method to call. :param params: Parameters as a python object (e.g., dict, list) :return: Raw JSON response from the device.
[ "Call", "an", "arbitrary", "method", "with", "given", "parameters", "." ]
train
https://github.com/rytilahti/python-songpal/blob/0443de6b3d960b9067a851d82261ca00e46b4618/songpal/device.py#L493-L504
rytilahti/python-songpal
songpal/group.py
GroupControl.connect
async def connect(self): requester = AiohttpRequester() factory = UpnpFactory(requester) device = await factory.async_create_device(self.url) self.service = device.service('urn:schemas-sony-com:service:Group:1') if not self.service: _LOGGER.error("Unable to find group service!") return False for act in self.service.actions.values(): _LOGGER.debug("Action: %s (%s)", act, [arg.name for arg in act.in_arguments()]) return True """ Available actions INFO:songpal.upnpctl:Action: <UpnpService.Action(X_GetDeviceInfo)> ([]) INFO:songpal.upnpctl:Action: <UpnpService.Action(X_GetState)> ([]) INFO:songpal.upnpctl:Action: <UpnpService.Action(X_GetStateM)> ([]) INFO:songpal.upnpctl:Action: <UpnpService.Action(X_SetGroupName)> (['GroupName']) INFO:songpal.upnpctl:Action: <UpnpService.Action(X_ChangeGroupVolume)> (['GroupVolume']) INFO:songpal.upnpctl:Action: <UpnpService.Action(X_GetAllGroupMemory)> ([]) INFO:songpal.upnpctl:Action: <UpnpService.Action(X_DeleteGroupMemory)> (['MemoryID']) INFO:songpal.upnpctl:Action: <UpnpService.Action(X_UpdateGroupMemory)> (['MemoryID', 'GroupMode', 'GroupName', 'SlaveList', 'CodecType', 'CodecBitrate']) INFO:songpal.upnpctl:Action: <UpnpService.Action(X_Start)> (['GroupMode', 'GroupName', 'SlaveList', 'CodecType', 'CodecBitrate']) INFO:songpal.upnpctl:Action: <UpnpService.Action(X_Entry)> (['MasterSessionID', 'SlaveList']) INFO:songpal.upnpctl:Action: <UpnpService.Action(X_EntryM)> (['MasterSessionID', 'SlaveList']) INFO:songpal.upnpctl:Action: <UpnpService.Action(X_Leave)> (['MasterSessionID', 'SlaveList']) INFO:songpal.upnpctl:Action: <UpnpService.Action(X_LeaveM)> (['MasterSessionID', 'SlaveList']) INFO:songpal.upnpctl:Action: <UpnpService.Action(X_Abort)> (['MasterSessionID']) INFO:songpal.upnpctl:Action: <UpnpService.Action(X_SetGroupMute)> (['GroupMute']) INFO:songpal.upnpctl:Action: <UpnpService.Action(X_SetCodec)> (['CodecType', 'CodecBitrate']) INFO:songpal.upnpctl:Action: <UpnpService.Action(X_GetCodec)> ([]) INFO:songpal.upnpctl:Action: <UpnpService.Action(X_Invite)> (['GroupMode', 'GroupName', 'MasterUUID', 'MasterSessionID']) INFO:songpal.upnpctl:Action: <UpnpService.Action(X_Exit)> (['SlaveSessionID']) INFO:songpal.upnpctl:Action: <UpnpService.Action(X_Play)> (['MasterSessionID']) INFO:songpal.upnpctl:Action: <UpnpService.Action(X_Stop)> (['MasterSessionID']) INFO:songpal.upnpctl:Action: <UpnpService.Action(X_Delegate)> (['GroupMode', 'SlaveList', 'DelegateURI', 'DelegateURIMetaData']) """
python
async def connect(self): requester = AiohttpRequester() factory = UpnpFactory(requester) device = await factory.async_create_device(self.url) self.service = device.service('urn:schemas-sony-com:service:Group:1') if not self.service: _LOGGER.error("Unable to find group service!") return False for act in self.service.actions.values(): _LOGGER.debug("Action: %s (%s)", act, [arg.name for arg in act.in_arguments()]) return True """ Available actions INFO:songpal.upnpctl:Action: <UpnpService.Action(X_GetDeviceInfo)> ([]) INFO:songpal.upnpctl:Action: <UpnpService.Action(X_GetState)> ([]) INFO:songpal.upnpctl:Action: <UpnpService.Action(X_GetStateM)> ([]) INFO:songpal.upnpctl:Action: <UpnpService.Action(X_SetGroupName)> (['GroupName']) INFO:songpal.upnpctl:Action: <UpnpService.Action(X_ChangeGroupVolume)> (['GroupVolume']) INFO:songpal.upnpctl:Action: <UpnpService.Action(X_GetAllGroupMemory)> ([]) INFO:songpal.upnpctl:Action: <UpnpService.Action(X_DeleteGroupMemory)> (['MemoryID']) INFO:songpal.upnpctl:Action: <UpnpService.Action(X_UpdateGroupMemory)> (['MemoryID', 'GroupMode', 'GroupName', 'SlaveList', 'CodecType', 'CodecBitrate']) INFO:songpal.upnpctl:Action: <UpnpService.Action(X_Start)> (['GroupMode', 'GroupName', 'SlaveList', 'CodecType', 'CodecBitrate']) INFO:songpal.upnpctl:Action: <UpnpService.Action(X_Entry)> (['MasterSessionID', 'SlaveList']) INFO:songpal.upnpctl:Action: <UpnpService.Action(X_EntryM)> (['MasterSessionID', 'SlaveList']) INFO:songpal.upnpctl:Action: <UpnpService.Action(X_Leave)> (['MasterSessionID', 'SlaveList']) INFO:songpal.upnpctl:Action: <UpnpService.Action(X_LeaveM)> (['MasterSessionID', 'SlaveList']) INFO:songpal.upnpctl:Action: <UpnpService.Action(X_Abort)> (['MasterSessionID']) INFO:songpal.upnpctl:Action: <UpnpService.Action(X_SetGroupMute)> (['GroupMute']) INFO:songpal.upnpctl:Action: <UpnpService.Action(X_SetCodec)> (['CodecType', 'CodecBitrate']) INFO:songpal.upnpctl:Action: <UpnpService.Action(X_GetCodec)> ([]) INFO:songpal.upnpctl:Action: <UpnpService.Action(X_Invite)> (['GroupMode', 'GroupName', 'MasterUUID', 'MasterSessionID']) INFO:songpal.upnpctl:Action: <UpnpService.Action(X_Exit)> (['SlaveSessionID']) INFO:songpal.upnpctl:Action: <UpnpService.Action(X_Play)> (['MasterSessionID']) INFO:songpal.upnpctl:Action: <UpnpService.Action(X_Stop)> (['MasterSessionID']) INFO:songpal.upnpctl:Action: <UpnpService.Action(X_Delegate)> (['GroupMode', 'SlaveList', 'DelegateURI', 'DelegateURIMetaData']) """
[ "async", "def", "connect", "(", "self", ")", ":", "requester", "=", "AiohttpRequester", "(", ")", "factory", "=", "UpnpFactory", "(", "requester", ")", "device", "=", "await", "factory", ".", "async_create_device", "(", "self", ".", "url", ")", "self", ".", "service", "=", "device", ".", "service", "(", "'urn:schemas-sony-com:service:Group:1'", ")", "if", "not", "self", ".", "service", ":", "_LOGGER", ".", "error", "(", "\"Unable to find group service!\"", ")", "return", "False", "for", "act", "in", "self", ".", "service", ".", "actions", ".", "values", "(", ")", ":", "_LOGGER", ".", "debug", "(", "\"Action: %s (%s)\"", ",", "act", ",", "[", "arg", ".", "name", "for", "arg", "in", "act", ".", "in_arguments", "(", ")", "]", ")", "return", "True" ]
Available actions INFO:songpal.upnpctl:Action: <UpnpService.Action(X_GetDeviceInfo)> ([]) INFO:songpal.upnpctl:Action: <UpnpService.Action(X_GetState)> ([]) INFO:songpal.upnpctl:Action: <UpnpService.Action(X_GetStateM)> ([]) INFO:songpal.upnpctl:Action: <UpnpService.Action(X_SetGroupName)> (['GroupName']) INFO:songpal.upnpctl:Action: <UpnpService.Action(X_ChangeGroupVolume)> (['GroupVolume']) INFO:songpal.upnpctl:Action: <UpnpService.Action(X_GetAllGroupMemory)> ([]) INFO:songpal.upnpctl:Action: <UpnpService.Action(X_DeleteGroupMemory)> (['MemoryID']) INFO:songpal.upnpctl:Action: <UpnpService.Action(X_UpdateGroupMemory)> (['MemoryID', 'GroupMode', 'GroupName', 'SlaveList', 'CodecType', 'CodecBitrate']) INFO:songpal.upnpctl:Action: <UpnpService.Action(X_Start)> (['GroupMode', 'GroupName', 'SlaveList', 'CodecType', 'CodecBitrate']) INFO:songpal.upnpctl:Action: <UpnpService.Action(X_Entry)> (['MasterSessionID', 'SlaveList']) INFO:songpal.upnpctl:Action: <UpnpService.Action(X_EntryM)> (['MasterSessionID', 'SlaveList']) INFO:songpal.upnpctl:Action: <UpnpService.Action(X_Leave)> (['MasterSessionID', 'SlaveList']) INFO:songpal.upnpctl:Action: <UpnpService.Action(X_LeaveM)> (['MasterSessionID', 'SlaveList']) INFO:songpal.upnpctl:Action: <UpnpService.Action(X_Abort)> (['MasterSessionID']) INFO:songpal.upnpctl:Action: <UpnpService.Action(X_SetGroupMute)> (['GroupMute']) INFO:songpal.upnpctl:Action: <UpnpService.Action(X_SetCodec)> (['CodecType', 'CodecBitrate']) INFO:songpal.upnpctl:Action: <UpnpService.Action(X_GetCodec)> ([]) INFO:songpal.upnpctl:Action: <UpnpService.Action(X_Invite)> (['GroupMode', 'GroupName', 'MasterUUID', 'MasterSessionID']) INFO:songpal.upnpctl:Action: <UpnpService.Action(X_Exit)> (['SlaveSessionID']) INFO:songpal.upnpctl:Action: <UpnpService.Action(X_Play)> (['MasterSessionID']) INFO:songpal.upnpctl:Action: <UpnpService.Action(X_Stop)> (['MasterSessionID']) INFO:songpal.upnpctl:Action: <UpnpService.Action(X_Delegate)> (['GroupMode', 'SlaveList', 'DelegateURI', 'DelegateURIMetaData'])
[ "Available", "actions" ]
train
https://github.com/rytilahti/python-songpal/blob/0443de6b3d960b9067a851d82261ca00e46b4618/songpal/group.py#L83-L124
rytilahti/python-songpal
songpal/group.py
GroupControl.call
async def call(self, action, **kwargs): """Make an action call with given kwargs.""" act = self.service.action(action) _LOGGER.info("Calling %s with %s", action, kwargs) res = await act.async_call(**kwargs) _LOGGER.info(" Result: %s" % res) return res
python
async def call(self, action, **kwargs): """Make an action call with given kwargs.""" act = self.service.action(action) _LOGGER.info("Calling %s with %s", action, kwargs) res = await act.async_call(**kwargs) _LOGGER.info(" Result: %s" % res) return res
[ "async", "def", "call", "(", "self", ",", "action", ",", "*", "*", "kwargs", ")", ":", "act", "=", "self", ".", "service", ".", "action", "(", "action", ")", "_LOGGER", ".", "info", "(", "\"Calling %s with %s\"", ",", "action", ",", "kwargs", ")", "res", "=", "await", "act", ".", "async_call", "(", "*", "*", "kwargs", ")", "_LOGGER", ".", "info", "(", "\" Result: %s\"", "%", "res", ")", "return", "res" ]
Make an action call with given kwargs.
[ "Make", "an", "action", "call", "with", "given", "kwargs", "." ]
train
https://github.com/rytilahti/python-songpal/blob/0443de6b3d960b9067a851d82261ca00e46b4618/songpal/group.py#L125-L133
rytilahti/python-songpal
songpal/group.py
GroupControl.info
async def info(self): """Return device info.""" """ {'MasterCapability': 9, 'TransportPort': 3975} """ act = self.service.action("X_GetDeviceInfo") res = await act.async_call() return res
python
async def info(self): """Return device info.""" """ {'MasterCapability': 9, 'TransportPort': 3975} """ act = self.service.action("X_GetDeviceInfo") res = await act.async_call() return res
[ "async", "def", "info", "(", "self", ")", ":", "\"\"\"\n {'MasterCapability': 9, 'TransportPort': 3975}\n \"\"\"", "act", "=", "self", ".", "service", ".", "action", "(", "\"X_GetDeviceInfo\"", ")", "res", "=", "await", "act", ".", "async_call", "(", ")", "return", "res" ]
Return device info.
[ "Return", "device", "info", "." ]
train
https://github.com/rytilahti/python-songpal/blob/0443de6b3d960b9067a851d82261ca00e46b4618/songpal/group.py#L136-L143
rytilahti/python-songpal
songpal/group.py
GroupControl.state
async def state(self) -> GroupState: """Return the current group state""" act = self.service.action("X_GetState") res = await act.async_call() return GroupState.make(**res)
python
async def state(self) -> GroupState: """Return the current group state""" act = self.service.action("X_GetState") res = await act.async_call() return GroupState.make(**res)
[ "async", "def", "state", "(", "self", ")", "->", "GroupState", ":", "act", "=", "self", ".", "service", ".", "action", "(", "\"X_GetState\"", ")", "res", "=", "await", "act", ".", "async_call", "(", ")", "return", "GroupState", ".", "make", "(", "*", "*", "res", ")" ]
Return the current group state
[ "Return", "the", "current", "group", "state" ]
train
https://github.com/rytilahti/python-songpal/blob/0443de6b3d960b9067a851d82261ca00e46b4618/songpal/group.py#L145-L149
rytilahti/python-songpal
songpal/group.py
GroupControl.get_group_memory
async def get_group_memory(self): """Return group memory.""" # Returns an XML with groupMemoryList act = self.service.action("X_GetAllGroupMemory") res = await act.async_call() return res
python
async def get_group_memory(self): """Return group memory.""" # Returns an XML with groupMemoryList act = self.service.action("X_GetAllGroupMemory") res = await act.async_call() return res
[ "async", "def", "get_group_memory", "(", "self", ")", ":", "# Returns an XML with groupMemoryList", "act", "=", "self", ".", "service", ".", "action", "(", "\"X_GetAllGroupMemory\"", ")", "res", "=", "await", "act", ".", "async_call", "(", ")", "return", "res" ]
Return group memory.
[ "Return", "group", "memory", "." ]
train
https://github.com/rytilahti/python-songpal/blob/0443de6b3d960b9067a851d82261ca00e46b4618/songpal/group.py#L157-L162
rytilahti/python-songpal
songpal/group.py
GroupControl.update_group_memory
async def update_group_memory(self, memory_id, mode, name, slaves, codectype=0x0040, bitrate=0x0003): """Update existing memory? Can be used to create new ones, too?""" act = self.service.action("X_UpdateGroupMemory") res = await act.async_call(MemoryID=memory_id, GroupMode=mode, GroupName=name, SlaveList=slaves, CodecType=codectype, CodecBitrate=bitrate) return res
python
async def update_group_memory(self, memory_id, mode, name, slaves, codectype=0x0040, bitrate=0x0003): """Update existing memory? Can be used to create new ones, too?""" act = self.service.action("X_UpdateGroupMemory") res = await act.async_call(MemoryID=memory_id, GroupMode=mode, GroupName=name, SlaveList=slaves, CodecType=codectype, CodecBitrate=bitrate) return res
[ "async", "def", "update_group_memory", "(", "self", ",", "memory_id", ",", "mode", ",", "name", ",", "slaves", ",", "codectype", "=", "0x0040", ",", "bitrate", "=", "0x0003", ")", ":", "act", "=", "self", ".", "service", ".", "action", "(", "\"X_UpdateGroupMemory\"", ")", "res", "=", "await", "act", ".", "async_call", "(", "MemoryID", "=", "memory_id", ",", "GroupMode", "=", "mode", ",", "GroupName", "=", "name", ",", "SlaveList", "=", "slaves", ",", "CodecType", "=", "codectype", ",", "CodecBitrate", "=", "bitrate", ")", "return", "res" ]
Update existing memory? Can be used to create new ones, too?
[ "Update", "existing", "memory?", "Can", "be", "used", "to", "create", "new", "ones", "too?" ]
train
https://github.com/rytilahti/python-songpal/blob/0443de6b3d960b9067a851d82261ca00e46b4618/songpal/group.py#L164-L174
rytilahti/python-songpal
songpal/group.py
GroupControl.delete_group_memory
async def delete_group_memory(self, memory_id): """Delete group memory.""" act = self.service.action("X_DeleteGroupMemory") res = await act.async_call(MemoryID=memory_id)
python
async def delete_group_memory(self, memory_id): """Delete group memory.""" act = self.service.action("X_DeleteGroupMemory") res = await act.async_call(MemoryID=memory_id)
[ "async", "def", "delete_group_memory", "(", "self", ",", "memory_id", ")", ":", "act", "=", "self", ".", "service", ".", "action", "(", "\"X_DeleteGroupMemory\"", ")", "res", "=", "await", "act", ".", "async_call", "(", "MemoryID", "=", "memory_id", ")" ]
Delete group memory.
[ "Delete", "group", "memory", "." ]
train
https://github.com/rytilahti/python-songpal/blob/0443de6b3d960b9067a851d82261ca00e46b4618/songpal/group.py#L176-L179
rytilahti/python-songpal
songpal/group.py
GroupControl.get_codec
async def get_codec(self): """Get codec settings.""" act = self.service.action("X_GetCodec") res = await act.async_call() return res
python
async def get_codec(self): """Get codec settings.""" act = self.service.action("X_GetCodec") res = await act.async_call() return res
[ "async", "def", "get_codec", "(", "self", ")", ":", "act", "=", "self", ".", "service", ".", "action", "(", "\"X_GetCodec\"", ")", "res", "=", "await", "act", ".", "async_call", "(", ")", "return", "res" ]
Get codec settings.
[ "Get", "codec", "settings", "." ]
train
https://github.com/rytilahti/python-songpal/blob/0443de6b3d960b9067a851d82261ca00e46b4618/songpal/group.py#L181-L185
rytilahti/python-songpal
songpal/group.py
GroupControl.set_codec
async def set_codec(self, codectype=0x0040, bitrate=0x0003): """Set codec settings.""" act = self.service.action("X_SetCodec") res = await act.async_call(CodecType=codectype, CodecBitrate=bitrate) return res
python
async def set_codec(self, codectype=0x0040, bitrate=0x0003): """Set codec settings.""" act = self.service.action("X_SetCodec") res = await act.async_call(CodecType=codectype, CodecBitrate=bitrate) return res
[ "async", "def", "set_codec", "(", "self", ",", "codectype", "=", "0x0040", ",", "bitrate", "=", "0x0003", ")", ":", "act", "=", "self", ".", "service", ".", "action", "(", "\"X_SetCodec\"", ")", "res", "=", "await", "act", ".", "async_call", "(", "CodecType", "=", "codectype", ",", "CodecBitrate", "=", "bitrate", ")", "return", "res" ]
Set codec settings.
[ "Set", "codec", "settings", "." ]
train
https://github.com/rytilahti/python-songpal/blob/0443de6b3d960b9067a851d82261ca00e46b4618/songpal/group.py#L187-L191
rytilahti/python-songpal
songpal/group.py
GroupControl.abort
async def abort(self): """Abort current group session.""" state = await self.state() res = await self.call("X_Abort", MasterSessionID=state.MasterSessionID) return res
python
async def abort(self): """Abort current group session.""" state = await self.state() res = await self.call("X_Abort", MasterSessionID=state.MasterSessionID) return res
[ "async", "def", "abort", "(", "self", ")", ":", "state", "=", "await", "self", ".", "state", "(", ")", "res", "=", "await", "self", ".", "call", "(", "\"X_Abort\"", ",", "MasterSessionID", "=", "state", ".", "MasterSessionID", ")", "return", "res" ]
Abort current group session.
[ "Abort", "current", "group", "session", "." ]
train
https://github.com/rytilahti/python-songpal/blob/0443de6b3d960b9067a851d82261ca00e46b4618/songpal/group.py#L193-L197
rytilahti/python-songpal
songpal/group.py
GroupControl.stop
async def stop(self): """Stop playback?""" state = await self.state() res = await self.call("X_Stop", MasterSessionID=state.MasterSessionID) return res
python
async def stop(self): """Stop playback?""" state = await self.state() res = await self.call("X_Stop", MasterSessionID=state.MasterSessionID) return res
[ "async", "def", "stop", "(", "self", ")", ":", "state", "=", "await", "self", ".", "state", "(", ")", "res", "=", "await", "self", ".", "call", "(", "\"X_Stop\"", ",", "MasterSessionID", "=", "state", ".", "MasterSessionID", ")", "return", "res" ]
Stop playback?
[ "Stop", "playback?" ]
train
https://github.com/rytilahti/python-songpal/blob/0443de6b3d960b9067a851d82261ca00e46b4618/songpal/group.py#L199-L203
rytilahti/python-songpal
songpal/group.py
GroupControl.play
async def play(self): """Start playback?""" state = await self.state() res = await self.call("X_Play", MasterSessionID=state.MasterSessionID) return res
python
async def play(self): """Start playback?""" state = await self.state() res = await self.call("X_Play", MasterSessionID=state.MasterSessionID) return res
[ "async", "def", "play", "(", "self", ")", ":", "state", "=", "await", "self", ".", "state", "(", ")", "res", "=", "await", "self", ".", "call", "(", "\"X_Play\"", ",", "MasterSessionID", "=", "state", ".", "MasterSessionID", ")", "return", "res" ]
Start playback?
[ "Start", "playback?" ]
train
https://github.com/rytilahti/python-songpal/blob/0443de6b3d960b9067a851d82261ca00e46b4618/songpal/group.py#L205-L209
rytilahti/python-songpal
songpal/group.py
GroupControl.create
async def create(self, name, slaves): """Create a group.""" # NOTE: codectype and codecbitrate were simply chosen from an example.. res = await self.call("X_Start", GroupMode="GROUP", GroupName=name, SlaveList=",".join(slaves), CodecType=0x0040, CodecBitrate=0x0003) return res
python
async def create(self, name, slaves): """Create a group.""" # NOTE: codectype and codecbitrate were simply chosen from an example.. res = await self.call("X_Start", GroupMode="GROUP", GroupName=name, SlaveList=",".join(slaves), CodecType=0x0040, CodecBitrate=0x0003) return res
[ "async", "def", "create", "(", "self", ",", "name", ",", "slaves", ")", ":", "# NOTE: codectype and codecbitrate were simply chosen from an example..", "res", "=", "await", "self", ".", "call", "(", "\"X_Start\"", ",", "GroupMode", "=", "\"GROUP\"", ",", "GroupName", "=", "name", ",", "SlaveList", "=", "\",\"", ".", "join", "(", "slaves", ")", ",", "CodecType", "=", "0x0040", ",", "CodecBitrate", "=", "0x0003", ")", "return", "res" ]
Create a group.
[ "Create", "a", "group", "." ]
train
https://github.com/rytilahti/python-songpal/blob/0443de6b3d960b9067a851d82261ca00e46b4618/songpal/group.py#L211-L219
rytilahti/python-songpal
songpal/service.py
Service.fetch_signatures
async def fetch_signatures(endpoint, protocol, idgen): """Request available methods for the service.""" async with aiohttp.ClientSession() as session: req = { "method": "getMethodTypes", "params": [''], "version": "1.0", "id": next(idgen), } if protocol == ProtocolType.WebSocket: async with session.ws_connect(endpoint, timeout=2) as s: await s.send_json(req) res = await s.receive_json() return res else: res = await session.post(endpoint, json=req) json = await res.json() return json
python
async def fetch_signatures(endpoint, protocol, idgen): """Request available methods for the service.""" async with aiohttp.ClientSession() as session: req = { "method": "getMethodTypes", "params": [''], "version": "1.0", "id": next(idgen), } if protocol == ProtocolType.WebSocket: async with session.ws_connect(endpoint, timeout=2) as s: await s.send_json(req) res = await s.receive_json() return res else: res = await session.post(endpoint, json=req) json = await res.json() return json
[ "async", "def", "fetch_signatures", "(", "endpoint", ",", "protocol", ",", "idgen", ")", ":", "async", "with", "aiohttp", ".", "ClientSession", "(", ")", "as", "session", ":", "req", "=", "{", "\"method\"", ":", "\"getMethodTypes\"", ",", "\"params\"", ":", "[", "''", "]", ",", "\"version\"", ":", "\"1.0\"", ",", "\"id\"", ":", "next", "(", "idgen", ")", ",", "}", "if", "protocol", "==", "ProtocolType", ".", "WebSocket", ":", "async", "with", "session", ".", "ws_connect", "(", "endpoint", ",", "timeout", "=", "2", ")", "as", "s", ":", "await", "s", ".", "send_json", "(", "req", ")", "res", "=", "await", "s", ".", "receive_json", "(", ")", "return", "res", "else", ":", "res", "=", "await", "session", ".", "post", "(", "endpoint", ",", "json", "=", "req", ")", "json", "=", "await", "res", ".", "json", "(", ")", "return", "json" ]
Request available methods for the service.
[ "Request", "available", "methods", "for", "the", "service", "." ]
train
https://github.com/rytilahti/python-songpal/blob/0443de6b3d960b9067a851d82261ca00e46b4618/songpal/service.py#L41-L60
rytilahti/python-songpal
songpal/service.py
Service.from_payload
async def from_payload(cls, payload, endpoint, idgen, debug, force_protocol=None): """Create Service object from a payload.""" service_name = payload["service"] if "protocols" not in payload: raise SongpalException( "Unable to find protocols from payload: %s" % payload ) protocols = payload["protocols"] _LOGGER.debug("Available protocols for %s: %s", service_name, protocols) if force_protocol and force_protocol.value in protocols: protocol = force_protocol elif "websocket:jsonizer" in protocols: protocol = ProtocolType.WebSocket elif "xhrpost:jsonizer" in protocols: protocol = ProtocolType.XHRPost else: raise SongpalException( "No known protocols for %s, got: %s" % (service_name, protocols) ) _LOGGER.debug("Using protocol: %s" % protocol) service_endpoint = "%s/%s" % (endpoint, service_name) # creation here we want to pass the created service class to methods. service = cls(service_name, service_endpoint, protocol, idgen, debug) sigs = await cls.fetch_signatures( service_endpoint, protocol, idgen ) if debug > 1: _LOGGER.debug("Signatures: %s", sigs) if "error" in sigs: _LOGGER.error("Got error when fetching sigs: %s", sigs["error"]) return None methods = {} for sig in sigs["results"]: name = sig[0] parsed_sig = MethodSignature.from_payload(*sig) if name in methods: _LOGGER.debug("Got duplicate signature for %s, existing was %s. Keeping the existing one", parsed_sig, methods[name]) else: methods[name] = Method(service, parsed_sig, debug) service.methods = methods if "notifications" in payload and "switchNotifications" in methods: notifications = [ Notification( service_endpoint, methods["switchNotifications"], notification ) for notification in payload["notifications"] ] service.notifications = notifications _LOGGER.debug("Got notifications: %s" % notifications) return service
python
async def from_payload(cls, payload, endpoint, idgen, debug, force_protocol=None): """Create Service object from a payload.""" service_name = payload["service"] if "protocols" not in payload: raise SongpalException( "Unable to find protocols from payload: %s" % payload ) protocols = payload["protocols"] _LOGGER.debug("Available protocols for %s: %s", service_name, protocols) if force_protocol and force_protocol.value in protocols: protocol = force_protocol elif "websocket:jsonizer" in protocols: protocol = ProtocolType.WebSocket elif "xhrpost:jsonizer" in protocols: protocol = ProtocolType.XHRPost else: raise SongpalException( "No known protocols for %s, got: %s" % (service_name, protocols) ) _LOGGER.debug("Using protocol: %s" % protocol) service_endpoint = "%s/%s" % (endpoint, service_name) # creation here we want to pass the created service class to methods. service = cls(service_name, service_endpoint, protocol, idgen, debug) sigs = await cls.fetch_signatures( service_endpoint, protocol, idgen ) if debug > 1: _LOGGER.debug("Signatures: %s", sigs) if "error" in sigs: _LOGGER.error("Got error when fetching sigs: %s", sigs["error"]) return None methods = {} for sig in sigs["results"]: name = sig[0] parsed_sig = MethodSignature.from_payload(*sig) if name in methods: _LOGGER.debug("Got duplicate signature for %s, existing was %s. Keeping the existing one", parsed_sig, methods[name]) else: methods[name] = Method(service, parsed_sig, debug) service.methods = methods if "notifications" in payload and "switchNotifications" in methods: notifications = [ Notification( service_endpoint, methods["switchNotifications"], notification ) for notification in payload["notifications"] ] service.notifications = notifications _LOGGER.debug("Got notifications: %s" % notifications) return service
[ "async", "def", "from_payload", "(", "cls", ",", "payload", ",", "endpoint", ",", "idgen", ",", "debug", ",", "force_protocol", "=", "None", ")", ":", "service_name", "=", "payload", "[", "\"service\"", "]", "if", "\"protocols\"", "not", "in", "payload", ":", "raise", "SongpalException", "(", "\"Unable to find protocols from payload: %s\"", "%", "payload", ")", "protocols", "=", "payload", "[", "\"protocols\"", "]", "_LOGGER", ".", "debug", "(", "\"Available protocols for %s: %s\"", ",", "service_name", ",", "protocols", ")", "if", "force_protocol", "and", "force_protocol", ".", "value", "in", "protocols", ":", "protocol", "=", "force_protocol", "elif", "\"websocket:jsonizer\"", "in", "protocols", ":", "protocol", "=", "ProtocolType", ".", "WebSocket", "elif", "\"xhrpost:jsonizer\"", "in", "protocols", ":", "protocol", "=", "ProtocolType", ".", "XHRPost", "else", ":", "raise", "SongpalException", "(", "\"No known protocols for %s, got: %s\"", "%", "(", "service_name", ",", "protocols", ")", ")", "_LOGGER", ".", "debug", "(", "\"Using protocol: %s\"", "%", "protocol", ")", "service_endpoint", "=", "\"%s/%s\"", "%", "(", "endpoint", ",", "service_name", ")", "# creation here we want to pass the created service class to methods.", "service", "=", "cls", "(", "service_name", ",", "service_endpoint", ",", "protocol", ",", "idgen", ",", "debug", ")", "sigs", "=", "await", "cls", ".", "fetch_signatures", "(", "service_endpoint", ",", "protocol", ",", "idgen", ")", "if", "debug", ">", "1", ":", "_LOGGER", ".", "debug", "(", "\"Signatures: %s\"", ",", "sigs", ")", "if", "\"error\"", "in", "sigs", ":", "_LOGGER", ".", "error", "(", "\"Got error when fetching sigs: %s\"", ",", "sigs", "[", "\"error\"", "]", ")", "return", "None", "methods", "=", "{", "}", "for", "sig", "in", "sigs", "[", "\"results\"", "]", ":", "name", "=", "sig", "[", "0", "]", "parsed_sig", "=", "MethodSignature", ".", "from_payload", "(", "*", "sig", ")", "if", "name", "in", "methods", ":", "_LOGGER", ".", "debug", "(", "\"Got duplicate signature for %s, existing was %s. Keeping the existing one\"", ",", "parsed_sig", ",", "methods", "[", "name", "]", ")", "else", ":", "methods", "[", "name", "]", "=", "Method", "(", "service", ",", "parsed_sig", ",", "debug", ")", "service", ".", "methods", "=", "methods", "if", "\"notifications\"", "in", "payload", "and", "\"switchNotifications\"", "in", "methods", ":", "notifications", "=", "[", "Notification", "(", "service_endpoint", ",", "methods", "[", "\"switchNotifications\"", "]", ",", "notification", ")", "for", "notification", "in", "payload", "[", "\"notifications\"", "]", "]", "service", ".", "notifications", "=", "notifications", "_LOGGER", ".", "debug", "(", "\"Got notifications: %s\"", "%", "notifications", ")", "return", "service" ]
Create Service object from a payload.
[ "Create", "Service", "object", "from", "a", "payload", "." ]
train
https://github.com/rytilahti/python-songpal/blob/0443de6b3d960b9067a851d82261ca00e46b4618/songpal/service.py#L63-L124
rytilahti/python-songpal
songpal/service.py
Service.call_method
async def call_method(self, method, *args, **kwargs): """Call a method (internal). This is an internal implementation, which formats the parameters if necessary and chooses the preferred transport protocol. The return values are JSON objects. Use :func:__call__: provides external API leveraging this. """ _LOGGER.debug( "%s got called with args (%s) kwargs (%s)" % (method.name, args, kwargs) ) # Used for allowing keeping reading from the socket _consumer = None if "_consumer" in kwargs: if self.active_protocol != ProtocolType.WebSocket: raise SongpalException( "Notifications are only supported over websockets" ) _consumer = kwargs["_consumer"] del kwargs["_consumer"] if len(kwargs) == 0 and len(args) == 0: params = [] # params need to be empty array, if none is given elif len(kwargs) > 0: params = [kwargs] elif len(args) == 1 and args[0] is not None: params = [args[0]] else: params = [] # TODO check for type correctness # TODO note parameters are not always necessary, see getPlaybackModeSettings # which has 'target' and 'uri' but works just fine without anything (wildcard) # if len(params) != len(self._inputs): # _LOGGER.error("args: %s signature: %s" % (args, # self.signature.input)) # raise Exception("Invalid number of inputs, wanted %s got %s / %s" % ( # len(self.signature.input), len(args), len(kwargs))) async with aiohttp.ClientSession() as session: req = { "method": method.name, "params": params, "version": method.version, "id": next(self.idgen), } if self.debug > 1: _LOGGER.debug("sending request: %s (proto: %s)", req, self.active_protocol) if self.active_protocol == ProtocolType.WebSocket: async with session.ws_connect( self.endpoint, timeout=self.timeout, heartbeat=self.timeout * 5 ) as s: await s.send_json(req) # If we have a consumer, we are going to loop forever while # emiting the incoming payloads to e.g. notification handler. if _consumer is not None: self.listening = True while self.listening: res_raw = await s.receive_json() res = self.wrap_notification(res_raw) _LOGGER.debug("Got notification: %s", res) if self.debug > 1: _LOGGER.debug("Got notification raw: %s", res_raw) await _consumer(res) res = await s.receive_json() return res else: res = await session.post(self.endpoint, json=req) return await res.json()
python
async def call_method(self, method, *args, **kwargs): """Call a method (internal). This is an internal implementation, which formats the parameters if necessary and chooses the preferred transport protocol. The return values are JSON objects. Use :func:__call__: provides external API leveraging this. """ _LOGGER.debug( "%s got called with args (%s) kwargs (%s)" % (method.name, args, kwargs) ) # Used for allowing keeping reading from the socket _consumer = None if "_consumer" in kwargs: if self.active_protocol != ProtocolType.WebSocket: raise SongpalException( "Notifications are only supported over websockets" ) _consumer = kwargs["_consumer"] del kwargs["_consumer"] if len(kwargs) == 0 and len(args) == 0: params = [] # params need to be empty array, if none is given elif len(kwargs) > 0: params = [kwargs] elif len(args) == 1 and args[0] is not None: params = [args[0]] else: params = [] # TODO check for type correctness # TODO note parameters are not always necessary, see getPlaybackModeSettings # which has 'target' and 'uri' but works just fine without anything (wildcard) # if len(params) != len(self._inputs): # _LOGGER.error("args: %s signature: %s" % (args, # self.signature.input)) # raise Exception("Invalid number of inputs, wanted %s got %s / %s" % ( # len(self.signature.input), len(args), len(kwargs))) async with aiohttp.ClientSession() as session: req = { "method": method.name, "params": params, "version": method.version, "id": next(self.idgen), } if self.debug > 1: _LOGGER.debug("sending request: %s (proto: %s)", req, self.active_protocol) if self.active_protocol == ProtocolType.WebSocket: async with session.ws_connect( self.endpoint, timeout=self.timeout, heartbeat=self.timeout * 5 ) as s: await s.send_json(req) # If we have a consumer, we are going to loop forever while # emiting the incoming payloads to e.g. notification handler. if _consumer is not None: self.listening = True while self.listening: res_raw = await s.receive_json() res = self.wrap_notification(res_raw) _LOGGER.debug("Got notification: %s", res) if self.debug > 1: _LOGGER.debug("Got notification raw: %s", res_raw) await _consumer(res) res = await s.receive_json() return res else: res = await session.post(self.endpoint, json=req) return await res.json()
[ "async", "def", "call_method", "(", "self", ",", "method", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "_LOGGER", ".", "debug", "(", "\"%s got called with args (%s) kwargs (%s)\"", "%", "(", "method", ".", "name", ",", "args", ",", "kwargs", ")", ")", "# Used for allowing keeping reading from the socket", "_consumer", "=", "None", "if", "\"_consumer\"", "in", "kwargs", ":", "if", "self", ".", "active_protocol", "!=", "ProtocolType", ".", "WebSocket", ":", "raise", "SongpalException", "(", "\"Notifications are only supported over websockets\"", ")", "_consumer", "=", "kwargs", "[", "\"_consumer\"", "]", "del", "kwargs", "[", "\"_consumer\"", "]", "if", "len", "(", "kwargs", ")", "==", "0", "and", "len", "(", "args", ")", "==", "0", ":", "params", "=", "[", "]", "# params need to be empty array, if none is given", "elif", "len", "(", "kwargs", ")", ">", "0", ":", "params", "=", "[", "kwargs", "]", "elif", "len", "(", "args", ")", "==", "1", "and", "args", "[", "0", "]", "is", "not", "None", ":", "params", "=", "[", "args", "[", "0", "]", "]", "else", ":", "params", "=", "[", "]", "# TODO check for type correctness", "# TODO note parameters are not always necessary, see getPlaybackModeSettings", "# which has 'target' and 'uri' but works just fine without anything (wildcard)", "# if len(params) != len(self._inputs):", "# _LOGGER.error(\"args: %s signature: %s\" % (args,", "# self.signature.input))", "# raise Exception(\"Invalid number of inputs, wanted %s got %s / %s\" % (", "# len(self.signature.input), len(args), len(kwargs)))", "async", "with", "aiohttp", ".", "ClientSession", "(", ")", "as", "session", ":", "req", "=", "{", "\"method\"", ":", "method", ".", "name", ",", "\"params\"", ":", "params", ",", "\"version\"", ":", "method", ".", "version", ",", "\"id\"", ":", "next", "(", "self", ".", "idgen", ")", ",", "}", "if", "self", ".", "debug", ">", "1", ":", "_LOGGER", ".", "debug", "(", "\"sending request: %s (proto: %s)\"", ",", "req", ",", "self", ".", "active_protocol", ")", "if", "self", ".", "active_protocol", "==", "ProtocolType", ".", "WebSocket", ":", "async", "with", "session", ".", "ws_connect", "(", "self", ".", "endpoint", ",", "timeout", "=", "self", ".", "timeout", ",", "heartbeat", "=", "self", ".", "timeout", "*", "5", ")", "as", "s", ":", "await", "s", ".", "send_json", "(", "req", ")", "# If we have a consumer, we are going to loop forever while", "# emiting the incoming payloads to e.g. notification handler.", "if", "_consumer", "is", "not", "None", ":", "self", ".", "listening", "=", "True", "while", "self", ".", "listening", ":", "res_raw", "=", "await", "s", ".", "receive_json", "(", ")", "res", "=", "self", ".", "wrap_notification", "(", "res_raw", ")", "_LOGGER", ".", "debug", "(", "\"Got notification: %s\"", ",", "res", ")", "if", "self", ".", "debug", ">", "1", ":", "_LOGGER", ".", "debug", "(", "\"Got notification raw: %s\"", ",", "res_raw", ")", "await", "_consumer", "(", "res", ")", "res", "=", "await", "s", ".", "receive_json", "(", ")", "return", "res", "else", ":", "res", "=", "await", "session", ".", "post", "(", "self", ".", "endpoint", ",", "json", "=", "req", ")", "return", "await", "res", ".", "json", "(", ")" ]
Call a method (internal). This is an internal implementation, which formats the parameters if necessary and chooses the preferred transport protocol. The return values are JSON objects. Use :func:__call__: provides external API leveraging this.
[ "Call", "a", "method", "(", "internal", ")", "." ]
train
https://github.com/rytilahti/python-songpal/blob/0443de6b3d960b9067a851d82261ca00e46b4618/songpal/service.py#L126-L197
rytilahti/python-songpal
songpal/service.py
Service.wrap_notification
def wrap_notification(self, data): """Convert notification JSON to a notification class.""" if "method" in data: method = data["method"] params = data["params"] change = params[0] if method == "notifyPowerStatus": return PowerChange.make(**change) elif method == "notifyVolumeInformation": return VolumeChange.make(**change) elif method == "notifyPlayingContentInfo": return ContentChange.make(**change) elif method == "notifySettingsUpdate": return SettingChange.make(**change) elif method == "notifySWUpdateInfo": return SoftwareUpdateChange.make(**change) else: _LOGGER.warning("Got unknown notification type: %s", method) elif "result" in data: result = data["result"][0] if "enabled" in result and "enabled" in result: return NotificationChange(**result) else: _LOGGER.warning("Unknown notification, returning raw: %s", data) return data
python
def wrap_notification(self, data): """Convert notification JSON to a notification class.""" if "method" in data: method = data["method"] params = data["params"] change = params[0] if method == "notifyPowerStatus": return PowerChange.make(**change) elif method == "notifyVolumeInformation": return VolumeChange.make(**change) elif method == "notifyPlayingContentInfo": return ContentChange.make(**change) elif method == "notifySettingsUpdate": return SettingChange.make(**change) elif method == "notifySWUpdateInfo": return SoftwareUpdateChange.make(**change) else: _LOGGER.warning("Got unknown notification type: %s", method) elif "result" in data: result = data["result"][0] if "enabled" in result and "enabled" in result: return NotificationChange(**result) else: _LOGGER.warning("Unknown notification, returning raw: %s", data) return data
[ "def", "wrap_notification", "(", "self", ",", "data", ")", ":", "if", "\"method\"", "in", "data", ":", "method", "=", "data", "[", "\"method\"", "]", "params", "=", "data", "[", "\"params\"", "]", "change", "=", "params", "[", "0", "]", "if", "method", "==", "\"notifyPowerStatus\"", ":", "return", "PowerChange", ".", "make", "(", "*", "*", "change", ")", "elif", "method", "==", "\"notifyVolumeInformation\"", ":", "return", "VolumeChange", ".", "make", "(", "*", "*", "change", ")", "elif", "method", "==", "\"notifyPlayingContentInfo\"", ":", "return", "ContentChange", ".", "make", "(", "*", "*", "change", ")", "elif", "method", "==", "\"notifySettingsUpdate\"", ":", "return", "SettingChange", ".", "make", "(", "*", "*", "change", ")", "elif", "method", "==", "\"notifySWUpdateInfo\"", ":", "return", "SoftwareUpdateChange", ".", "make", "(", "*", "*", "change", ")", "else", ":", "_LOGGER", ".", "warning", "(", "\"Got unknown notification type: %s\"", ",", "method", ")", "elif", "\"result\"", "in", "data", ":", "result", "=", "data", "[", "\"result\"", "]", "[", "0", "]", "if", "\"enabled\"", "in", "result", "and", "\"enabled\"", "in", "result", ":", "return", "NotificationChange", "(", "*", "*", "result", ")", "else", ":", "_LOGGER", ".", "warning", "(", "\"Unknown notification, returning raw: %s\"", ",", "data", ")", "return", "data" ]
Convert notification JSON to a notification class.
[ "Convert", "notification", "JSON", "to", "a", "notification", "class", "." ]
train
https://github.com/rytilahti/python-songpal/blob/0443de6b3d960b9067a851d82261ca00e46b4618/songpal/service.py#L199-L223
rytilahti/python-songpal
songpal/service.py
Service.listen_all_notifications
async def listen_all_notifications(self, callback): """Enable all exposed notifications. :param callback: Callback to call when a notification is received. """ everything = [noti.asdict() for noti in self.notifications] if len(everything) > 0: await self._methods["switchNotifications"]( {"enabled": everything}, _consumer=callback ) else: _LOGGER.debug("No notifications available for %s", self.name)
python
async def listen_all_notifications(self, callback): """Enable all exposed notifications. :param callback: Callback to call when a notification is received. """ everything = [noti.asdict() for noti in self.notifications] if len(everything) > 0: await self._methods["switchNotifications"]( {"enabled": everything}, _consumer=callback ) else: _LOGGER.debug("No notifications available for %s", self.name)
[ "async", "def", "listen_all_notifications", "(", "self", ",", "callback", ")", ":", "everything", "=", "[", "noti", ".", "asdict", "(", ")", "for", "noti", "in", "self", ".", "notifications", "]", "if", "len", "(", "everything", ")", ">", "0", ":", "await", "self", ".", "_methods", "[", "\"switchNotifications\"", "]", "(", "{", "\"enabled\"", ":", "everything", "}", ",", "_consumer", "=", "callback", ")", "else", ":", "_LOGGER", ".", "debug", "(", "\"No notifications available for %s\"", ",", "self", ".", "name", ")" ]
Enable all exposed notifications. :param callback: Callback to call when a notification is received.
[ "Enable", "all", "exposed", "notifications", "." ]
train
https://github.com/rytilahti/python-songpal/blob/0443de6b3d960b9067a851d82261ca00e46b4618/songpal/service.py#L266-L277
rytilahti/python-songpal
songpal/service.py
Service.asdict
def asdict(self): """Return dict presentation of this service. Useful for dumping the device information into JSON. """ return { "methods": {m.name: m.asdict() for m in self.methods}, "protocols": self.protocols, "notifications": {n.name: n.asdict() for n in self.notifications}, }
python
def asdict(self): """Return dict presentation of this service. Useful for dumping the device information into JSON. """ return { "methods": {m.name: m.asdict() for m in self.methods}, "protocols": self.protocols, "notifications": {n.name: n.asdict() for n in self.notifications}, }
[ "def", "asdict", "(", "self", ")", ":", "return", "{", "\"methods\"", ":", "{", "m", ".", "name", ":", "m", ".", "asdict", "(", ")", "for", "m", "in", "self", ".", "methods", "}", ",", "\"protocols\"", ":", "self", ".", "protocols", ",", "\"notifications\"", ":", "{", "n", ".", "name", ":", "n", ".", "asdict", "(", ")", "for", "n", "in", "self", ".", "notifications", "}", ",", "}" ]
Return dict presentation of this service. Useful for dumping the device information into JSON.
[ "Return", "dict", "presentation", "of", "this", "service", "." ]
train
https://github.com/rytilahti/python-songpal/blob/0443de6b3d960b9067a851d82261ca00e46b4618/songpal/service.py#L283-L292
scivision/lowtran
lowtran/scenarios.py
horizrad
def horizrad(infn: Path, outfn: Path, c1: dict) -> xarray.Dataset: """ read CSV, simulate, write, plot """ if infn is not None: infn = Path(infn).expanduser() if infn.suffix == '.h5': TR = xarray.open_dataset(infn) return TR c1.update({'model': 0, # 0: user meterological data 'itype': 1, # 1: horizontal path 'iemsct': 1, # 1: radiance model 'im': 1, # 1: for horizontal path (see Lowtran manual p.42) 'ird1': 1, # 1: use card 2C2) }) # %% read csv file if not infn: # demo mode c1['p'] = [949., 959.] c1['t'] = [283.8, 285.] c1['wmol'] = [[93.96, 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.], [93.96, 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.]] c1['time'] = [parse('2017-04-05T12'), parse('2017-04-05T18')] else: # read csv, normal case PTdata = read_csv(infn) c1['p'] = PTdata['p'] c1['t'] = PTdata['Ta'] c1['wmol'] = np.zeros((PTdata.shape[0], 12)) c1['wmol'][:, 0] = PTdata['RH'] c1['time'] = [parse(t) for t in PTdata['time']] # %% TR is 3-D array with axes: time, wavelength, and [transmission,radiance] TR = loopuserdef(c1) return TR
python
def horizrad(infn: Path, outfn: Path, c1: dict) -> xarray.Dataset: """ read CSV, simulate, write, plot """ if infn is not None: infn = Path(infn).expanduser() if infn.suffix == '.h5': TR = xarray.open_dataset(infn) return TR c1.update({'model': 0, # 0: user meterological data 'itype': 1, # 1: horizontal path 'iemsct': 1, # 1: radiance model 'im': 1, # 1: for horizontal path (see Lowtran manual p.42) 'ird1': 1, # 1: use card 2C2) }) # %% read csv file if not infn: # demo mode c1['p'] = [949., 959.] c1['t'] = [283.8, 285.] c1['wmol'] = [[93.96, 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.], [93.96, 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.]] c1['time'] = [parse('2017-04-05T12'), parse('2017-04-05T18')] else: # read csv, normal case PTdata = read_csv(infn) c1['p'] = PTdata['p'] c1['t'] = PTdata['Ta'] c1['wmol'] = np.zeros((PTdata.shape[0], 12)) c1['wmol'][:, 0] = PTdata['RH'] c1['time'] = [parse(t) for t in PTdata['time']] # %% TR is 3-D array with axes: time, wavelength, and [transmission,radiance] TR = loopuserdef(c1) return TR
[ "def", "horizrad", "(", "infn", ":", "Path", ",", "outfn", ":", "Path", ",", "c1", ":", "dict", ")", "->", "xarray", ".", "Dataset", ":", "if", "infn", "is", "not", "None", ":", "infn", "=", "Path", "(", "infn", ")", ".", "expanduser", "(", ")", "if", "infn", ".", "suffix", "==", "'.h5'", ":", "TR", "=", "xarray", ".", "open_dataset", "(", "infn", ")", "return", "TR", "c1", ".", "update", "(", "{", "'model'", ":", "0", ",", "# 0: user meterological data", "'itype'", ":", "1", ",", "# 1: horizontal path", "'iemsct'", ":", "1", ",", "# 1: radiance model", "'im'", ":", "1", ",", "# 1: for horizontal path (see Lowtran manual p.42)", "'ird1'", ":", "1", ",", "# 1: use card 2C2)", "}", ")", "# %% read csv file", "if", "not", "infn", ":", "# demo mode", "c1", "[", "'p'", "]", "=", "[", "949.", ",", "959.", "]", "c1", "[", "'t'", "]", "=", "[", "283.8", ",", "285.", "]", "c1", "[", "'wmol'", "]", "=", "[", "[", "93.96", ",", "0.", ",", "0.", ",", "0.", ",", "0.", ",", "0.", ",", "0.", ",", "0.", ",", "0.", ",", "0.", ",", "0.", ",", "0.", "]", ",", "[", "93.96", ",", "0.", ",", "0.", ",", "0.", ",", "0.", ",", "0.", ",", "0.", ",", "0.", ",", "0.", ",", "0.", ",", "0.", ",", "0.", "]", "]", "c1", "[", "'time'", "]", "=", "[", "parse", "(", "'2017-04-05T12'", ")", ",", "parse", "(", "'2017-04-05T18'", ")", "]", "else", ":", "# read csv, normal case", "PTdata", "=", "read_csv", "(", "infn", ")", "c1", "[", "'p'", "]", "=", "PTdata", "[", "'p'", "]", "c1", "[", "'t'", "]", "=", "PTdata", "[", "'Ta'", "]", "c1", "[", "'wmol'", "]", "=", "np", ".", "zeros", "(", "(", "PTdata", ".", "shape", "[", "0", "]", ",", "12", ")", ")", "c1", "[", "'wmol'", "]", "[", ":", ",", "0", "]", "=", "PTdata", "[", "'RH'", "]", "c1", "[", "'time'", "]", "=", "[", "parse", "(", "t", ")", "for", "t", "in", "PTdata", "[", "'time'", "]", "]", "# %% TR is 3-D array with axes: time, wavelength, and [transmission,radiance]", "TR", "=", "loopuserdef", "(", "c1", ")", "return", "TR" ]
read CSV, simulate, write, plot
[ "read", "CSV", "simulate", "write", "plot" ]
train
https://github.com/scivision/lowtran/blob/9954d859e53437436103f9ab54a7e2602ecaa1b7/lowtran/scenarios.py#L50-L85
scivision/lowtran
lowtran/base.py
nm2lt7
def nm2lt7(short_nm: float, long_nm: float, step_cminv: float = 20) -> Tuple[float, float, float]: """converts wavelength in nm to cm^-1 minimum meaningful step is 20, but 5 is minimum before crashing lowtran short: shortest wavelength e.g. 200 nm long: longest wavelength e.g. 30000 nm step: step size in cm^-1 e.g. 20 output in cm^-1 """ short = 1e7 / short_nm long = 1e7 / long_nm N = int(np.ceil((short-long) / step_cminv)) + 1 # yes, ceil return short, long, N
python
def nm2lt7(short_nm: float, long_nm: float, step_cminv: float = 20) -> Tuple[float, float, float]: """converts wavelength in nm to cm^-1 minimum meaningful step is 20, but 5 is minimum before crashing lowtran short: shortest wavelength e.g. 200 nm long: longest wavelength e.g. 30000 nm step: step size in cm^-1 e.g. 20 output in cm^-1 """ short = 1e7 / short_nm long = 1e7 / long_nm N = int(np.ceil((short-long) / step_cminv)) + 1 # yes, ceil return short, long, N
[ "def", "nm2lt7", "(", "short_nm", ":", "float", ",", "long_nm", ":", "float", ",", "step_cminv", ":", "float", "=", "20", ")", "->", "Tuple", "[", "float", ",", "float", ",", "float", "]", ":", "short", "=", "1e7", "/", "short_nm", "long", "=", "1e7", "/", "long_nm", "N", "=", "int", "(", "np", ".", "ceil", "(", "(", "short", "-", "long", ")", "/", "step_cminv", ")", ")", "+", "1", "# yes, ceil", "return", "short", ",", "long", ",", "N" ]
converts wavelength in nm to cm^-1 minimum meaningful step is 20, but 5 is minimum before crashing lowtran short: shortest wavelength e.g. 200 nm long: longest wavelength e.g. 30000 nm step: step size in cm^-1 e.g. 20 output in cm^-1
[ "converts", "wavelength", "in", "nm", "to", "cm^", "-", "1", "minimum", "meaningful", "step", "is", "20", "but", "5", "is", "minimum", "before", "crashing", "lowtran" ]
train
https://github.com/scivision/lowtran/blob/9954d859e53437436103f9ab54a7e2602ecaa1b7/lowtran/base.py#L12-L27
scivision/lowtran
lowtran/base.py
loopuserdef
def loopuserdef(c1: Dict[str, Any]) -> xarray.DataArray: """ golowtran() is for scalar parameters only (besides vector of wavelength, which Lowtran internally loops over) wmol, p, t must all be vector(s) of same length """ wmol = np.atleast_2d(c1['wmol']) P = np.atleast_1d(c1['p']) T = np.atleast_1d(c1['t']) time = np.atleast_1d(c1['time']) assert wmol.shape[0] == len(P) == len(T) == len(time), 'WMOL, P, T,time must be vectors of equal length' N = len(P) # %% 3-D array indexed by metadata TR = xarray.Dataset(coords={'time': time, 'wavelength_nm': None, 'angle_deg': None}) for i in range(N): c = c1.copy() c['wmol'] = wmol[i, :] c['p'] = P[i] c['t'] = T[i] c['time'] = time[i] TR = TR.merge(golowtran(c)) # TR = TR.sort_index(axis=0) # put times in order, sometimes CSV is not monotonic in time. return TR
python
def loopuserdef(c1: Dict[str, Any]) -> xarray.DataArray: """ golowtran() is for scalar parameters only (besides vector of wavelength, which Lowtran internally loops over) wmol, p, t must all be vector(s) of same length """ wmol = np.atleast_2d(c1['wmol']) P = np.atleast_1d(c1['p']) T = np.atleast_1d(c1['t']) time = np.atleast_1d(c1['time']) assert wmol.shape[0] == len(P) == len(T) == len(time), 'WMOL, P, T,time must be vectors of equal length' N = len(P) # %% 3-D array indexed by metadata TR = xarray.Dataset(coords={'time': time, 'wavelength_nm': None, 'angle_deg': None}) for i in range(N): c = c1.copy() c['wmol'] = wmol[i, :] c['p'] = P[i] c['t'] = T[i] c['time'] = time[i] TR = TR.merge(golowtran(c)) # TR = TR.sort_index(axis=0) # put times in order, sometimes CSV is not monotonic in time. return TR
[ "def", "loopuserdef", "(", "c1", ":", "Dict", "[", "str", ",", "Any", "]", ")", "->", "xarray", ".", "DataArray", ":", "wmol", "=", "np", ".", "atleast_2d", "(", "c1", "[", "'wmol'", "]", ")", "P", "=", "np", ".", "atleast_1d", "(", "c1", "[", "'p'", "]", ")", "T", "=", "np", ".", "atleast_1d", "(", "c1", "[", "'t'", "]", ")", "time", "=", "np", ".", "atleast_1d", "(", "c1", "[", "'time'", "]", ")", "assert", "wmol", ".", "shape", "[", "0", "]", "==", "len", "(", "P", ")", "==", "len", "(", "T", ")", "==", "len", "(", "time", ")", ",", "'WMOL, P, T,time must be vectors of equal length'", "N", "=", "len", "(", "P", ")", "# %% 3-D array indexed by metadata", "TR", "=", "xarray", ".", "Dataset", "(", "coords", "=", "{", "'time'", ":", "time", ",", "'wavelength_nm'", ":", "None", ",", "'angle_deg'", ":", "None", "}", ")", "for", "i", "in", "range", "(", "N", ")", ":", "c", "=", "c1", ".", "copy", "(", ")", "c", "[", "'wmol'", "]", "=", "wmol", "[", "i", ",", ":", "]", "c", "[", "'p'", "]", "=", "P", "[", "i", "]", "c", "[", "'t'", "]", "=", "T", "[", "i", "]", "c", "[", "'time'", "]", "=", "time", "[", "i", "]", "TR", "=", "TR", ".", "merge", "(", "golowtran", "(", "c", ")", ")", "# TR = TR.sort_index(axis=0) # put times in order, sometimes CSV is not monotonic in time.", "return", "TR" ]
golowtran() is for scalar parameters only (besides vector of wavelength, which Lowtran internally loops over) wmol, p, t must all be vector(s) of same length
[ "golowtran", "()", "is", "for", "scalar", "parameters", "only", "(", "besides", "vector", "of", "wavelength", "which", "Lowtran", "internally", "loops", "over", ")" ]
train
https://github.com/scivision/lowtran/blob/9954d859e53437436103f9ab54a7e2602ecaa1b7/lowtran/base.py#L30-L60
scivision/lowtran
lowtran/base.py
loopangle
def loopangle(c1: Dict[str, Any]) -> xarray.Dataset: """ loop over "ANGLE" """ angles = np.atleast_1d(c1['angle']) TR = xarray.Dataset(coords={'wavelength_nm': None, 'angle_deg': angles}) for a in angles: c = c1.copy() c['angle'] = a TR = TR.merge(golowtran(c)) return TR
python
def loopangle(c1: Dict[str, Any]) -> xarray.Dataset: """ loop over "ANGLE" """ angles = np.atleast_1d(c1['angle']) TR = xarray.Dataset(coords={'wavelength_nm': None, 'angle_deg': angles}) for a in angles: c = c1.copy() c['angle'] = a TR = TR.merge(golowtran(c)) return TR
[ "def", "loopangle", "(", "c1", ":", "Dict", "[", "str", ",", "Any", "]", ")", "->", "xarray", ".", "Dataset", ":", "angles", "=", "np", ".", "atleast_1d", "(", "c1", "[", "'angle'", "]", ")", "TR", "=", "xarray", ".", "Dataset", "(", "coords", "=", "{", "'wavelength_nm'", ":", "None", ",", "'angle_deg'", ":", "angles", "}", ")", "for", "a", "in", "angles", ":", "c", "=", "c1", ".", "copy", "(", ")", "c", "[", "'angle'", "]", "=", "a", "TR", "=", "TR", ".", "merge", "(", "golowtran", "(", "c", ")", ")", "return", "TR" ]
loop over "ANGLE"
[ "loop", "over", "ANGLE" ]
train
https://github.com/scivision/lowtran/blob/9954d859e53437436103f9ab54a7e2602ecaa1b7/lowtran/base.py#L63-L75
scivision/lowtran
lowtran/base.py
golowtran
def golowtran(c1: Dict[str, Any]) -> xarray.Dataset: """directly run Fortran code""" # %% default parameters c1.setdefault('time', None) defp = ('h1', 'h2', 'angle', 'im', 'iseasn', 'ird1', 'range_km', 'zmdl', 'p', 't') for p in defp: c1.setdefault(p, 0) c1.setdefault('wmol', [0]*12) # %% input check assert len(c1['wmol']) == 12, 'see Lowtran user manual for 12 values of WMOL' assert np.isfinite(c1['h1']), 'per Lowtran user manual Table 14, H1 must always be defined' # %% setup wavelength c1.setdefault('wlstep', 20) if c1['wlstep'] < 5: logging.critical('minimum resolution 5 cm^-1, specified resolution 20 cm^-1') wlshort, wllong, nwl = nm2lt7(c1['wlshort'], c1['wllong'], c1['wlstep']) if not 0 < wlshort and wllong <= 50000: logging.critical('specified model range 0 <= wavelength [cm^-1] <= 50000') # %% invoke lowtran """ Note we invoke case "3a" from table 14, only observer altitude and apparent angle are specified """ Tx, V, Alam, trace, unif, suma, irrad, sumvv = lowtran7.lwtrn7( True, nwl, wllong, wlshort, c1['wlstep'], c1['model'], c1['itype'], c1['iemsct'], c1['im'], c1['iseasn'], c1['ird1'], c1['zmdl'], c1['p'], c1['t'], c1['wmol'], c1['h1'], c1['h2'], c1['angle'], c1['range_km']) dims = ('time', 'wavelength_nm', 'angle_deg') TR = xarray.Dataset({'transmission': (dims, Tx[:, 9][None, :, None]), 'radiance': (dims, sumvv[None, :, None]), 'irradiance': (dims, irrad[:, 0][None, :, None]), 'pathscatter': (dims, irrad[:, 2][None, :, None])}, coords={'time': [c1['time']], 'wavelength_nm': Alam*1e3, 'angle_deg': [c1['angle']]}) return TR
python
def golowtran(c1: Dict[str, Any]) -> xarray.Dataset: """directly run Fortran code""" # %% default parameters c1.setdefault('time', None) defp = ('h1', 'h2', 'angle', 'im', 'iseasn', 'ird1', 'range_km', 'zmdl', 'p', 't') for p in defp: c1.setdefault(p, 0) c1.setdefault('wmol', [0]*12) # %% input check assert len(c1['wmol']) == 12, 'see Lowtran user manual for 12 values of WMOL' assert np.isfinite(c1['h1']), 'per Lowtran user manual Table 14, H1 must always be defined' # %% setup wavelength c1.setdefault('wlstep', 20) if c1['wlstep'] < 5: logging.critical('minimum resolution 5 cm^-1, specified resolution 20 cm^-1') wlshort, wllong, nwl = nm2lt7(c1['wlshort'], c1['wllong'], c1['wlstep']) if not 0 < wlshort and wllong <= 50000: logging.critical('specified model range 0 <= wavelength [cm^-1] <= 50000') # %% invoke lowtran """ Note we invoke case "3a" from table 14, only observer altitude and apparent angle are specified """ Tx, V, Alam, trace, unif, suma, irrad, sumvv = lowtran7.lwtrn7( True, nwl, wllong, wlshort, c1['wlstep'], c1['model'], c1['itype'], c1['iemsct'], c1['im'], c1['iseasn'], c1['ird1'], c1['zmdl'], c1['p'], c1['t'], c1['wmol'], c1['h1'], c1['h2'], c1['angle'], c1['range_km']) dims = ('time', 'wavelength_nm', 'angle_deg') TR = xarray.Dataset({'transmission': (dims, Tx[:, 9][None, :, None]), 'radiance': (dims, sumvv[None, :, None]), 'irradiance': (dims, irrad[:, 0][None, :, None]), 'pathscatter': (dims, irrad[:, 2][None, :, None])}, coords={'time': [c1['time']], 'wavelength_nm': Alam*1e3, 'angle_deg': [c1['angle']]}) return TR
[ "def", "golowtran", "(", "c1", ":", "Dict", "[", "str", ",", "Any", "]", ")", "->", "xarray", ".", "Dataset", ":", "# %% default parameters", "c1", ".", "setdefault", "(", "'time'", ",", "None", ")", "defp", "=", "(", "'h1'", ",", "'h2'", ",", "'angle'", ",", "'im'", ",", "'iseasn'", ",", "'ird1'", ",", "'range_km'", ",", "'zmdl'", ",", "'p'", ",", "'t'", ")", "for", "p", "in", "defp", ":", "c1", ".", "setdefault", "(", "p", ",", "0", ")", "c1", ".", "setdefault", "(", "'wmol'", ",", "[", "0", "]", "*", "12", ")", "# %% input check", "assert", "len", "(", "c1", "[", "'wmol'", "]", ")", "==", "12", ",", "'see Lowtran user manual for 12 values of WMOL'", "assert", "np", ".", "isfinite", "(", "c1", "[", "'h1'", "]", ")", ",", "'per Lowtran user manual Table 14, H1 must always be defined'", "# %% setup wavelength", "c1", ".", "setdefault", "(", "'wlstep'", ",", "20", ")", "if", "c1", "[", "'wlstep'", "]", "<", "5", ":", "logging", ".", "critical", "(", "'minimum resolution 5 cm^-1, specified resolution 20 cm^-1'", ")", "wlshort", ",", "wllong", ",", "nwl", "=", "nm2lt7", "(", "c1", "[", "'wlshort'", "]", ",", "c1", "[", "'wllong'", "]", ",", "c1", "[", "'wlstep'", "]", ")", "if", "not", "0", "<", "wlshort", "and", "wllong", "<=", "50000", ":", "logging", ".", "critical", "(", "'specified model range 0 <= wavelength [cm^-1] <= 50000'", ")", "# %% invoke lowtran", "\"\"\"\n Note we invoke case \"3a\" from table 14, only observer altitude and apparent\n angle are specified\n \"\"\"", "Tx", ",", "V", ",", "Alam", ",", "trace", ",", "unif", ",", "suma", ",", "irrad", ",", "sumvv", "=", "lowtran7", ".", "lwtrn7", "(", "True", ",", "nwl", ",", "wllong", ",", "wlshort", ",", "c1", "[", "'wlstep'", "]", ",", "c1", "[", "'model'", "]", ",", "c1", "[", "'itype'", "]", ",", "c1", "[", "'iemsct'", "]", ",", "c1", "[", "'im'", "]", ",", "c1", "[", "'iseasn'", "]", ",", "c1", "[", "'ird1'", "]", ",", "c1", "[", "'zmdl'", "]", ",", "c1", "[", "'p'", "]", ",", "c1", "[", "'t'", "]", ",", "c1", "[", "'wmol'", "]", ",", "c1", "[", "'h1'", "]", ",", "c1", "[", "'h2'", "]", ",", "c1", "[", "'angle'", "]", ",", "c1", "[", "'range_km'", "]", ")", "dims", "=", "(", "'time'", ",", "'wavelength_nm'", ",", "'angle_deg'", ")", "TR", "=", "xarray", ".", "Dataset", "(", "{", "'transmission'", ":", "(", "dims", ",", "Tx", "[", ":", ",", "9", "]", "[", "None", ",", ":", ",", "None", "]", ")", ",", "'radiance'", ":", "(", "dims", ",", "sumvv", "[", "None", ",", ":", ",", "None", "]", ")", ",", "'irradiance'", ":", "(", "dims", ",", "irrad", "[", ":", ",", "0", "]", "[", "None", ",", ":", ",", "None", "]", ")", ",", "'pathscatter'", ":", "(", "dims", ",", "irrad", "[", ":", ",", "2", "]", "[", "None", ",", ":", ",", "None", "]", ")", "}", ",", "coords", "=", "{", "'time'", ":", "[", "c1", "[", "'time'", "]", "]", ",", "'wavelength_nm'", ":", "Alam", "*", "1e3", ",", "'angle_deg'", ":", "[", "c1", "[", "'angle'", "]", "]", "}", ")", "return", "TR" ]
directly run Fortran code
[ "directly", "run", "Fortran", "code" ]
train
https://github.com/scivision/lowtran/blob/9954d859e53437436103f9ab54a7e2602ecaa1b7/lowtran/base.py#L78-L121
scivision/lowtran
lowtran/plots.py
plotradtime
def plotradtime(TR: xarray.Dataset, c1: Dict[str, Any], log: bool = False): """ make one plot per time for now. TR: 3-D array: time, wavelength, [transmittance, radiance] radiance is currently single-scatter solar """ for t in TR.time: # for each time plotirrad(TR.sel(time=t), c1, log)
python
def plotradtime(TR: xarray.Dataset, c1: Dict[str, Any], log: bool = False): """ make one plot per time for now. TR: 3-D array: time, wavelength, [transmittance, radiance] radiance is currently single-scatter solar """ for t in TR.time: # for each time plotirrad(TR.sel(time=t), c1, log)
[ "def", "plotradtime", "(", "TR", ":", "xarray", ".", "Dataset", ",", "c1", ":", "Dict", "[", "str", ",", "Any", "]", ",", "log", ":", "bool", "=", "False", ")", ":", "for", "t", "in", "TR", ".", "time", ":", "# for each time", "plotirrad", "(", "TR", ".", "sel", "(", "time", "=", "t", ")", ",", "c1", ",", "log", ")" ]
make one plot per time for now. TR: 3-D array: time, wavelength, [transmittance, radiance] radiance is currently single-scatter solar
[ "make", "one", "plot", "per", "time", "for", "now", "." ]
train
https://github.com/scivision/lowtran/blob/9954d859e53437436103f9ab54a7e2602ecaa1b7/lowtran/plots.py#L90-L100
rytilahti/python-songpal
songpal/method.py
Method.asdict
def asdict(self) -> Dict[str, Union[Dict, Union[str, Dict]]]: """Return a dictionary describing the method. This can be used to dump the information into a JSON file. """ return { "service": self.service.name, **self.signature.serialize(), }
python
def asdict(self) -> Dict[str, Union[Dict, Union[str, Dict]]]: """Return a dictionary describing the method. This can be used to dump the information into a JSON file. """ return { "service": self.service.name, **self.signature.serialize(), }
[ "def", "asdict", "(", "self", ")", "->", "Dict", "[", "str", ",", "Union", "[", "Dict", ",", "Union", "[", "str", ",", "Dict", "]", "]", "]", ":", "return", "{", "\"service\"", ":", "self", ".", "service", ".", "name", ",", "*", "*", "self", ".", "signature", ".", "serialize", "(", ")", ",", "}" ]
Return a dictionary describing the method. This can be used to dump the information into a JSON file.
[ "Return", "a", "dictionary", "describing", "the", "method", "." ]
train
https://github.com/rytilahti/python-songpal/blob/0443de6b3d960b9067a851d82261ca00e46b4618/songpal/method.py#L107-L115
rytilahti/python-songpal
songpal/common.py
DeviceError.error
def error(self): """Return user-friendly error message.""" try: errcode = DeviceErrorCode(self.error_code) return "%s (%s): %s" % (errcode.name, errcode.value, self.error_message) except: return "Error %s: %s" % (self.error_code, self.error_message)
python
def error(self): """Return user-friendly error message.""" try: errcode = DeviceErrorCode(self.error_code) return "%s (%s): %s" % (errcode.name, errcode.value, self.error_message) except: return "Error %s: %s" % (self.error_code, self.error_message)
[ "def", "error", "(", "self", ")", ":", "try", ":", "errcode", "=", "DeviceErrorCode", "(", "self", ".", "error_code", ")", "return", "\"%s (%s): %s\"", "%", "(", "errcode", ".", "name", ",", "errcode", ".", "value", ",", "self", ".", "error_message", ")", "except", ":", "return", "\"Error %s: %s\"", "%", "(", "self", ".", "error_code", ",", "self", ".", "error_message", ")" ]
Return user-friendly error message.
[ "Return", "user", "-", "friendly", "error", "message", "." ]
train
https://github.com/rytilahti/python-songpal/blob/0443de6b3d960b9067a851d82261ca00e46b4618/songpal/common.py#L29-L35
rytilahti/python-songpal
songpal/main.py
err
def err(msg): """Pretty-print an error.""" click.echo(click.style(msg, fg="red", bold=True))
python
def err(msg): """Pretty-print an error.""" click.echo(click.style(msg, fg="red", bold=True))
[ "def", "err", "(", "msg", ")", ":", "click", ".", "echo", "(", "click", ".", "style", "(", "msg", ",", "fg", "=", "\"red\"", ",", "bold", "=", "True", ")", ")" ]
Pretty-print an error.
[ "Pretty", "-", "print", "an", "error", "." ]
train
https://github.com/rytilahti/python-songpal/blob/0443de6b3d960b9067a851d82261ca00e46b4618/songpal/main.py#L33-L35
rytilahti/python-songpal
songpal/main.py
coro
def coro(f): """Run a coroutine and handle possible errors for the click cli. Source https://github.com/pallets/click/issues/85#issuecomment-43378930 """ f = asyncio.coroutine(f) def wrapper(*args, **kwargs): loop = asyncio.get_event_loop() try: return loop.run_until_complete(f(*args, **kwargs)) except KeyboardInterrupt: click.echo("Got CTRL+C, quitting..") dev = args[0] loop.run_until_complete(dev.stop_listen_notifications()) except SongpalException as ex: err("Error: %s" % ex) if len(args) > 0 and hasattr(args[0], "debug"): if args[0].debug > 0: raise ex return update_wrapper(wrapper, f)
python
def coro(f): """Run a coroutine and handle possible errors for the click cli. Source https://github.com/pallets/click/issues/85#issuecomment-43378930 """ f = asyncio.coroutine(f) def wrapper(*args, **kwargs): loop = asyncio.get_event_loop() try: return loop.run_until_complete(f(*args, **kwargs)) except KeyboardInterrupt: click.echo("Got CTRL+C, quitting..") dev = args[0] loop.run_until_complete(dev.stop_listen_notifications()) except SongpalException as ex: err("Error: %s" % ex) if len(args) > 0 and hasattr(args[0], "debug"): if args[0].debug > 0: raise ex return update_wrapper(wrapper, f)
[ "def", "coro", "(", "f", ")", ":", "f", "=", "asyncio", ".", "coroutine", "(", "f", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "loop", "=", "asyncio", ".", "get_event_loop", "(", ")", "try", ":", "return", "loop", ".", "run_until_complete", "(", "f", "(", "*", "args", ",", "*", "*", "kwargs", ")", ")", "except", "KeyboardInterrupt", ":", "click", ".", "echo", "(", "\"Got CTRL+C, quitting..\"", ")", "dev", "=", "args", "[", "0", "]", "loop", ".", "run_until_complete", "(", "dev", ".", "stop_listen_notifications", "(", ")", ")", "except", "SongpalException", "as", "ex", ":", "err", "(", "\"Error: %s\"", "%", "ex", ")", "if", "len", "(", "args", ")", ">", "0", "and", "hasattr", "(", "args", "[", "0", "]", ",", "\"debug\"", ")", ":", "if", "args", "[", "0", "]", ".", "debug", ">", "0", ":", "raise", "ex", "return", "update_wrapper", "(", "wrapper", ",", "f", ")" ]
Run a coroutine and handle possible errors for the click cli. Source https://github.com/pallets/click/issues/85#issuecomment-43378930
[ "Run", "a", "coroutine", "and", "handle", "possible", "errors", "for", "the", "click", "cli", "." ]
train
https://github.com/rytilahti/python-songpal/blob/0443de6b3d960b9067a851d82261ca00e46b4618/songpal/main.py#L38-L59
rytilahti/python-songpal
songpal/main.py
traverse_settings
async def traverse_settings(dev, module, settings, depth=0): """Print all available settings.""" for setting in settings: if setting.is_directory: print("%s%s (%s)" % (depth * " ", setting.title, module)) return await traverse_settings(dev, module, setting.settings, depth + 2) else: try: print_settings([await setting.get_value(dev)], depth=depth) except SongpalException as ex: err("Unable to read setting %s: %s" % (setting, ex)) continue
python
async def traverse_settings(dev, module, settings, depth=0): """Print all available settings.""" for setting in settings: if setting.is_directory: print("%s%s (%s)" % (depth * " ", setting.title, module)) return await traverse_settings(dev, module, setting.settings, depth + 2) else: try: print_settings([await setting.get_value(dev)], depth=depth) except SongpalException as ex: err("Unable to read setting %s: %s" % (setting, ex)) continue
[ "async", "def", "traverse_settings", "(", "dev", ",", "module", ",", "settings", ",", "depth", "=", "0", ")", ":", "for", "setting", "in", "settings", ":", "if", "setting", ".", "is_directory", ":", "print", "(", "\"%s%s (%s)\"", "%", "(", "depth", "*", "\" \"", ",", "setting", ".", "title", ",", "module", ")", ")", "return", "await", "traverse_settings", "(", "dev", ",", "module", ",", "setting", ".", "settings", ",", "depth", "+", "2", ")", "else", ":", "try", ":", "print_settings", "(", "[", "await", "setting", ".", "get_value", "(", "dev", ")", "]", ",", "depth", "=", "depth", ")", "except", "SongpalException", "as", "ex", ":", "err", "(", "\"Unable to read setting %s: %s\"", "%", "(", "setting", ",", "ex", ")", ")", "continue" ]
Print all available settings.
[ "Print", "all", "available", "settings", "." ]
train
https://github.com/rytilahti/python-songpal/blob/0443de6b3d960b9067a851d82261ca00e46b4618/songpal/main.py#L62-L73
rytilahti/python-songpal
songpal/main.py
print_settings
def print_settings(settings, depth=0): """Print all available settings of the device.""" # handle the case where a single setting is passed if isinstance(settings, Setting): settings = [settings] for setting in settings: cur = setting.currentValue print( "%s* %s (%s, value: %s, type: %s)" % ( " " * depth, setting.title, setting.target, click.style(cur, bold=True), setting.type, ) ) for opt in setting.candidate: if not opt.isAvailable: logging.debug("Unavailable setting %s", opt) continue click.echo( click.style( "%s - %s (%s)" % (" " * depth, opt.title, opt.value), bold=opt.value == cur, ) )
python
def print_settings(settings, depth=0): """Print all available settings of the device.""" # handle the case where a single setting is passed if isinstance(settings, Setting): settings = [settings] for setting in settings: cur = setting.currentValue print( "%s* %s (%s, value: %s, type: %s)" % ( " " * depth, setting.title, setting.target, click.style(cur, bold=True), setting.type, ) ) for opt in setting.candidate: if not opt.isAvailable: logging.debug("Unavailable setting %s", opt) continue click.echo( click.style( "%s - %s (%s)" % (" " * depth, opt.title, opt.value), bold=opt.value == cur, ) )
[ "def", "print_settings", "(", "settings", ",", "depth", "=", "0", ")", ":", "# handle the case where a single setting is passed", "if", "isinstance", "(", "settings", ",", "Setting", ")", ":", "settings", "=", "[", "settings", "]", "for", "setting", "in", "settings", ":", "cur", "=", "setting", ".", "currentValue", "print", "(", "\"%s* %s (%s, value: %s, type: %s)\"", "%", "(", "\" \"", "*", "depth", ",", "setting", ".", "title", ",", "setting", ".", "target", ",", "click", ".", "style", "(", "cur", ",", "bold", "=", "True", ")", ",", "setting", ".", "type", ",", ")", ")", "for", "opt", "in", "setting", ".", "candidate", ":", "if", "not", "opt", ".", "isAvailable", ":", "logging", ".", "debug", "(", "\"Unavailable setting %s\"", ",", "opt", ")", "continue", "click", ".", "echo", "(", "click", ".", "style", "(", "\"%s - %s (%s)\"", "%", "(", "\" \"", "*", "depth", ",", "opt", ".", "title", ",", "opt", ".", "value", ")", ",", "bold", "=", "opt", ".", "value", "==", "cur", ",", ")", ")" ]
Print all available settings of the device.
[ "Print", "all", "available", "settings", "of", "the", "device", "." ]
train
https://github.com/rytilahti/python-songpal/blob/0443de6b3d960b9067a851d82261ca00e46b4618/songpal/main.py#L76-L102
rytilahti/python-songpal
songpal/main.py
cli
async def cli(ctx, endpoint, debug, websocket, post): """Songpal CLI.""" lvl = logging.INFO if debug: lvl = logging.DEBUG click.echo("Setting debug level to %s" % debug) logging.basicConfig(level=lvl) if ctx.invoked_subcommand == "discover": ctx.obj = {"debug": debug} return if endpoint is None: err("Endpoint is required except when with 'discover'!") return protocol = None if post and websocket: err("You can force either --post or --websocket") return elif websocket: protocol = ProtocolType.WebSocket elif post: protocol = ProtocolType.XHRPost logging.debug("Using endpoint %s", endpoint) x = Device(endpoint, force_protocol=protocol, debug=debug) try: await x.get_supported_methods() except (requests.exceptions.ConnectionError, SongpalException) as ex: err("Unable to get supported methods: %s" % ex) sys.exit(-1) ctx.obj = x
python
async def cli(ctx, endpoint, debug, websocket, post): """Songpal CLI.""" lvl = logging.INFO if debug: lvl = logging.DEBUG click.echo("Setting debug level to %s" % debug) logging.basicConfig(level=lvl) if ctx.invoked_subcommand == "discover": ctx.obj = {"debug": debug} return if endpoint is None: err("Endpoint is required except when with 'discover'!") return protocol = None if post and websocket: err("You can force either --post or --websocket") return elif websocket: protocol = ProtocolType.WebSocket elif post: protocol = ProtocolType.XHRPost logging.debug("Using endpoint %s", endpoint) x = Device(endpoint, force_protocol=protocol, debug=debug) try: await x.get_supported_methods() except (requests.exceptions.ConnectionError, SongpalException) as ex: err("Unable to get supported methods: %s" % ex) sys.exit(-1) ctx.obj = x
[ "async", "def", "cli", "(", "ctx", ",", "endpoint", ",", "debug", ",", "websocket", ",", "post", ")", ":", "lvl", "=", "logging", ".", "INFO", "if", "debug", ":", "lvl", "=", "logging", ".", "DEBUG", "click", ".", "echo", "(", "\"Setting debug level to %s\"", "%", "debug", ")", "logging", ".", "basicConfig", "(", "level", "=", "lvl", ")", "if", "ctx", ".", "invoked_subcommand", "==", "\"discover\"", ":", "ctx", ".", "obj", "=", "{", "\"debug\"", ":", "debug", "}", "return", "if", "endpoint", "is", "None", ":", "err", "(", "\"Endpoint is required except when with 'discover'!\"", ")", "return", "protocol", "=", "None", "if", "post", "and", "websocket", ":", "err", "(", "\"You can force either --post or --websocket\"", ")", "return", "elif", "websocket", ":", "protocol", "=", "ProtocolType", ".", "WebSocket", "elif", "post", ":", "protocol", "=", "ProtocolType", ".", "XHRPost", "logging", ".", "debug", "(", "\"Using endpoint %s\"", ",", "endpoint", ")", "x", "=", "Device", "(", "endpoint", ",", "force_protocol", "=", "protocol", ",", "debug", "=", "debug", ")", "try", ":", "await", "x", ".", "get_supported_methods", "(", ")", "except", "(", "requests", ".", "exceptions", ".", "ConnectionError", ",", "SongpalException", ")", "as", "ex", ":", "err", "(", "\"Unable to get supported methods: %s\"", "%", "ex", ")", "sys", ".", "exit", "(", "-", "1", ")", "ctx", ".", "obj", "=", "x" ]
Songpal CLI.
[ "Songpal", "CLI", "." ]
train
https://github.com/rytilahti/python-songpal/blob/0443de6b3d960b9067a851d82261ca00e46b4618/songpal/main.py#L115-L147
rytilahti/python-songpal
songpal/main.py
status
async def status(dev: Device): """Display status information.""" power = await dev.get_power() click.echo(click.style("%s" % power, bold=power)) vol = await dev.get_volume_information() click.echo(vol.pop()) play_info = await dev.get_play_info() if not play_info.is_idle: click.echo("Playing %s" % play_info) else: click.echo("Not playing any media") outs = await dev.get_inputs() for out in outs: if out.active: click.echo("Active output: %s" % out) sysinfo = await dev.get_system_info() click.echo("System information: %s" % sysinfo)
python
async def status(dev: Device): """Display status information.""" power = await dev.get_power() click.echo(click.style("%s" % power, bold=power)) vol = await dev.get_volume_information() click.echo(vol.pop()) play_info = await dev.get_play_info() if not play_info.is_idle: click.echo("Playing %s" % play_info) else: click.echo("Not playing any media") outs = await dev.get_inputs() for out in outs: if out.active: click.echo("Active output: %s" % out) sysinfo = await dev.get_system_info() click.echo("System information: %s" % sysinfo)
[ "async", "def", "status", "(", "dev", ":", "Device", ")", ":", "power", "=", "await", "dev", ".", "get_power", "(", ")", "click", ".", "echo", "(", "click", ".", "style", "(", "\"%s\"", "%", "power", ",", "bold", "=", "power", ")", ")", "vol", "=", "await", "dev", ".", "get_volume_information", "(", ")", "click", ".", "echo", "(", "vol", ".", "pop", "(", ")", ")", "play_info", "=", "await", "dev", ".", "get_play_info", "(", ")", "if", "not", "play_info", ".", "is_idle", ":", "click", ".", "echo", "(", "\"Playing %s\"", "%", "play_info", ")", "else", ":", "click", ".", "echo", "(", "\"Not playing any media\"", ")", "outs", "=", "await", "dev", ".", "get_inputs", "(", ")", "for", "out", "in", "outs", ":", "if", "out", ".", "active", ":", "click", ".", "echo", "(", "\"Active output: %s\"", "%", "out", ")", "sysinfo", "=", "await", "dev", ".", "get_system_info", "(", ")", "click", ".", "echo", "(", "\"System information: %s\"", "%", "sysinfo", ")" ]
Display status information.
[ "Display", "status", "information", "." ]
train
https://github.com/rytilahti/python-songpal/blob/0443de6b3d960b9067a851d82261ca00e46b4618/songpal/main.py#L157-L177
rytilahti/python-songpal
songpal/main.py
discover
async def discover(ctx): """Discover supported devices.""" TIMEOUT = 5 async def print_discovered(dev): pretty_name = "%s - %s" % (dev.name, dev.model_number) click.echo(click.style("\nFound %s" % pretty_name, bold=True)) click.echo("* API version: %s" % dev.version) click.echo("* Endpoint: %s" % dev.endpoint) click.echo(" Services:") for serv in dev.services: click.echo(" - Service: %s" % serv) click.echo("\n[UPnP]") click.echo("* URL: %s" % dev.upnp_location) click.echo("* UDN: %s" % dev.udn) click.echo(" Services:") for serv in dev.upnp_services: click.echo(" - Service: %s" % serv) click.echo("Discovering for %s seconds" % TIMEOUT) await Discover.discover(TIMEOUT, ctx.obj["debug"] or 0, callback=print_discovered)
python
async def discover(ctx): """Discover supported devices.""" TIMEOUT = 5 async def print_discovered(dev): pretty_name = "%s - %s" % (dev.name, dev.model_number) click.echo(click.style("\nFound %s" % pretty_name, bold=True)) click.echo("* API version: %s" % dev.version) click.echo("* Endpoint: %s" % dev.endpoint) click.echo(" Services:") for serv in dev.services: click.echo(" - Service: %s" % serv) click.echo("\n[UPnP]") click.echo("* URL: %s" % dev.upnp_location) click.echo("* UDN: %s" % dev.udn) click.echo(" Services:") for serv in dev.upnp_services: click.echo(" - Service: %s" % serv) click.echo("Discovering for %s seconds" % TIMEOUT) await Discover.discover(TIMEOUT, ctx.obj["debug"] or 0, callback=print_discovered)
[ "async", "def", "discover", "(", "ctx", ")", ":", "TIMEOUT", "=", "5", "async", "def", "print_discovered", "(", "dev", ")", ":", "pretty_name", "=", "\"%s - %s\"", "%", "(", "dev", ".", "name", ",", "dev", ".", "model_number", ")", "click", ".", "echo", "(", "click", ".", "style", "(", "\"\\nFound %s\"", "%", "pretty_name", ",", "bold", "=", "True", ")", ")", "click", ".", "echo", "(", "\"* API version: %s\"", "%", "dev", ".", "version", ")", "click", ".", "echo", "(", "\"* Endpoint: %s\"", "%", "dev", ".", "endpoint", ")", "click", ".", "echo", "(", "\" Services:\"", ")", "for", "serv", "in", "dev", ".", "services", ":", "click", ".", "echo", "(", "\" - Service: %s\"", "%", "serv", ")", "click", ".", "echo", "(", "\"\\n[UPnP]\"", ")", "click", ".", "echo", "(", "\"* URL: %s\"", "%", "dev", ".", "upnp_location", ")", "click", ".", "echo", "(", "\"* UDN: %s\"", "%", "dev", ".", "udn", ")", "click", ".", "echo", "(", "\" Services:\"", ")", "for", "serv", "in", "dev", ".", "upnp_services", ":", "click", ".", "echo", "(", "\" - Service: %s\"", "%", "serv", ")", "click", ".", "echo", "(", "\"Discovering for %s seconds\"", "%", "TIMEOUT", ")", "await", "Discover", ".", "discover", "(", "TIMEOUT", ",", "ctx", ".", "obj", "[", "\"debug\"", "]", "or", "0", ",", "callback", "=", "print_discovered", ")" ]
Discover supported devices.
[ "Discover", "supported", "devices", "." ]
train
https://github.com/rytilahti/python-songpal/blob/0443de6b3d960b9067a851d82261ca00e46b4618/songpal/main.py#L183-L204
rytilahti/python-songpal
songpal/main.py
power
async def power(dev: Device, cmd, target, value): """Turn on and off, control power settings. Accepts commands 'on', 'off', and 'settings'. """ async def try_turn(cmd): state = True if cmd == "on" else False try: return await dev.set_power(state) except SongpalException as ex: if ex.code == 3: err("The device is already %s." % cmd) else: raise ex if cmd == "on" or cmd == "off": click.echo(await try_turn(cmd)) elif cmd == "settings": settings = await dev.get_power_settings() print_settings(settings) elif cmd == "set" and target and value: click.echo(await dev.set_power_settings(target, value)) else: power = await dev.get_power() click.echo(click.style(str(power), bold=power))
python
async def power(dev: Device, cmd, target, value): """Turn on and off, control power settings. Accepts commands 'on', 'off', and 'settings'. """ async def try_turn(cmd): state = True if cmd == "on" else False try: return await dev.set_power(state) except SongpalException as ex: if ex.code == 3: err("The device is already %s." % cmd) else: raise ex if cmd == "on" or cmd == "off": click.echo(await try_turn(cmd)) elif cmd == "settings": settings = await dev.get_power_settings() print_settings(settings) elif cmd == "set" and target and value: click.echo(await dev.set_power_settings(target, value)) else: power = await dev.get_power() click.echo(click.style(str(power), bold=power))
[ "async", "def", "power", "(", "dev", ":", "Device", ",", "cmd", ",", "target", ",", "value", ")", ":", "async", "def", "try_turn", "(", "cmd", ")", ":", "state", "=", "True", "if", "cmd", "==", "\"on\"", "else", "False", "try", ":", "return", "await", "dev", ".", "set_power", "(", "state", ")", "except", "SongpalException", "as", "ex", ":", "if", "ex", ".", "code", "==", "3", ":", "err", "(", "\"The device is already %s.\"", "%", "cmd", ")", "else", ":", "raise", "ex", "if", "cmd", "==", "\"on\"", "or", "cmd", "==", "\"off\"", ":", "click", ".", "echo", "(", "await", "try_turn", "(", "cmd", ")", ")", "elif", "cmd", "==", "\"settings\"", ":", "settings", "=", "await", "dev", ".", "get_power_settings", "(", ")", "print_settings", "(", "settings", ")", "elif", "cmd", "==", "\"set\"", "and", "target", "and", "value", ":", "click", ".", "echo", "(", "await", "dev", ".", "set_power_settings", "(", "target", ",", "value", ")", ")", "else", ":", "power", "=", "await", "dev", ".", "get_power", "(", ")", "click", ".", "echo", "(", "click", ".", "style", "(", "str", "(", "power", ")", ",", "bold", "=", "power", ")", ")" ]
Turn on and off, control power settings. Accepts commands 'on', 'off', and 'settings'.
[ "Turn", "on", "and", "off", "control", "power", "settings", "." ]
train
https://github.com/rytilahti/python-songpal/blob/0443de6b3d960b9067a851d82261ca00e46b4618/songpal/main.py#L213-L237
rytilahti/python-songpal
songpal/main.py
input
async def input(dev: Device, input, output): """Get and change outputs.""" inputs = await dev.get_inputs() if input: click.echo("Activating %s" % input) try: input = next((x for x in inputs if x.title == input)) except StopIteration: click.echo("Unable to find input %s" % input) return zone = None if output: zone = await dev.get_zone(output) if zone.uri not in input.outputs: click.echo("Input %s not valid for zone %s" % (input.title, output)) return await input.activate(zone) else: click.echo("Inputs:") for input in inputs: act = False if input.active: act = True click.echo(" * " + click.style(str(input), bold=act)) for out in input.outputs: click.echo(" - %s" % out)
python
async def input(dev: Device, input, output): """Get and change outputs.""" inputs = await dev.get_inputs() if input: click.echo("Activating %s" % input) try: input = next((x for x in inputs if x.title == input)) except StopIteration: click.echo("Unable to find input %s" % input) return zone = None if output: zone = await dev.get_zone(output) if zone.uri not in input.outputs: click.echo("Input %s not valid for zone %s" % (input.title, output)) return await input.activate(zone) else: click.echo("Inputs:") for input in inputs: act = False if input.active: act = True click.echo(" * " + click.style(str(input), bold=act)) for out in input.outputs: click.echo(" - %s" % out)
[ "async", "def", "input", "(", "dev", ":", "Device", ",", "input", ",", "output", ")", ":", "inputs", "=", "await", "dev", ".", "get_inputs", "(", ")", "if", "input", ":", "click", ".", "echo", "(", "\"Activating %s\"", "%", "input", ")", "try", ":", "input", "=", "next", "(", "(", "x", "for", "x", "in", "inputs", "if", "x", ".", "title", "==", "input", ")", ")", "except", "StopIteration", ":", "click", ".", "echo", "(", "\"Unable to find input %s\"", "%", "input", ")", "return", "zone", "=", "None", "if", "output", ":", "zone", "=", "await", "dev", ".", "get_zone", "(", "output", ")", "if", "zone", ".", "uri", "not", "in", "input", ".", "outputs", ":", "click", ".", "echo", "(", "\"Input %s not valid for zone %s\"", "%", "(", "input", ".", "title", ",", "output", ")", ")", "return", "await", "input", ".", "activate", "(", "zone", ")", "else", ":", "click", ".", "echo", "(", "\"Inputs:\"", ")", "for", "input", "in", "inputs", ":", "act", "=", "False", "if", "input", ".", "active", ":", "act", "=", "True", "click", ".", "echo", "(", "\" * \"", "+", "click", ".", "style", "(", "str", "(", "input", ")", ",", "bold", "=", "act", ")", ")", "for", "out", "in", "input", ".", "outputs", ":", "click", ".", "echo", "(", "\" - %s\"", "%", "out", ")" ]
Get and change outputs.
[ "Get", "and", "change", "outputs", "." ]
train
https://github.com/rytilahti/python-songpal/blob/0443de6b3d960b9067a851d82261ca00e46b4618/songpal/main.py#L245-L271
rytilahti/python-songpal
songpal/main.py
zone
async def zone(dev: Device, zone, activate): """Get and change outputs.""" if zone: zone = await dev.get_zone(zone) click.echo("%s %s" % ("Activating" if activate else "Deactivating", zone)) await zone.activate(activate) else: click.echo("Zones:") for zone in await dev.get_zones(): act = False if zone.active: act = True click.echo(" * " + click.style(str(zone), bold=act))
python
async def zone(dev: Device, zone, activate): """Get and change outputs.""" if zone: zone = await dev.get_zone(zone) click.echo("%s %s" % ("Activating" if activate else "Deactivating", zone)) await zone.activate(activate) else: click.echo("Zones:") for zone in await dev.get_zones(): act = False if zone.active: act = True click.echo(" * " + click.style(str(zone), bold=act))
[ "async", "def", "zone", "(", "dev", ":", "Device", ",", "zone", ",", "activate", ")", ":", "if", "zone", ":", "zone", "=", "await", "dev", ".", "get_zone", "(", "zone", ")", "click", ".", "echo", "(", "\"%s %s\"", "%", "(", "\"Activating\"", "if", "activate", "else", "\"Deactivating\"", ",", "zone", ")", ")", "await", "zone", ".", "activate", "(", "activate", ")", "else", ":", "click", ".", "echo", "(", "\"Zones:\"", ")", "for", "zone", "in", "await", "dev", ".", "get_zones", "(", ")", ":", "act", "=", "False", "if", "zone", ".", "active", ":", "act", "=", "True", "click", ".", "echo", "(", "\" * \"", "+", "click", ".", "style", "(", "str", "(", "zone", ")", ",", "bold", "=", "act", ")", ")" ]
Get and change outputs.
[ "Get", "and", "change", "outputs", "." ]
train
https://github.com/rytilahti/python-songpal/blob/0443de6b3d960b9067a851d82261ca00e46b4618/songpal/main.py#L279-L291
rytilahti/python-songpal
songpal/main.py
googlecast
async def googlecast(dev: Device, target, value): """Return Googlecast settings.""" if target and value: click.echo("Setting %s = %s" % (target, value)) await dev.set_googlecast_settings(target, value) print_settings(await dev.get_googlecast_settings())
python
async def googlecast(dev: Device, target, value): """Return Googlecast settings.""" if target and value: click.echo("Setting %s = %s" % (target, value)) await dev.set_googlecast_settings(target, value) print_settings(await dev.get_googlecast_settings())
[ "async", "def", "googlecast", "(", "dev", ":", "Device", ",", "target", ",", "value", ")", ":", "if", "target", "and", "value", ":", "click", ".", "echo", "(", "\"Setting %s = %s\"", "%", "(", "target", ",", "value", ")", ")", "await", "dev", ".", "set_googlecast_settings", "(", "target", ",", "value", ")", "print_settings", "(", "await", "dev", ".", "get_googlecast_settings", "(", ")", ")" ]
Return Googlecast settings.
[ "Return", "Googlecast", "settings", "." ]
train
https://github.com/rytilahti/python-songpal/blob/0443de6b3d960b9067a851d82261ca00e46b4618/songpal/main.py#L299-L304
rytilahti/python-songpal
songpal/main.py
source
async def source(dev: Device, scheme): """List available sources. If no `scheme` is given, will list sources for all sc hemes. """ if scheme is None: schemes = await dev.get_schemes() schemes = [scheme.scheme for scheme in schemes] # noqa: T484 else: schemes = [scheme] for schema in schemes: try: sources = await dev.get_source_list(schema) except SongpalException as ex: click.echo("Unable to get sources for %s" % schema) continue for src in sources: click.echo(src) if src.isBrowsable: try: count = await dev.get_content_count(src.source) if count.count > 0: click.echo(" %s" % count) for content in await dev.get_contents(src.source): click.echo(" %s\n\t%s" % (content.title, content.uri)) else: click.echo(" No content to list.") except SongpalException as ex: click.echo(" %s" % ex)
python
async def source(dev: Device, scheme): """List available sources. If no `scheme` is given, will list sources for all sc hemes. """ if scheme is None: schemes = await dev.get_schemes() schemes = [scheme.scheme for scheme in schemes] # noqa: T484 else: schemes = [scheme] for schema in schemes: try: sources = await dev.get_source_list(schema) except SongpalException as ex: click.echo("Unable to get sources for %s" % schema) continue for src in sources: click.echo(src) if src.isBrowsable: try: count = await dev.get_content_count(src.source) if count.count > 0: click.echo(" %s" % count) for content in await dev.get_contents(src.source): click.echo(" %s\n\t%s" % (content.title, content.uri)) else: click.echo(" No content to list.") except SongpalException as ex: click.echo(" %s" % ex)
[ "async", "def", "source", "(", "dev", ":", "Device", ",", "scheme", ")", ":", "if", "scheme", "is", "None", ":", "schemes", "=", "await", "dev", ".", "get_schemes", "(", ")", "schemes", "=", "[", "scheme", ".", "scheme", "for", "scheme", "in", "schemes", "]", "# noqa: T484", "else", ":", "schemes", "=", "[", "scheme", "]", "for", "schema", "in", "schemes", ":", "try", ":", "sources", "=", "await", "dev", ".", "get_source_list", "(", "schema", ")", "except", "SongpalException", "as", "ex", ":", "click", ".", "echo", "(", "\"Unable to get sources for %s\"", "%", "schema", ")", "continue", "for", "src", "in", "sources", ":", "click", ".", "echo", "(", "src", ")", "if", "src", ".", "isBrowsable", ":", "try", ":", "count", "=", "await", "dev", ".", "get_content_count", "(", "src", ".", "source", ")", "if", "count", ".", "count", ">", "0", ":", "click", ".", "echo", "(", "\" %s\"", "%", "count", ")", "for", "content", "in", "await", "dev", ".", "get_contents", "(", "src", ".", "source", ")", ":", "click", ".", "echo", "(", "\" %s\\n\\t%s\"", "%", "(", "content", ".", "title", ",", "content", ".", "uri", ")", ")", "else", ":", "click", ".", "echo", "(", "\" No content to list.\"", ")", "except", "SongpalException", "as", "ex", ":", "click", ".", "echo", "(", "\" %s\"", "%", "ex", ")" ]
List available sources. If no `scheme` is given, will list sources for all sc hemes.
[ "List", "available", "sources", "." ]
train
https://github.com/rytilahti/python-songpal/blob/0443de6b3d960b9067a851d82261ca00e46b4618/songpal/main.py#L311-L340
rytilahti/python-songpal
songpal/main.py
volume
async def volume(dev: Device, volume, output): """Get and set the volume settings. Passing 'mute' as new volume will mute the volume, 'unmute' removes it. """ vol = None vol_controls = await dev.get_volume_information() if output is not None: click.echo("Using output: %s" % output) output_uri = (await dev.get_zone(output)).uri for v in vol_controls: if v.output == output_uri: vol = v break else: vol = vol_controls[0] if vol is None: err("Unable to find volume controller: %s" % output) return if volume and volume == "mute": click.echo("Muting") await vol.set_mute(True) elif volume and volume == "unmute": click.echo("Unmuting") await vol.set_mute(False) elif volume: click.echo("Setting volume to %s" % volume) await vol.set_volume(volume) if output is not None: click.echo(vol) else: [click.echo(x) for x in vol_controls]
python
async def volume(dev: Device, volume, output): """Get and set the volume settings. Passing 'mute' as new volume will mute the volume, 'unmute' removes it. """ vol = None vol_controls = await dev.get_volume_information() if output is not None: click.echo("Using output: %s" % output) output_uri = (await dev.get_zone(output)).uri for v in vol_controls: if v.output == output_uri: vol = v break else: vol = vol_controls[0] if vol is None: err("Unable to find volume controller: %s" % output) return if volume and volume == "mute": click.echo("Muting") await vol.set_mute(True) elif volume and volume == "unmute": click.echo("Unmuting") await vol.set_mute(False) elif volume: click.echo("Setting volume to %s" % volume) await vol.set_volume(volume) if output is not None: click.echo(vol) else: [click.echo(x) for x in vol_controls]
[ "async", "def", "volume", "(", "dev", ":", "Device", ",", "volume", ",", "output", ")", ":", "vol", "=", "None", "vol_controls", "=", "await", "dev", ".", "get_volume_information", "(", ")", "if", "output", "is", "not", "None", ":", "click", ".", "echo", "(", "\"Using output: %s\"", "%", "output", ")", "output_uri", "=", "(", "await", "dev", ".", "get_zone", "(", "output", ")", ")", ".", "uri", "for", "v", "in", "vol_controls", ":", "if", "v", ".", "output", "==", "output_uri", ":", "vol", "=", "v", "break", "else", ":", "vol", "=", "vol_controls", "[", "0", "]", "if", "vol", "is", "None", ":", "err", "(", "\"Unable to find volume controller: %s\"", "%", "output", ")", "return", "if", "volume", "and", "volume", "==", "\"mute\"", ":", "click", ".", "echo", "(", "\"Muting\"", ")", "await", "vol", ".", "set_mute", "(", "True", ")", "elif", "volume", "and", "volume", "==", "\"unmute\"", ":", "click", ".", "echo", "(", "\"Unmuting\"", ")", "await", "vol", ".", "set_mute", "(", "False", ")", "elif", "volume", ":", "click", ".", "echo", "(", "\"Setting volume to %s\"", "%", "volume", ")", "await", "vol", ".", "set_volume", "(", "volume", ")", "if", "output", "is", "not", "None", ":", "click", ".", "echo", "(", "vol", ")", "else", ":", "[", "click", ".", "echo", "(", "x", ")", "for", "x", "in", "vol_controls", "]" ]
Get and set the volume settings. Passing 'mute' as new volume will mute the volume, 'unmute' removes it.
[ "Get", "and", "set", "the", "volume", "settings", "." ]
train
https://github.com/rytilahti/python-songpal/blob/0443de6b3d960b9067a851d82261ca00e46b4618/songpal/main.py#L348-L383
rytilahti/python-songpal
songpal/main.py
schemes
async def schemes(dev: Device): """Print supported uri schemes.""" schemes = await dev.get_schemes() for scheme in schemes: click.echo(scheme)
python
async def schemes(dev: Device): """Print supported uri schemes.""" schemes = await dev.get_schemes() for scheme in schemes: click.echo(scheme)
[ "async", "def", "schemes", "(", "dev", ":", "Device", ")", ":", "schemes", "=", "await", "dev", ".", "get_schemes", "(", ")", "for", "scheme", "in", "schemes", ":", "click", ".", "echo", "(", "scheme", ")" ]
Print supported uri schemes.
[ "Print", "supported", "uri", "schemes", "." ]
train
https://github.com/rytilahti/python-songpal/blob/0443de6b3d960b9067a851d82261ca00e46b4618/songpal/main.py#L389-L393
rytilahti/python-songpal
songpal/main.py
check_update
async def check_update(dev: Device, internet: bool, update: bool): """Print out update information.""" if internet: print("Checking updates from network") else: print("Not checking updates from internet") update_info = await dev.get_update_info(from_network=internet) if not update_info.isUpdatable: click.echo("No updates available.") return if not update: click.echo("Update available: %s" % update_info) click.echo("Use --update to activate update!") else: click.echo("Activating update, please be seated.") res = await dev.activate_system_update() click.echo("Update result: %s" % res)
python
async def check_update(dev: Device, internet: bool, update: bool): """Print out update information.""" if internet: print("Checking updates from network") else: print("Not checking updates from internet") update_info = await dev.get_update_info(from_network=internet) if not update_info.isUpdatable: click.echo("No updates available.") return if not update: click.echo("Update available: %s" % update_info) click.echo("Use --update to activate update!") else: click.echo("Activating update, please be seated.") res = await dev.activate_system_update() click.echo("Update result: %s" % res)
[ "async", "def", "check_update", "(", "dev", ":", "Device", ",", "internet", ":", "bool", ",", "update", ":", "bool", ")", ":", "if", "internet", ":", "print", "(", "\"Checking updates from network\"", ")", "else", ":", "print", "(", "\"Not checking updates from internet\"", ")", "update_info", "=", "await", "dev", ".", "get_update_info", "(", "from_network", "=", "internet", ")", "if", "not", "update_info", ".", "isUpdatable", ":", "click", ".", "echo", "(", "\"No updates available.\"", ")", "return", "if", "not", "update", ":", "click", ".", "echo", "(", "\"Update available: %s\"", "%", "update_info", ")", "click", ".", "echo", "(", "\"Use --update to activate update!\"", ")", "else", ":", "click", ".", "echo", "(", "\"Activating update, please be seated.\"", ")", "res", "=", "await", "dev", ".", "activate_system_update", "(", ")", "click", ".", "echo", "(", "\"Update result: %s\"", "%", "res", ")" ]
Print out update information.
[ "Print", "out", "update", "information", "." ]
train
https://github.com/rytilahti/python-songpal/blob/0443de6b3d960b9067a851d82261ca00e46b4618/songpal/main.py#L401-L417
rytilahti/python-songpal
songpal/main.py
bluetooth
async def bluetooth(dev: Device, target, value): """Get or set bluetooth settings.""" if target and value: await dev.set_bluetooth_settings(target, value) print_settings(await dev.get_bluetooth_settings())
python
async def bluetooth(dev: Device, target, value): """Get or set bluetooth settings.""" if target and value: await dev.set_bluetooth_settings(target, value) print_settings(await dev.get_bluetooth_settings())
[ "async", "def", "bluetooth", "(", "dev", ":", "Device", ",", "target", ",", "value", ")", ":", "if", "target", "and", "value", ":", "await", "dev", ".", "set_bluetooth_settings", "(", "target", ",", "value", ")", "print_settings", "(", "await", "dev", ".", "get_bluetooth_settings", "(", ")", ")" ]
Get or set bluetooth settings.
[ "Get", "or", "set", "bluetooth", "settings", "." ]
train
https://github.com/rytilahti/python-songpal/blob/0443de6b3d960b9067a851d82261ca00e46b4618/songpal/main.py#L425-L430
rytilahti/python-songpal
songpal/main.py
sysinfo
async def sysinfo(dev: Device): """Print out system information (version, MAC addrs).""" click.echo(await dev.get_system_info()) click.echo(await dev.get_interface_information())
python
async def sysinfo(dev: Device): """Print out system information (version, MAC addrs).""" click.echo(await dev.get_system_info()) click.echo(await dev.get_interface_information())
[ "async", "def", "sysinfo", "(", "dev", ":", "Device", ")", ":", "click", ".", "echo", "(", "await", "dev", ".", "get_system_info", "(", ")", ")", "click", ".", "echo", "(", "await", "dev", ".", "get_interface_information", "(", ")", ")" ]
Print out system information (version, MAC addrs).
[ "Print", "out", "system", "information", "(", "version", "MAC", "addrs", ")", "." ]
train
https://github.com/rytilahti/python-songpal/blob/0443de6b3d960b9067a851d82261ca00e46b4618/songpal/main.py#L436-L439
rytilahti/python-songpal
songpal/main.py
settings
async def settings(dev: Device): """Print out all possible settings.""" settings_tree = await dev.get_settings() for module in settings_tree: await traverse_settings(dev, module.usage, module.settings)
python
async def settings(dev: Device): """Print out all possible settings.""" settings_tree = await dev.get_settings() for module in settings_tree: await traverse_settings(dev, module.usage, module.settings)
[ "async", "def", "settings", "(", "dev", ":", "Device", ")", ":", "settings_tree", "=", "await", "dev", ".", "get_settings", "(", ")", "for", "module", "in", "settings_tree", ":", "await", "traverse_settings", "(", "dev", ",", "module", ".", "usage", ",", "module", ".", "settings", ")" ]
Print out all possible settings.
[ "Print", "out", "all", "possible", "settings", "." ]
train
https://github.com/rytilahti/python-songpal/blob/0443de6b3d960b9067a851d82261ca00e46b4618/songpal/main.py#L453-L458
rytilahti/python-songpal
songpal/main.py
storage
async def storage(dev: Device): """Print storage information.""" storages = await dev.get_storage_list() for storage in storages: click.echo(storage)
python
async def storage(dev: Device): """Print storage information.""" storages = await dev.get_storage_list() for storage in storages: click.echo(storage)
[ "async", "def", "storage", "(", "dev", ":", "Device", ")", ":", "storages", "=", "await", "dev", ".", "get_storage_list", "(", ")", "for", "storage", "in", "storages", ":", "click", ".", "echo", "(", "storage", ")" ]
Print storage information.
[ "Print", "storage", "information", "." ]
train
https://github.com/rytilahti/python-songpal/blob/0443de6b3d960b9067a851d82261ca00e46b4618/songpal/main.py#L464-L468
rytilahti/python-songpal
songpal/main.py
sound
async def sound(dev: Device, target, value): """Get or set sound settings.""" if target and value: click.echo("Setting %s to %s" % (target, value)) click.echo(await dev.set_sound_settings(target, value)) print_settings(await dev.get_sound_settings())
python
async def sound(dev: Device, target, value): """Get or set sound settings.""" if target and value: click.echo("Setting %s to %s" % (target, value)) click.echo(await dev.set_sound_settings(target, value)) print_settings(await dev.get_sound_settings())
[ "async", "def", "sound", "(", "dev", ":", "Device", ",", "target", ",", "value", ")", ":", "if", "target", "and", "value", ":", "click", ".", "echo", "(", "\"Setting %s to %s\"", "%", "(", "target", ",", "value", ")", ")", "click", ".", "echo", "(", "await", "dev", ".", "set_sound_settings", "(", "target", ",", "value", ")", ")", "print_settings", "(", "await", "dev", ".", "get_sound_settings", "(", ")", ")" ]
Get or set sound settings.
[ "Get", "or", "set", "sound", "settings", "." ]
train
https://github.com/rytilahti/python-songpal/blob/0443de6b3d960b9067a851d82261ca00e46b4618/songpal/main.py#L476-L482
rytilahti/python-songpal
songpal/main.py
soundfield
async def soundfield(dev: Device, soundfield: str): """Get or set sound field.""" if soundfield is not None: await dev.set_sound_settings("soundField", soundfield) soundfields = await dev.get_sound_settings("soundField") print_settings(soundfields)
python
async def soundfield(dev: Device, soundfield: str): """Get or set sound field.""" if soundfield is not None: await dev.set_sound_settings("soundField", soundfield) soundfields = await dev.get_sound_settings("soundField") print_settings(soundfields)
[ "async", "def", "soundfield", "(", "dev", ":", "Device", ",", "soundfield", ":", "str", ")", ":", "if", "soundfield", "is", "not", "None", ":", "await", "dev", ".", "set_sound_settings", "(", "\"soundField\"", ",", "soundfield", ")", "soundfields", "=", "await", "dev", ".", "get_sound_settings", "(", "\"soundField\"", ")", "print_settings", "(", "soundfields", ")" ]
Get or set sound field.
[ "Get", "or", "set", "sound", "field", "." ]
train
https://github.com/rytilahti/python-songpal/blob/0443de6b3d960b9067a851d82261ca00e46b4618/songpal/main.py#L489-L494
rytilahti/python-songpal
songpal/main.py
playback
async def playback(dev: Device, cmd, target, value): """Get and set playback settings, e.g. repeat and shuffle..""" if target and value: dev.set_playback_settings(target, value) if cmd == "support": click.echo("Supported playback functions:") supported = await dev.get_supported_playback_functions("storage:usb1") for i in supported: print(i) elif cmd == "settings": print_settings(await dev.get_playback_settings()) # click.echo("Playback functions:") # funcs = await dev.get_available_playback_functions() # print(funcs) else: click.echo("Currently playing: %s" % await dev.get_play_info())
python
async def playback(dev: Device, cmd, target, value): """Get and set playback settings, e.g. repeat and shuffle..""" if target and value: dev.set_playback_settings(target, value) if cmd == "support": click.echo("Supported playback functions:") supported = await dev.get_supported_playback_functions("storage:usb1") for i in supported: print(i) elif cmd == "settings": print_settings(await dev.get_playback_settings()) # click.echo("Playback functions:") # funcs = await dev.get_available_playback_functions() # print(funcs) else: click.echo("Currently playing: %s" % await dev.get_play_info())
[ "async", "def", "playback", "(", "dev", ":", "Device", ",", "cmd", ",", "target", ",", "value", ")", ":", "if", "target", "and", "value", ":", "dev", ".", "set_playback_settings", "(", "target", ",", "value", ")", "if", "cmd", "==", "\"support\"", ":", "click", ".", "echo", "(", "\"Supported playback functions:\"", ")", "supported", "=", "await", "dev", ".", "get_supported_playback_functions", "(", "\"storage:usb1\"", ")", "for", "i", "in", "supported", ":", "print", "(", "i", ")", "elif", "cmd", "==", "\"settings\"", ":", "print_settings", "(", "await", "dev", ".", "get_playback_settings", "(", ")", ")", "# click.echo(\"Playback functions:\")", "# funcs = await dev.get_available_playback_functions()", "# print(funcs)", "else", ":", "click", ".", "echo", "(", "\"Currently playing: %s\"", "%", "await", "dev", ".", "get_play_info", "(", ")", ")" ]
Get and set playback settings, e.g. repeat and shuffle..
[ "Get", "and", "set", "playback", "settings", "e", ".", "g", ".", "repeat", "and", "shuffle", ".." ]
train
https://github.com/rytilahti/python-songpal/blob/0443de6b3d960b9067a851d82261ca00e46b4618/songpal/main.py#L511-L526
rytilahti/python-songpal
songpal/main.py
speaker
async def speaker(dev: Device, target, value): """Get and set external speaker settings.""" if target and value: click.echo("Setting %s to %s" % (target, value)) await dev.set_speaker_settings(target, value) print_settings(await dev.get_speaker_settings())
python
async def speaker(dev: Device, target, value): """Get and set external speaker settings.""" if target and value: click.echo("Setting %s to %s" % (target, value)) await dev.set_speaker_settings(target, value) print_settings(await dev.get_speaker_settings())
[ "async", "def", "speaker", "(", "dev", ":", "Device", ",", "target", ",", "value", ")", ":", "if", "target", "and", "value", ":", "click", ".", "echo", "(", "\"Setting %s to %s\"", "%", "(", "target", ",", "value", ")", ")", "await", "dev", ".", "set_speaker_settings", "(", "target", ",", "value", ")", "print_settings", "(", "await", "dev", ".", "get_speaker_settings", "(", ")", ")" ]
Get and set external speaker settings.
[ "Get", "and", "set", "external", "speaker", "settings", "." ]
train
https://github.com/rytilahti/python-songpal/blob/0443de6b3d960b9067a851d82261ca00e46b4618/songpal/main.py#L534-L540
rytilahti/python-songpal
songpal/main.py
notifications
async def notifications(dev: Device, notification: str, listen_all: bool): """List available notifications and listen to them. Using --listen-all [notification] allows to listen to all notifications from the given subsystem. If the subsystem is omited, notifications from all subsystems are requested. """ notifications = await dev.get_notifications() async def handle_notification(x): click.echo("got notification: %s" % x) if listen_all: if notification is not None: await dev.services[notification].listen_all_notifications( handle_notification ) else: click.echo("Listening to all possible notifications") await dev.listen_notifications(fallback_callback=handle_notification) elif notification: click.echo("Subscribing to notification %s" % notification) for notif in notifications: if notif.name == notification: await notif.activate(handle_notification) click.echo("Unable to find notification %s" % notification) else: click.echo(click.style("Available notifications", bold=True)) for notification in notifications: click.echo("* %s" % notification)
python
async def notifications(dev: Device, notification: str, listen_all: bool): """List available notifications and listen to them. Using --listen-all [notification] allows to listen to all notifications from the given subsystem. If the subsystem is omited, notifications from all subsystems are requested. """ notifications = await dev.get_notifications() async def handle_notification(x): click.echo("got notification: %s" % x) if listen_all: if notification is not None: await dev.services[notification].listen_all_notifications( handle_notification ) else: click.echo("Listening to all possible notifications") await dev.listen_notifications(fallback_callback=handle_notification) elif notification: click.echo("Subscribing to notification %s" % notification) for notif in notifications: if notif.name == notification: await notif.activate(handle_notification) click.echo("Unable to find notification %s" % notification) else: click.echo(click.style("Available notifications", bold=True)) for notification in notifications: click.echo("* %s" % notification)
[ "async", "def", "notifications", "(", "dev", ":", "Device", ",", "notification", ":", "str", ",", "listen_all", ":", "bool", ")", ":", "notifications", "=", "await", "dev", ".", "get_notifications", "(", ")", "async", "def", "handle_notification", "(", "x", ")", ":", "click", ".", "echo", "(", "\"got notification: %s\"", "%", "x", ")", "if", "listen_all", ":", "if", "notification", "is", "not", "None", ":", "await", "dev", ".", "services", "[", "notification", "]", ".", "listen_all_notifications", "(", "handle_notification", ")", "else", ":", "click", ".", "echo", "(", "\"Listening to all possible notifications\"", ")", "await", "dev", ".", "listen_notifications", "(", "fallback_callback", "=", "handle_notification", ")", "elif", "notification", ":", "click", ".", "echo", "(", "\"Subscribing to notification %s\"", "%", "notification", ")", "for", "notif", "in", "notifications", ":", "if", "notif", ".", "name", "==", "notification", ":", "await", "notif", ".", "activate", "(", "handle_notification", ")", "click", ".", "echo", "(", "\"Unable to find notification %s\"", "%", "notification", ")", "else", ":", "click", ".", "echo", "(", "click", ".", "style", "(", "\"Available notifications\"", ",", "bold", "=", "True", ")", ")", "for", "notification", "in", "notifications", ":", "click", ".", "echo", "(", "\"* %s\"", "%", "notification", ")" ]
List available notifications and listen to them. Using --listen-all [notification] allows to listen to all notifications from the given subsystem. If the subsystem is omited, notifications from all subsystems are requested.
[ "List", "available", "notifications", "and", "listen", "to", "them", "." ]
train
https://github.com/rytilahti/python-songpal/blob/0443de6b3d960b9067a851d82261ca00e46b4618/songpal/main.py#L548-L581
rytilahti/python-songpal
songpal/main.py
list_all
def list_all(dev: Device): """List all available API calls.""" for name, service in dev.services.items(): click.echo(click.style("\nService %s" % name, bold=True)) for method in service.methods: click.echo(" %s" % method.name)
python
def list_all(dev: Device): """List all available API calls.""" for name, service in dev.services.items(): click.echo(click.style("\nService %s" % name, bold=True)) for method in service.methods: click.echo(" %s" % method.name)
[ "def", "list_all", "(", "dev", ":", "Device", ")", ":", "for", "name", ",", "service", "in", "dev", ".", "services", ".", "items", "(", ")", ":", "click", ".", "echo", "(", "click", ".", "style", "(", "\"\\nService %s\"", "%", "name", ",", "bold", "=", "True", ")", ")", "for", "method", "in", "service", ".", "methods", ":", "click", ".", "echo", "(", "\" %s\"", "%", "method", ".", "name", ")" ]
List all available API calls.
[ "List", "all", "available", "API", "calls", "." ]
train
https://github.com/rytilahti/python-songpal/blob/0443de6b3d960b9067a851d82261ca00e46b4618/songpal/main.py#L594-L599
rytilahti/python-songpal
songpal/main.py
command
async def command(dev, service, method, parameters): """Run a raw command.""" params = None if parameters is not None: params = ast.literal_eval(parameters) click.echo("Calling %s.%s with params %s" % (service, method, params)) res = await dev.raw_command(service, method, params) click.echo(res)
python
async def command(dev, service, method, parameters): """Run a raw command.""" params = None if parameters is not None: params = ast.literal_eval(parameters) click.echo("Calling %s.%s with params %s" % (service, method, params)) res = await dev.raw_command(service, method, params) click.echo(res)
[ "async", "def", "command", "(", "dev", ",", "service", ",", "method", ",", "parameters", ")", ":", "params", "=", "None", "if", "parameters", "is", "not", "None", ":", "params", "=", "ast", ".", "literal_eval", "(", "parameters", ")", "click", ".", "echo", "(", "\"Calling %s.%s with params %s\"", "%", "(", "service", ",", "method", ",", "params", ")", ")", "res", "=", "await", "dev", ".", "raw_command", "(", "service", ",", "method", ",", "params", ")", "click", ".", "echo", "(", "res", ")" ]
Run a raw command.
[ "Run", "a", "raw", "command", "." ]
train
https://github.com/rytilahti/python-songpal/blob/0443de6b3d960b9067a851d82261ca00e46b4618/songpal/main.py#L608-L615
rytilahti/python-songpal
songpal/main.py
dump_devinfo
async def dump_devinfo(dev: Device, file): """Dump developer information. Pass `file` to write the results directly into a file. """ import attr methods = await dev.get_supported_methods() res = { "supported_methods": {k: v.asdict() for k, v in methods.items()}, "settings": [attr.asdict(x) for x in await dev.get_settings()], "sysinfo": attr.asdict(await dev.get_system_info()), "interface_info": attr.asdict(await dev.get_interface_information()), } if file: click.echo("Saving to file: %s" % file.name) json.dump(res, file, sort_keys=True, indent=4) else: click.echo(json.dumps(res, sort_keys=True, indent=4))
python
async def dump_devinfo(dev: Device, file): """Dump developer information. Pass `file` to write the results directly into a file. """ import attr methods = await dev.get_supported_methods() res = { "supported_methods": {k: v.asdict() for k, v in methods.items()}, "settings": [attr.asdict(x) for x in await dev.get_settings()], "sysinfo": attr.asdict(await dev.get_system_info()), "interface_info": attr.asdict(await dev.get_interface_information()), } if file: click.echo("Saving to file: %s" % file.name) json.dump(res, file, sort_keys=True, indent=4) else: click.echo(json.dumps(res, sort_keys=True, indent=4))
[ "async", "def", "dump_devinfo", "(", "dev", ":", "Device", ",", "file", ")", ":", "import", "attr", "methods", "=", "await", "dev", ".", "get_supported_methods", "(", ")", "res", "=", "{", "\"supported_methods\"", ":", "{", "k", ":", "v", ".", "asdict", "(", ")", "for", "k", ",", "v", "in", "methods", ".", "items", "(", ")", "}", ",", "\"settings\"", ":", "[", "attr", ".", "asdict", "(", "x", ")", "for", "x", "in", "await", "dev", ".", "get_settings", "(", ")", "]", ",", "\"sysinfo\"", ":", "attr", ".", "asdict", "(", "await", "dev", ".", "get_system_info", "(", ")", ")", ",", "\"interface_info\"", ":", "attr", ".", "asdict", "(", "await", "dev", ".", "get_interface_information", "(", ")", ")", ",", "}", "if", "file", ":", "click", ".", "echo", "(", "\"Saving to file: %s\"", "%", "file", ".", "name", ")", "json", ".", "dump", "(", "res", ",", "file", ",", "sort_keys", "=", "True", ",", "indent", "=", "4", ")", "else", ":", "click", ".", "echo", "(", "json", ".", "dumps", "(", "res", ",", "sort_keys", "=", "True", ",", "indent", "=", "4", ")", ")" ]
Dump developer information. Pass `file` to write the results directly into a file.
[ "Dump", "developer", "information", "." ]
train
https://github.com/rytilahti/python-songpal/blob/0443de6b3d960b9067a851d82261ca00e46b4618/songpal/main.py#L622-L640
rytilahti/python-songpal
songpal/main.py
state
async def state(gc: GroupControl): """Current group state.""" state = await gc.state() click.echo(state) click.echo("Full state info: %s" % repr(state))
python
async def state(gc: GroupControl): """Current group state.""" state = await gc.state() click.echo(state) click.echo("Full state info: %s" % repr(state))
[ "async", "def", "state", "(", "gc", ":", "GroupControl", ")", ":", "state", "=", "await", "gc", ".", "state", "(", ")", "click", ".", "echo", "(", "state", ")", "click", ".", "echo", "(", "\"Full state info: %s\"", "%", "repr", "(", "state", ")", ")" ]
Current group state.
[ "Current", "group", "state", "." ]
train
https://github.com/rytilahti/python-songpal/blob/0443de6b3d960b9067a851d82261ca00e46b4618/songpal/main.py#L667-L671
rytilahti/python-songpal
songpal/main.py
create
async def create(gc: GroupControl, name, slaves): """Create new group""" click.echo("Creating group %s with slaves: %s" % (name, slaves)) click.echo(await gc.create(name, slaves))
python
async def create(gc: GroupControl, name, slaves): """Create new group""" click.echo("Creating group %s with slaves: %s" % (name, slaves)) click.echo(await gc.create(name, slaves))
[ "async", "def", "create", "(", "gc", ":", "GroupControl", ",", "name", ",", "slaves", ")", ":", "click", ".", "echo", "(", "\"Creating group %s with slaves: %s\"", "%", "(", "name", ",", "slaves", ")", ")", "click", ".", "echo", "(", "await", "gc", ".", "create", "(", "name", ",", "slaves", ")", ")" ]
Create new group
[ "Create", "new", "group" ]
train
https://github.com/rytilahti/python-songpal/blob/0443de6b3d960b9067a851d82261ca00e46b4618/songpal/main.py#L697-L700
rytilahti/python-songpal
songpal/main.py
add
async def add(gc: GroupControl, slaves): """Add speakers to group.""" click.echo("Adding to existing group: %s" % slaves) click.echo(await gc.add(slaves))
python
async def add(gc: GroupControl, slaves): """Add speakers to group.""" click.echo("Adding to existing group: %s" % slaves) click.echo(await gc.add(slaves))
[ "async", "def", "add", "(", "gc", ":", "GroupControl", ",", "slaves", ")", ":", "click", ".", "echo", "(", "\"Adding to existing group: %s\"", "%", "slaves", ")", "click", ".", "echo", "(", "await", "gc", ".", "add", "(", "slaves", ")", ")" ]
Add speakers to group.
[ "Add", "speakers", "to", "group", "." ]
train
https://github.com/rytilahti/python-songpal/blob/0443de6b3d960b9067a851d82261ca00e46b4618/songpal/main.py#L715-L718
rytilahti/python-songpal
songpal/main.py
remove
async def remove(gc: GroupControl, slaves): """Remove speakers from group.""" click.echo("Removing from existing group: %s" % slaves) click.echo(await gc.remove(slaves))
python
async def remove(gc: GroupControl, slaves): """Remove speakers from group.""" click.echo("Removing from existing group: %s" % slaves) click.echo(await gc.remove(slaves))
[ "async", "def", "remove", "(", "gc", ":", "GroupControl", ",", "slaves", ")", ":", "click", ".", "echo", "(", "\"Removing from existing group: %s\"", "%", "slaves", ")", "click", ".", "echo", "(", "await", "gc", ".", "remove", "(", "slaves", ")", ")" ]
Remove speakers from group.
[ "Remove", "speakers", "from", "group", "." ]
train
https://github.com/rytilahti/python-songpal/blob/0443de6b3d960b9067a851d82261ca00e46b4618/songpal/main.py#L724-L727
rytilahti/python-songpal
songpal/main.py
volume
async def volume(gc: GroupControl, volume): """Adjust volume [-100, 100]""" click.echo("Setting volume to %s" % volume) click.echo(await gc.set_group_volume(volume))
python
async def volume(gc: GroupControl, volume): """Adjust volume [-100, 100]""" click.echo("Setting volume to %s" % volume) click.echo(await gc.set_group_volume(volume))
[ "async", "def", "volume", "(", "gc", ":", "GroupControl", ",", "volume", ")", ":", "click", ".", "echo", "(", "\"Setting volume to %s\"", "%", "volume", ")", "click", ".", "echo", "(", "await", "gc", ".", "set_group_volume", "(", "volume", ")", ")" ]
Adjust volume [-100, 100]
[ "Adjust", "volume", "[", "-", "100", "100", "]" ]
train
https://github.com/rytilahti/python-songpal/blob/0443de6b3d960b9067a851d82261ca00e46b4618/songpal/main.py#L733-L736
rytilahti/python-songpal
songpal/main.py
mute
async def mute(gc: GroupControl, mute): """(Un)mute group.""" click.echo("Muting group: %s" % mute) click.echo(await gc.set_mute(mute))
python
async def mute(gc: GroupControl, mute): """(Un)mute group.""" click.echo("Muting group: %s" % mute) click.echo(await gc.set_mute(mute))
[ "async", "def", "mute", "(", "gc", ":", "GroupControl", ",", "mute", ")", ":", "click", ".", "echo", "(", "\"Muting group: %s\"", "%", "mute", ")", "click", ".", "echo", "(", "await", "gc", ".", "set_mute", "(", "mute", ")", ")" ]
(Un)mute group.
[ "(", "Un", ")", "mute", "group", "." ]
train
https://github.com/rytilahti/python-songpal/blob/0443de6b3d960b9067a851d82261ca00e46b4618/songpal/main.py#L742-L745
rytilahti/python-songpal
songpal/discovery.py
Discover.discover
async def discover(timeout, debug=0, callback=None): """Discover supported devices.""" ST = "urn:schemas-sony-com:service:ScalarWebAPI:1" _LOGGER.info("Discovering for %s seconds" % timeout) from async_upnp_client import UpnpFactory from async_upnp_client.aiohttp import AiohttpRequester async def parse_device(device): requester = AiohttpRequester() factory = UpnpFactory(requester) url = device["location"] device = await factory.async_create_device(url) if debug > 0: print(etree.ElementTree.tostring(device.xml).decode()) NS = { 'av': 'urn:schemas-sony-com:av', } info = device.xml.find(".//av:X_ScalarWebAPI_DeviceInfo", NS) if not info: _LOGGER.error("Unable to find X_ScalaerWebAPI_DeviceInfo") return endpoint = info.find(".//av:X_ScalarWebAPI_BaseURL", NS).text version = info.find(".//av:X_ScalarWebAPI_Version", NS).text services = [x.text for x in info.findall(".//av:X_ScalarWebAPI_ServiceType", NS)] dev = DiscoveredDevice(name=device.name, model_number=device.model_number, udn=device.udn, endpoint=endpoint, version=version, services=services, upnp_services=list(device.services.keys()), upnp_location=url) _LOGGER.debug("Discovered: %s" % dev) if callback is not None: await callback(dev) await async_search(timeout=timeout, service_type=ST, async_callback=parse_device)
python
async def discover(timeout, debug=0, callback=None): """Discover supported devices.""" ST = "urn:schemas-sony-com:service:ScalarWebAPI:1" _LOGGER.info("Discovering for %s seconds" % timeout) from async_upnp_client import UpnpFactory from async_upnp_client.aiohttp import AiohttpRequester async def parse_device(device): requester = AiohttpRequester() factory = UpnpFactory(requester) url = device["location"] device = await factory.async_create_device(url) if debug > 0: print(etree.ElementTree.tostring(device.xml).decode()) NS = { 'av': 'urn:schemas-sony-com:av', } info = device.xml.find(".//av:X_ScalarWebAPI_DeviceInfo", NS) if not info: _LOGGER.error("Unable to find X_ScalaerWebAPI_DeviceInfo") return endpoint = info.find(".//av:X_ScalarWebAPI_BaseURL", NS).text version = info.find(".//av:X_ScalarWebAPI_Version", NS).text services = [x.text for x in info.findall(".//av:X_ScalarWebAPI_ServiceType", NS)] dev = DiscoveredDevice(name=device.name, model_number=device.model_number, udn=device.udn, endpoint=endpoint, version=version, services=services, upnp_services=list(device.services.keys()), upnp_location=url) _LOGGER.debug("Discovered: %s" % dev) if callback is not None: await callback(dev) await async_search(timeout=timeout, service_type=ST, async_callback=parse_device)
[ "async", "def", "discover", "(", "timeout", ",", "debug", "=", "0", ",", "callback", "=", "None", ")", ":", "ST", "=", "\"urn:schemas-sony-com:service:ScalarWebAPI:1\"", "_LOGGER", ".", "info", "(", "\"Discovering for %s seconds\"", "%", "timeout", ")", "from", "async_upnp_client", "import", "UpnpFactory", "from", "async_upnp_client", ".", "aiohttp", "import", "AiohttpRequester", "async", "def", "parse_device", "(", "device", ")", ":", "requester", "=", "AiohttpRequester", "(", ")", "factory", "=", "UpnpFactory", "(", "requester", ")", "url", "=", "device", "[", "\"location\"", "]", "device", "=", "await", "factory", ".", "async_create_device", "(", "url", ")", "if", "debug", ">", "0", ":", "print", "(", "etree", ".", "ElementTree", ".", "tostring", "(", "device", ".", "xml", ")", ".", "decode", "(", ")", ")", "NS", "=", "{", "'av'", ":", "'urn:schemas-sony-com:av'", ",", "}", "info", "=", "device", ".", "xml", ".", "find", "(", "\".//av:X_ScalarWebAPI_DeviceInfo\"", ",", "NS", ")", "if", "not", "info", ":", "_LOGGER", ".", "error", "(", "\"Unable to find X_ScalaerWebAPI_DeviceInfo\"", ")", "return", "endpoint", "=", "info", ".", "find", "(", "\".//av:X_ScalarWebAPI_BaseURL\"", ",", "NS", ")", ".", "text", "version", "=", "info", ".", "find", "(", "\".//av:X_ScalarWebAPI_Version\"", ",", "NS", ")", ".", "text", "services", "=", "[", "x", ".", "text", "for", "x", "in", "info", ".", "findall", "(", "\".//av:X_ScalarWebAPI_ServiceType\"", ",", "NS", ")", "]", "dev", "=", "DiscoveredDevice", "(", "name", "=", "device", ".", "name", ",", "model_number", "=", "device", ".", "model_number", ",", "udn", "=", "device", ".", "udn", ",", "endpoint", "=", "endpoint", ",", "version", "=", "version", ",", "services", "=", "services", ",", "upnp_services", "=", "list", "(", "device", ".", "services", ".", "keys", "(", ")", ")", ",", "upnp_location", "=", "url", ")", "_LOGGER", ".", "debug", "(", "\"Discovered: %s\"", "%", "dev", ")", "if", "callback", "is", "not", "None", ":", "await", "callback", "(", "dev", ")", "await", "async_search", "(", "timeout", "=", "timeout", ",", "service_type", "=", "ST", ",", "async_callback", "=", "parse_device", ")" ]
Discover supported devices.
[ "Discover", "supported", "devices", "." ]
train
https://github.com/rytilahti/python-songpal/blob/0443de6b3d960b9067a851d82261ca00e46b4618/songpal/discovery.py#L21-L68
kanboard/python-api-client
kanboard/client.py
Kanboard.execute
def execute(self, method, **kwargs): """ Call remote API procedure Args: method: Procedure name kwargs: Procedure named arguments Returns: Procedure result Raises: urllib2.HTTPError: Any HTTP error (Python 2) urllib.error.HTTPError: Any HTTP error (Python 3) """ payload = { 'id': 1, 'jsonrpc': '2.0', 'method': method, 'params': kwargs } credentials = base64.b64encode('{}:{}'.format(self._username, self._password).encode()) auth_header_prefix = 'Basic ' if self._auth_header == DEFAULT_AUTH_HEADER else '' headers = { self._auth_header: auth_header_prefix + credentials.decode(), 'Content-Type': 'application/json', } return self._do_request(headers, payload)
python
def execute(self, method, **kwargs): """ Call remote API procedure Args: method: Procedure name kwargs: Procedure named arguments Returns: Procedure result Raises: urllib2.HTTPError: Any HTTP error (Python 2) urllib.error.HTTPError: Any HTTP error (Python 3) """ payload = { 'id': 1, 'jsonrpc': '2.0', 'method': method, 'params': kwargs } credentials = base64.b64encode('{}:{}'.format(self._username, self._password).encode()) auth_header_prefix = 'Basic ' if self._auth_header == DEFAULT_AUTH_HEADER else '' headers = { self._auth_header: auth_header_prefix + credentials.decode(), 'Content-Type': 'application/json', } return self._do_request(headers, payload)
[ "def", "execute", "(", "self", ",", "method", ",", "*", "*", "kwargs", ")", ":", "payload", "=", "{", "'id'", ":", "1", ",", "'jsonrpc'", ":", "'2.0'", ",", "'method'", ":", "method", ",", "'params'", ":", "kwargs", "}", "credentials", "=", "base64", ".", "b64encode", "(", "'{}:{}'", ".", "format", "(", "self", ".", "_username", ",", "self", ".", "_password", ")", ".", "encode", "(", ")", ")", "auth_header_prefix", "=", "'Basic '", "if", "self", ".", "_auth_header", "==", "DEFAULT_AUTH_HEADER", "else", "''", "headers", "=", "{", "self", ".", "_auth_header", ":", "auth_header_prefix", "+", "credentials", ".", "decode", "(", ")", ",", "'Content-Type'", ":", "'application/json'", ",", "}", "return", "self", ".", "_do_request", "(", "headers", ",", "payload", ")" ]
Call remote API procedure Args: method: Procedure name kwargs: Procedure named arguments Returns: Procedure result Raises: urllib2.HTTPError: Any HTTP error (Python 2) urllib.error.HTTPError: Any HTTP error (Python 3)
[ "Call", "remote", "API", "procedure" ]
train
https://github.com/kanboard/python-api-client/blob/a1e81094bb399a9a3f4f14de67406e1d2bbee393/kanboard/client.py#L106-L135
bwesterb/py-tarjan
src/tc.py
tc
def tc(g): """ Given a graph @g, returns the transitive closure of @g """ ret = {} for scc in tarjan(g): ws = set() ews = set() for v in scc: ws.update(g[v]) for w in ws: assert w in ret or w in scc ews.add(w) ews.update(ret.get(w,())) if len(scc) > 1: ews.update(scc) ews = tuple(ews) for v in scc: ret[v] = ews return ret
python
def tc(g): """ Given a graph @g, returns the transitive closure of @g """ ret = {} for scc in tarjan(g): ws = set() ews = set() for v in scc: ws.update(g[v]) for w in ws: assert w in ret or w in scc ews.add(w) ews.update(ret.get(w,())) if len(scc) > 1: ews.update(scc) ews = tuple(ews) for v in scc: ret[v] = ews return ret
[ "def", "tc", "(", "g", ")", ":", "ret", "=", "{", "}", "for", "scc", "in", "tarjan", "(", "g", ")", ":", "ws", "=", "set", "(", ")", "ews", "=", "set", "(", ")", "for", "v", "in", "scc", ":", "ws", ".", "update", "(", "g", "[", "v", "]", ")", "for", "w", "in", "ws", ":", "assert", "w", "in", "ret", "or", "w", "in", "scc", "ews", ".", "add", "(", "w", ")", "ews", ".", "update", "(", "ret", ".", "get", "(", "w", ",", "(", ")", ")", ")", "if", "len", "(", "scc", ")", ">", "1", ":", "ews", ".", "update", "(", "scc", ")", "ews", "=", "tuple", "(", "ews", ")", "for", "v", "in", "scc", ":", "ret", "[", "v", "]", "=", "ews", "return", "ret" ]
Given a graph @g, returns the transitive closure of @g
[ "Given", "a", "graph" ]
train
https://github.com/bwesterb/py-tarjan/blob/60b0e3a1a7b925514fdce2ffbd84e1e246aba6d8/src/tc.py#L3-L20
manolomartinez/greg
greg/classes.py
Session.list_feeds
def list_feeds(self): """ Output a list of all feed names """ feeds = configparser.ConfigParser() feeds.read(self.data_filename) return feeds.sections()
python
def list_feeds(self): """ Output a list of all feed names """ feeds = configparser.ConfigParser() feeds.read(self.data_filename) return feeds.sections()
[ "def", "list_feeds", "(", "self", ")", ":", "feeds", "=", "configparser", ".", "ConfigParser", "(", ")", "feeds", ".", "read", "(", "self", ".", "data_filename", ")", "return", "feeds", ".", "sections", "(", ")" ]
Output a list of all feed names
[ "Output", "a", "list", "of", "all", "feed", "names" ]
train
https://github.com/manolomartinez/greg/blob/63bb24197c13087a01963ac439cd8380007d9467/greg/classes.py#L52-L58
manolomartinez/greg
greg/classes.py
Session.retrieve_config_file
def retrieve_config_file(self): """ Retrieve config file """ try: if self.args["configfile"]: return self.args["configfile"] except KeyError: pass return os.path.expanduser('~/.config/greg/greg.conf')
python
def retrieve_config_file(self): """ Retrieve config file """ try: if self.args["configfile"]: return self.args["configfile"] except KeyError: pass return os.path.expanduser('~/.config/greg/greg.conf')
[ "def", "retrieve_config_file", "(", "self", ")", ":", "try", ":", "if", "self", ".", "args", "[", "\"configfile\"", "]", ":", "return", "self", ".", "args", "[", "\"configfile\"", "]", "except", "KeyError", ":", "pass", "return", "os", ".", "path", ".", "expanduser", "(", "'~/.config/greg/greg.conf'", ")" ]
Retrieve config file
[ "Retrieve", "config", "file" ]
train
https://github.com/manolomartinez/greg/blob/63bb24197c13087a01963ac439cd8380007d9467/greg/classes.py#L60-L69
manolomartinez/greg
greg/classes.py
Session.retrieve_data_directory
def retrieve_data_directory(self): """ Retrieve the data directory Look first into config_filename_global then into config_filename_user. The latter takes preeminence. """ args = self.args try: if args['datadirectory']: aux.ensure_dir(args['datadirectory']) return args['datadirectory'] except KeyError: pass config = configparser.ConfigParser() config.read([config_filename_global, self.config_filename_user]) section = config.default_section data_path = config.get(section, 'Data directory', fallback='~/.local/share/greg') data_path_expanded = os.path.expanduser(data_path) aux.ensure_dir(data_path_expanded) return os.path.expanduser(data_path_expanded)
python
def retrieve_data_directory(self): """ Retrieve the data directory Look first into config_filename_global then into config_filename_user. The latter takes preeminence. """ args = self.args try: if args['datadirectory']: aux.ensure_dir(args['datadirectory']) return args['datadirectory'] except KeyError: pass config = configparser.ConfigParser() config.read([config_filename_global, self.config_filename_user]) section = config.default_section data_path = config.get(section, 'Data directory', fallback='~/.local/share/greg') data_path_expanded = os.path.expanduser(data_path) aux.ensure_dir(data_path_expanded) return os.path.expanduser(data_path_expanded)
[ "def", "retrieve_data_directory", "(", "self", ")", ":", "args", "=", "self", ".", "args", "try", ":", "if", "args", "[", "'datadirectory'", "]", ":", "aux", ".", "ensure_dir", "(", "args", "[", "'datadirectory'", "]", ")", "return", "args", "[", "'datadirectory'", "]", "except", "KeyError", ":", "pass", "config", "=", "configparser", ".", "ConfigParser", "(", ")", "config", ".", "read", "(", "[", "config_filename_global", ",", "self", ".", "config_filename_user", "]", ")", "section", "=", "config", ".", "default_section", "data_path", "=", "config", ".", "get", "(", "section", ",", "'Data directory'", ",", "fallback", "=", "'~/.local/share/greg'", ")", "data_path_expanded", "=", "os", ".", "path", ".", "expanduser", "(", "data_path", ")", "aux", ".", "ensure_dir", "(", "data_path_expanded", ")", "return", "os", ".", "path", ".", "expanduser", "(", "data_path_expanded", ")" ]
Retrieve the data directory Look first into config_filename_global then into config_filename_user. The latter takes preeminence.
[ "Retrieve", "the", "data", "directory", "Look", "first", "into", "config_filename_global", "then", "into", "config_filename_user", ".", "The", "latter", "takes", "preeminence", "." ]
train
https://github.com/manolomartinez/greg/blob/63bb24197c13087a01963ac439cd8380007d9467/greg/classes.py#L71-L91
manolomartinez/greg
greg/classes.py
Feed.retrieve_config
def retrieve_config(self, value, default): """ Retrieves a value (with a certain fallback) from the config files (looks first into config_filename_global then into config_filename_user. The latest takes preeminence) if the command line flag for the value is used, that overrides everything else """ args = self.args name = self.name try: if args[value]: return args[value] except KeyError: pass section = name if self.config.has_section( name) else self.config.default_section answer = self.config.get(section, value, fallback=default) return answer
python
def retrieve_config(self, value, default): """ Retrieves a value (with a certain fallback) from the config files (looks first into config_filename_global then into config_filename_user. The latest takes preeminence) if the command line flag for the value is used, that overrides everything else """ args = self.args name = self.name try: if args[value]: return args[value] except KeyError: pass section = name if self.config.has_section( name) else self.config.default_section answer = self.config.get(section, value, fallback=default) return answer
[ "def", "retrieve_config", "(", "self", ",", "value", ",", "default", ")", ":", "args", "=", "self", ".", "args", "name", "=", "self", ".", "name", "try", ":", "if", "args", "[", "value", "]", ":", "return", "args", "[", "value", "]", "except", "KeyError", ":", "pass", "section", "=", "name", "if", "self", ".", "config", ".", "has_section", "(", "name", ")", "else", "self", ".", "config", ".", "default_section", "answer", "=", "self", ".", "config", ".", "get", "(", "section", ",", "value", ",", "fallback", "=", "default", ")", "return", "answer" ]
Retrieves a value (with a certain fallback) from the config files (looks first into config_filename_global then into config_filename_user. The latest takes preeminence) if the command line flag for the value is used, that overrides everything else
[ "Retrieves", "a", "value", "(", "with", "a", "certain", "fallback", ")", "from", "the", "config", "files", "(", "looks", "first", "into", "config_filename_global", "then", "into", "config_filename_user", ".", "The", "latest", "takes", "preeminence", ")", "if", "the", "command", "line", "flag", "for", "the", "value", "is", "used", "that", "overrides", "everything", "else" ]
train
https://github.com/manolomartinez/greg/blob/63bb24197c13087a01963ac439cd8380007d9467/greg/classes.py#L119-L136
manolomartinez/greg
greg/classes.py
Feed.retrieve_download_path
def retrieve_download_path(self): """ Retrieves the download path (looks first into config_filename_global then into the [DEFAULT], then the [feed], section of config_filename_user. The latest takes preeminence) """ section = self.name if self.config.has_section( self.name) else self.config.default_section download_path = self.config.get( section, 'Download directory', fallback='~/Podcasts') subdirectory = self.config.get( section, 'Create subdirectories', fallback='no') return [os.path.expanduser(download_path), subdirectory]
python
def retrieve_download_path(self): """ Retrieves the download path (looks first into config_filename_global then into the [DEFAULT], then the [feed], section of config_filename_user. The latest takes preeminence) """ section = self.name if self.config.has_section( self.name) else self.config.default_section download_path = self.config.get( section, 'Download directory', fallback='~/Podcasts') subdirectory = self.config.get( section, 'Create subdirectories', fallback='no') return [os.path.expanduser(download_path), subdirectory]
[ "def", "retrieve_download_path", "(", "self", ")", ":", "section", "=", "self", ".", "name", "if", "self", ".", "config", ".", "has_section", "(", "self", ".", "name", ")", "else", "self", ".", "config", ".", "default_section", "download_path", "=", "self", ".", "config", ".", "get", "(", "section", ",", "'Download directory'", ",", "fallback", "=", "'~/Podcasts'", ")", "subdirectory", "=", "self", ".", "config", ".", "get", "(", "section", ",", "'Create subdirectories'", ",", "fallback", "=", "'no'", ")", "return", "[", "os", ".", "path", ".", "expanduser", "(", "download_path", ")", ",", "subdirectory", "]" ]
Retrieves the download path (looks first into config_filename_global then into the [DEFAULT], then the [feed], section of config_filename_user. The latest takes preeminence)
[ "Retrieves", "the", "download", "path", "(", "looks", "first", "into", "config_filename_global", "then", "into", "the", "[", "DEFAULT", "]", "then", "the", "[", "feed", "]", "section", "of", "config_filename_user", ".", "The", "latest", "takes", "preeminence", ")" ]
train
https://github.com/manolomartinez/greg/blob/63bb24197c13087a01963ac439cd8380007d9467/greg/classes.py#L146-L158
manolomartinez/greg
greg/classes.py
Feed.will_tag
def will_tag(self): """ Check whether the feed should be tagged """ wanttags = self.retrieve_config('Tag', 'no') if wanttags == 'yes': if aux.staggerexists: willtag = True else: willtag = False print(("You want me to tag {0}, but you have not installed " "the Stagger module. I cannot honour your request."). format(self.name), file=sys.stderr, flush=True) else: willtag = False return willtag
python
def will_tag(self): """ Check whether the feed should be tagged """ wanttags = self.retrieve_config('Tag', 'no') if wanttags == 'yes': if aux.staggerexists: willtag = True else: willtag = False print(("You want me to tag {0}, but you have not installed " "the Stagger module. I cannot honour your request."). format(self.name), file=sys.stderr, flush=True) else: willtag = False return willtag
[ "def", "will_tag", "(", "self", ")", ":", "wanttags", "=", "self", ".", "retrieve_config", "(", "'Tag'", ",", "'no'", ")", "if", "wanttags", "==", "'yes'", ":", "if", "aux", ".", "staggerexists", ":", "willtag", "=", "True", "else", ":", "willtag", "=", "False", "print", "(", "(", "\"You want me to tag {0}, but you have not installed \"", "\"the Stagger module. I cannot honour your request.\"", ")", ".", "format", "(", "self", ".", "name", ")", ",", "file", "=", "sys", ".", "stderr", ",", "flush", "=", "True", ")", "else", ":", "willtag", "=", "False", "return", "willtag" ]
Check whether the feed should be tagged
[ "Check", "whether", "the", "feed", "should", "be", "tagged" ]
train
https://github.com/manolomartinez/greg/blob/63bb24197c13087a01963ac439cd8380007d9467/greg/classes.py#L202-L217
manolomartinez/greg
greg/classes.py
Feed.how_many
def how_many(self): """ Ascertain where to start downloading, and how many entries. """ if self.linkdates != []: # What follows is a quick sanity check: if the entry date is in the # future, this is probably a mistake, and we just count the entry # date as right now. if max(self.linkdates) <= list(time.localtime()): currentdate = max(self.linkdates) else: currentdate = list(time.localtime()) print(("This entry has its date set in the future. " "I will use your current local time as its date " "instead."), file=sys.stderr, flush=True) stop = sys.maxsize else: currentdate = [1, 1, 1, 0, 0] firstsync = self.retrieve_config('firstsync', '1') if firstsync == 'all': stop = sys.maxsize else: stop = int(firstsync) return currentdate, stop
python
def how_many(self): """ Ascertain where to start downloading, and how many entries. """ if self.linkdates != []: # What follows is a quick sanity check: if the entry date is in the # future, this is probably a mistake, and we just count the entry # date as right now. if max(self.linkdates) <= list(time.localtime()): currentdate = max(self.linkdates) else: currentdate = list(time.localtime()) print(("This entry has its date set in the future. " "I will use your current local time as its date " "instead."), file=sys.stderr, flush=True) stop = sys.maxsize else: currentdate = [1, 1, 1, 0, 0] firstsync = self.retrieve_config('firstsync', '1') if firstsync == 'all': stop = sys.maxsize else: stop = int(firstsync) return currentdate, stop
[ "def", "how_many", "(", "self", ")", ":", "if", "self", ".", "linkdates", "!=", "[", "]", ":", "# What follows is a quick sanity check: if the entry date is in the", "# future, this is probably a mistake, and we just count the entry", "# date as right now.", "if", "max", "(", "self", ".", "linkdates", ")", "<=", "list", "(", "time", ".", "localtime", "(", ")", ")", ":", "currentdate", "=", "max", "(", "self", ".", "linkdates", ")", "else", ":", "currentdate", "=", "list", "(", "time", ".", "localtime", "(", ")", ")", "print", "(", "(", "\"This entry has its date set in the future. \"", "\"I will use your current local time as its date \"", "\"instead.\"", ")", ",", "file", "=", "sys", ".", "stderr", ",", "flush", "=", "True", ")", "stop", "=", "sys", ".", "maxsize", "else", ":", "currentdate", "=", "[", "1", ",", "1", ",", "1", ",", "0", ",", "0", "]", "firstsync", "=", "self", ".", "retrieve_config", "(", "'firstsync'", ",", "'1'", ")", "if", "firstsync", "==", "'all'", ":", "stop", "=", "sys", ".", "maxsize", "else", ":", "stop", "=", "int", "(", "firstsync", ")", "return", "currentdate", ",", "stop" ]
Ascertain where to start downloading, and how many entries.
[ "Ascertain", "where", "to", "start", "downloading", "and", "how", "many", "entries", "." ]
train
https://github.com/manolomartinez/greg/blob/63bb24197c13087a01963ac439cd8380007d9467/greg/classes.py#L219-L243
manolomartinez/greg
greg/classes.py
Feed.fix_linkdate
def fix_linkdate(self, entry): """ Give a date for the entry, depending on feed.sync_by_date Save it as feed.linkdate """ if self.sync_by_date: try: entry.linkdate = list(entry.published_parsed) self.linkdate = list(entry.published_parsed) except (AttributeError, TypeError): try: entry.linkdate = list(entry.updated_parsed) self.linkdate = list(entry.updated_parsed) except (AttributeError, TypeError): print(("This entry doesn't seem to have a parseable date. " "I will use your local time instead."), file=sys.stderr, flush=True) entry.linkdate = list(time.localtime()) self.linkdate = list(time.localtime()) else: entry.linkdate = list(time.localtime())
python
def fix_linkdate(self, entry): """ Give a date for the entry, depending on feed.sync_by_date Save it as feed.linkdate """ if self.sync_by_date: try: entry.linkdate = list(entry.published_parsed) self.linkdate = list(entry.published_parsed) except (AttributeError, TypeError): try: entry.linkdate = list(entry.updated_parsed) self.linkdate = list(entry.updated_parsed) except (AttributeError, TypeError): print(("This entry doesn't seem to have a parseable date. " "I will use your local time instead."), file=sys.stderr, flush=True) entry.linkdate = list(time.localtime()) self.linkdate = list(time.localtime()) else: entry.linkdate = list(time.localtime())
[ "def", "fix_linkdate", "(", "self", ",", "entry", ")", ":", "if", "self", ".", "sync_by_date", ":", "try", ":", "entry", ".", "linkdate", "=", "list", "(", "entry", ".", "published_parsed", ")", "self", ".", "linkdate", "=", "list", "(", "entry", ".", "published_parsed", ")", "except", "(", "AttributeError", ",", "TypeError", ")", ":", "try", ":", "entry", ".", "linkdate", "=", "list", "(", "entry", ".", "updated_parsed", ")", "self", ".", "linkdate", "=", "list", "(", "entry", ".", "updated_parsed", ")", "except", "(", "AttributeError", ",", "TypeError", ")", ":", "print", "(", "(", "\"This entry doesn't seem to have a parseable date. \"", "\"I will use your local time instead.\"", ")", ",", "file", "=", "sys", ".", "stderr", ",", "flush", "=", "True", ")", "entry", ".", "linkdate", "=", "list", "(", "time", ".", "localtime", "(", ")", ")", "self", ".", "linkdate", "=", "list", "(", "time", ".", "localtime", "(", ")", ")", "else", ":", "entry", ".", "linkdate", "=", "list", "(", "time", ".", "localtime", "(", ")", ")" ]
Give a date for the entry, depending on feed.sync_by_date Save it as feed.linkdate
[ "Give", "a", "date", "for", "the", "entry", "depending", "on", "feed", ".", "sync_by_date", "Save", "it", "as", "feed", ".", "linkdate" ]
train
https://github.com/manolomartinez/greg/blob/63bb24197c13087a01963ac439cd8380007d9467/greg/classes.py#L245-L265
manolomartinez/greg
greg/classes.py
Feed.retrieve_mime
def retrieve_mime(self): """ Check the mime-type to download """ mime = self.retrieve_config('mime', 'audio') mimedict = {"number": mime} # the input that parse_for_download expects return aux.parse_for_download(mimedict)
python
def retrieve_mime(self): """ Check the mime-type to download """ mime = self.retrieve_config('mime', 'audio') mimedict = {"number": mime} # the input that parse_for_download expects return aux.parse_for_download(mimedict)
[ "def", "retrieve_mime", "(", "self", ")", ":", "mime", "=", "self", ".", "retrieve_config", "(", "'mime'", ",", "'audio'", ")", "mimedict", "=", "{", "\"number\"", ":", "mime", "}", "# the input that parse_for_download expects", "return", "aux", ".", "parse_for_download", "(", "mimedict", ")" ]
Check the mime-type to download
[ "Check", "the", "mime", "-", "type", "to", "download" ]
train
https://github.com/manolomartinez/greg/blob/63bb24197c13087a01963ac439cd8380007d9467/greg/classes.py#L267-L274
manolomartinez/greg
greg/classes.py
Feed.download_entry
def download_entry(self, entry): """ Find entry link and download entry """ downloadlinks = {} downloaded = False ignoreenclosures = self.retrieve_config('ignoreenclosures', 'no') notype = self.retrieve_config('notype', 'no') if ignoreenclosures == 'no': for enclosure in entry.enclosures: if notype == 'yes': downloadlinks[urlparse(enclosure["href"]).path.split( "/")[-1]] = enclosure["href"] # preserve original name else: try: # We will download all enclosures of the desired # mime-type if any([mimetype in enclosure["type"] for mimetype in self.mime]): downloadlinks[urlparse( enclosure["href"]).path.split( "/")[-1]] = enclosure["href"] # preserve original name except KeyError: print("This podcast carries no information about " "enclosure types. Try using the notype " "option in your greg.conf", file=sys.stderr, flush=True) else: downloadlinks[urlparse(entry.link).query.split( "/")[-1]] = entry.link for podname in downloadlinks: if (podname, entry.linkdate) not in zip(self.entrylinks, self.linkdates): try: title = entry.title except: title = podname try: sanitizedsummary = aux.html_to_text(entry.summary) if sanitizedsummary == "": sanitizedsummary = "No summary available" except: sanitizedsummary = "No summary available" try: placeholders = Placeholders( self, entry, downloadlinks[podname], podname, title, sanitizedsummary) placeholders = aux.check_directory(placeholders) condition = aux.filtercond(placeholders) if condition: print("Downloading {} -- {}".format(title, podname)) aux.download_handler(self, placeholders) if self.willtag: aux.tag(placeholders) downloaded = True else: print("Skipping {} -- {}".format(title, podname)) downloaded = False if self.info: with open(self.info, 'a') as current: # We write to file this often to ensure that # downloaded entries count as downloaded. current.write(''.join([podname, ' ', str(entry.linkdate), '\n'])) except URLError: sys.exit(("... something went wrong. " "Are you connected to the internet?")) return downloaded
python
def download_entry(self, entry): """ Find entry link and download entry """ downloadlinks = {} downloaded = False ignoreenclosures = self.retrieve_config('ignoreenclosures', 'no') notype = self.retrieve_config('notype', 'no') if ignoreenclosures == 'no': for enclosure in entry.enclosures: if notype == 'yes': downloadlinks[urlparse(enclosure["href"]).path.split( "/")[-1]] = enclosure["href"] # preserve original name else: try: # We will download all enclosures of the desired # mime-type if any([mimetype in enclosure["type"] for mimetype in self.mime]): downloadlinks[urlparse( enclosure["href"]).path.split( "/")[-1]] = enclosure["href"] # preserve original name except KeyError: print("This podcast carries no information about " "enclosure types. Try using the notype " "option in your greg.conf", file=sys.stderr, flush=True) else: downloadlinks[urlparse(entry.link).query.split( "/")[-1]] = entry.link for podname in downloadlinks: if (podname, entry.linkdate) not in zip(self.entrylinks, self.linkdates): try: title = entry.title except: title = podname try: sanitizedsummary = aux.html_to_text(entry.summary) if sanitizedsummary == "": sanitizedsummary = "No summary available" except: sanitizedsummary = "No summary available" try: placeholders = Placeholders( self, entry, downloadlinks[podname], podname, title, sanitizedsummary) placeholders = aux.check_directory(placeholders) condition = aux.filtercond(placeholders) if condition: print("Downloading {} -- {}".format(title, podname)) aux.download_handler(self, placeholders) if self.willtag: aux.tag(placeholders) downloaded = True else: print("Skipping {} -- {}".format(title, podname)) downloaded = False if self.info: with open(self.info, 'a') as current: # We write to file this often to ensure that # downloaded entries count as downloaded. current.write(''.join([podname, ' ', str(entry.linkdate), '\n'])) except URLError: sys.exit(("... something went wrong. " "Are you connected to the internet?")) return downloaded
[ "def", "download_entry", "(", "self", ",", "entry", ")", ":", "downloadlinks", "=", "{", "}", "downloaded", "=", "False", "ignoreenclosures", "=", "self", ".", "retrieve_config", "(", "'ignoreenclosures'", ",", "'no'", ")", "notype", "=", "self", ".", "retrieve_config", "(", "'notype'", ",", "'no'", ")", "if", "ignoreenclosures", "==", "'no'", ":", "for", "enclosure", "in", "entry", ".", "enclosures", ":", "if", "notype", "==", "'yes'", ":", "downloadlinks", "[", "urlparse", "(", "enclosure", "[", "\"href\"", "]", ")", ".", "path", ".", "split", "(", "\"/\"", ")", "[", "-", "1", "]", "]", "=", "enclosure", "[", "\"href\"", "]", "# preserve original name", "else", ":", "try", ":", "# We will download all enclosures of the desired", "# mime-type", "if", "any", "(", "[", "mimetype", "in", "enclosure", "[", "\"type\"", "]", "for", "mimetype", "in", "self", ".", "mime", "]", ")", ":", "downloadlinks", "[", "urlparse", "(", "enclosure", "[", "\"href\"", "]", ")", ".", "path", ".", "split", "(", "\"/\"", ")", "[", "-", "1", "]", "]", "=", "enclosure", "[", "\"href\"", "]", "# preserve original name", "except", "KeyError", ":", "print", "(", "\"This podcast carries no information about \"", "\"enclosure types. Try using the notype \"", "\"option in your greg.conf\"", ",", "file", "=", "sys", ".", "stderr", ",", "flush", "=", "True", ")", "else", ":", "downloadlinks", "[", "urlparse", "(", "entry", ".", "link", ")", ".", "query", ".", "split", "(", "\"/\"", ")", "[", "-", "1", "]", "]", "=", "entry", ".", "link", "for", "podname", "in", "downloadlinks", ":", "if", "(", "podname", ",", "entry", ".", "linkdate", ")", "not", "in", "zip", "(", "self", ".", "entrylinks", ",", "self", ".", "linkdates", ")", ":", "try", ":", "title", "=", "entry", ".", "title", "except", ":", "title", "=", "podname", "try", ":", "sanitizedsummary", "=", "aux", ".", "html_to_text", "(", "entry", ".", "summary", ")", "if", "sanitizedsummary", "==", "\"\"", ":", "sanitizedsummary", "=", "\"No summary available\"", "except", ":", "sanitizedsummary", "=", "\"No summary available\"", "try", ":", "placeholders", "=", "Placeholders", "(", "self", ",", "entry", ",", "downloadlinks", "[", "podname", "]", ",", "podname", ",", "title", ",", "sanitizedsummary", ")", "placeholders", "=", "aux", ".", "check_directory", "(", "placeholders", ")", "condition", "=", "aux", ".", "filtercond", "(", "placeholders", ")", "if", "condition", ":", "print", "(", "\"Downloading {} -- {}\"", ".", "format", "(", "title", ",", "podname", ")", ")", "aux", ".", "download_handler", "(", "self", ",", "placeholders", ")", "if", "self", ".", "willtag", ":", "aux", ".", "tag", "(", "placeholders", ")", "downloaded", "=", "True", "else", ":", "print", "(", "\"Skipping {} -- {}\"", ".", "format", "(", "title", ",", "podname", ")", ")", "downloaded", "=", "False", "if", "self", ".", "info", ":", "with", "open", "(", "self", ".", "info", ",", "'a'", ")", "as", "current", ":", "# We write to file this often to ensure that", "# downloaded entries count as downloaded.", "current", ".", "write", "(", "''", ".", "join", "(", "[", "podname", ",", "' '", ",", "str", "(", "entry", ".", "linkdate", ")", ",", "'\\n'", "]", ")", ")", "except", "URLError", ":", "sys", ".", "exit", "(", "(", "\"... something went wrong. \"", "\"Are you connected to the internet?\"", ")", ")", "return", "downloaded" ]
Find entry link and download entry
[ "Find", "entry", "link", "and", "download", "entry" ]
train
https://github.com/manolomartinez/greg/blob/63bb24197c13087a01963ac439cd8380007d9467/greg/classes.py#L276-L345
manolomartinez/greg
greg/parser.py
main
def main(): """ Parse the args and call whatever function was selected """ args = parser.parse_args() try: function = args.func except AttributeError: parser.print_usage() parser.exit(1) function(vars(args))
python
def main(): """ Parse the args and call whatever function was selected """ args = parser.parse_args() try: function = args.func except AttributeError: parser.print_usage() parser.exit(1) function(vars(args))
[ "def", "main", "(", ")", ":", "args", "=", "parser", ".", "parse_args", "(", ")", "try", ":", "function", "=", "args", ".", "func", "except", "AttributeError", ":", "parser", ".", "print_usage", "(", ")", "parser", ".", "exit", "(", "1", ")", "function", "(", "vars", "(", "args", ")", ")" ]
Parse the args and call whatever function was selected
[ "Parse", "the", "args", "and", "call", "whatever", "function", "was", "selected" ]
train
https://github.com/manolomartinez/greg/blob/63bb24197c13087a01963ac439cd8380007d9467/greg/parser.py#L128-L138
manolomartinez/greg
greg/commands.py
add
def add(args): """ Add a new feed """ session = c.Session(args) if args["name"] in session.feeds.sections(): sys.exit("You already have a feed with that name.") if args["name"] in ["all", "DEFAULT"]: sys.exit( ("greg uses ""{}"" for a special purpose." "Please choose another name for your feed.").format(args["name"])) entry = {} for key, value in args.items(): if value is not None and key != "func" and key != "name": entry[key] = value session.feeds[args["name"]] = entry with open(session.data_filename, 'w') as configfile: session.feeds.write(configfile)
python
def add(args): """ Add a new feed """ session = c.Session(args) if args["name"] in session.feeds.sections(): sys.exit("You already have a feed with that name.") if args["name"] in ["all", "DEFAULT"]: sys.exit( ("greg uses ""{}"" for a special purpose." "Please choose another name for your feed.").format(args["name"])) entry = {} for key, value in args.items(): if value is not None and key != "func" and key != "name": entry[key] = value session.feeds[args["name"]] = entry with open(session.data_filename, 'w') as configfile: session.feeds.write(configfile)
[ "def", "add", "(", "args", ")", ":", "session", "=", "c", ".", "Session", "(", "args", ")", "if", "args", "[", "\"name\"", "]", "in", "session", ".", "feeds", ".", "sections", "(", ")", ":", "sys", ".", "exit", "(", "\"You already have a feed with that name.\"", ")", "if", "args", "[", "\"name\"", "]", "in", "[", "\"all\"", ",", "\"DEFAULT\"", "]", ":", "sys", ".", "exit", "(", "(", "\"greg uses \"", "\"{}\"", "\" for a special purpose.\"", "\"Please choose another name for your feed.\"", ")", ".", "format", "(", "args", "[", "\"name\"", "]", ")", ")", "entry", "=", "{", "}", "for", "key", ",", "value", "in", "args", ".", "items", "(", ")", ":", "if", "value", "is", "not", "None", "and", "key", "!=", "\"func\"", "and", "key", "!=", "\"name\"", ":", "entry", "[", "key", "]", "=", "value", "session", ".", "feeds", "[", "args", "[", "\"name\"", "]", "]", "=", "entry", "with", "open", "(", "session", ".", "data_filename", ",", "'w'", ")", "as", "configfile", ":", "session", ".", "feeds", ".", "write", "(", "configfile", ")" ]
Add a new feed
[ "Add", "a", "new", "feed" ]
train
https://github.com/manolomartinez/greg/blob/63bb24197c13087a01963ac439cd8380007d9467/greg/commands.py#L35-L52
manolomartinez/greg
greg/commands.py
remove
def remove(args): """ Remove the feed given in <args> """ session = c.Session(args) if not args["name"] in session.feeds: sys.exit("You don't have a feed with that name.") inputtext = ("Are you sure you want to remove the {} " " feed? (y/N) ").format(args["name"]) reply = input(inputtext) if reply != "y" and reply != "Y": return 0 else: session.feeds.remove_section(args["name"]) with open(session.data_filename, 'w') as configfile: session.feeds.write(configfile) try: os.remove(os.path.join(session.data_dir, args["name"])) except FileNotFoundError: pass
python
def remove(args): """ Remove the feed given in <args> """ session = c.Session(args) if not args["name"] in session.feeds: sys.exit("You don't have a feed with that name.") inputtext = ("Are you sure you want to remove the {} " " feed? (y/N) ").format(args["name"]) reply = input(inputtext) if reply != "y" and reply != "Y": return 0 else: session.feeds.remove_section(args["name"]) with open(session.data_filename, 'w') as configfile: session.feeds.write(configfile) try: os.remove(os.path.join(session.data_dir, args["name"])) except FileNotFoundError: pass
[ "def", "remove", "(", "args", ")", ":", "session", "=", "c", ".", "Session", "(", "args", ")", "if", "not", "args", "[", "\"name\"", "]", "in", "session", ".", "feeds", ":", "sys", ".", "exit", "(", "\"You don't have a feed with that name.\"", ")", "inputtext", "=", "(", "\"Are you sure you want to remove the {} \"", "\" feed? (y/N) \"", ")", ".", "format", "(", "args", "[", "\"name\"", "]", ")", "reply", "=", "input", "(", "inputtext", ")", "if", "reply", "!=", "\"y\"", "and", "reply", "!=", "\"Y\"", ":", "return", "0", "else", ":", "session", ".", "feeds", ".", "remove_section", "(", "args", "[", "\"name\"", "]", ")", "with", "open", "(", "session", ".", "data_filename", ",", "'w'", ")", "as", "configfile", ":", "session", ".", "feeds", ".", "write", "(", "configfile", ")", "try", ":", "os", ".", "remove", "(", "os", ".", "path", ".", "join", "(", "session", ".", "data_dir", ",", "args", "[", "\"name\"", "]", ")", ")", "except", "FileNotFoundError", ":", "pass" ]
Remove the feed given in <args>
[ "Remove", "the", "feed", "given", "in", "<args", ">" ]
train
https://github.com/manolomartinez/greg/blob/63bb24197c13087a01963ac439cd8380007d9467/greg/commands.py#L98-L117
manolomartinez/greg
greg/commands.py
info
def info(args): """ Provide information of a number of feeds """ session = c.Session(args) if "all" in args["names"]: feeds = session.list_feeds() else: feeds = args["names"] for feed in feeds: aux.pretty_print(session, feed)
python
def info(args): """ Provide information of a number of feeds """ session = c.Session(args) if "all" in args["names"]: feeds = session.list_feeds() else: feeds = args["names"] for feed in feeds: aux.pretty_print(session, feed)
[ "def", "info", "(", "args", ")", ":", "session", "=", "c", ".", "Session", "(", "args", ")", "if", "\"all\"", "in", "args", "[", "\"names\"", "]", ":", "feeds", "=", "session", ".", "list_feeds", "(", ")", "else", ":", "feeds", "=", "args", "[", "\"names\"", "]", "for", "feed", "in", "feeds", ":", "aux", ".", "pretty_print", "(", "session", ",", "feed", ")" ]
Provide information of a number of feeds
[ "Provide", "information", "of", "a", "number", "of", "feeds" ]
train
https://github.com/manolomartinez/greg/blob/63bb24197c13087a01963ac439cd8380007d9467/greg/commands.py#L120-L130
manolomartinez/greg
greg/commands.py
sync
def sync(args): """ Implement the 'greg sync' command """ import operator session = c.Session(args) if "all" in args["names"]: targetfeeds = session.list_feeds() else: targetfeeds = [] for name in args["names"]: if name not in session.feeds: print("You don't have a feed called {}." .format(name), file=sys.stderr, flush=True) else: targetfeeds.append(name) for target in targetfeeds: feed = c.Feed(session, target, None) if not feed.wentwrong: try: title = feed.podcast.target.title except AttributeError: title = target print("Checking", title, end="...\n") currentdate, stop = feed.how_many() entrycounter = 0 entries_to_download = feed.podcast.entries for entry in entries_to_download: feed.fix_linkdate(entry) # Sort entries_to_download, but only if you want to download as # many as there are if stop >= len(entries_to_download): entries_to_download.sort(key=operator.attrgetter("linkdate"), reverse=False) for entry in entries_to_download: if entry.linkdate > currentdate: downloaded = feed.download_entry(entry) entrycounter += downloaded if entrycounter >= stop: break print("Done") else: msg = ''.join(["I cannot sync ", feed, " just now. Are you connected to the internet?"]) print(msg, file=sys.stderr, flush=True)
python
def sync(args): """ Implement the 'greg sync' command """ import operator session = c.Session(args) if "all" in args["names"]: targetfeeds = session.list_feeds() else: targetfeeds = [] for name in args["names"]: if name not in session.feeds: print("You don't have a feed called {}." .format(name), file=sys.stderr, flush=True) else: targetfeeds.append(name) for target in targetfeeds: feed = c.Feed(session, target, None) if not feed.wentwrong: try: title = feed.podcast.target.title except AttributeError: title = target print("Checking", title, end="...\n") currentdate, stop = feed.how_many() entrycounter = 0 entries_to_download = feed.podcast.entries for entry in entries_to_download: feed.fix_linkdate(entry) # Sort entries_to_download, but only if you want to download as # many as there are if stop >= len(entries_to_download): entries_to_download.sort(key=operator.attrgetter("linkdate"), reverse=False) for entry in entries_to_download: if entry.linkdate > currentdate: downloaded = feed.download_entry(entry) entrycounter += downloaded if entrycounter >= stop: break print("Done") else: msg = ''.join(["I cannot sync ", feed, " just now. Are you connected to the internet?"]) print(msg, file=sys.stderr, flush=True)
[ "def", "sync", "(", "args", ")", ":", "import", "operator", "session", "=", "c", ".", "Session", "(", "args", ")", "if", "\"all\"", "in", "args", "[", "\"names\"", "]", ":", "targetfeeds", "=", "session", ".", "list_feeds", "(", ")", "else", ":", "targetfeeds", "=", "[", "]", "for", "name", "in", "args", "[", "\"names\"", "]", ":", "if", "name", "not", "in", "session", ".", "feeds", ":", "print", "(", "\"You don't have a feed called {}.\"", ".", "format", "(", "name", ")", ",", "file", "=", "sys", ".", "stderr", ",", "flush", "=", "True", ")", "else", ":", "targetfeeds", ".", "append", "(", "name", ")", "for", "target", "in", "targetfeeds", ":", "feed", "=", "c", ".", "Feed", "(", "session", ",", "target", ",", "None", ")", "if", "not", "feed", ".", "wentwrong", ":", "try", ":", "title", "=", "feed", ".", "podcast", ".", "target", ".", "title", "except", "AttributeError", ":", "title", "=", "target", "print", "(", "\"Checking\"", ",", "title", ",", "end", "=", "\"...\\n\"", ")", "currentdate", ",", "stop", "=", "feed", ".", "how_many", "(", ")", "entrycounter", "=", "0", "entries_to_download", "=", "feed", ".", "podcast", ".", "entries", "for", "entry", "in", "entries_to_download", ":", "feed", ".", "fix_linkdate", "(", "entry", ")", "# Sort entries_to_download, but only if you want to download as", "# many as there are", "if", "stop", ">=", "len", "(", "entries_to_download", ")", ":", "entries_to_download", ".", "sort", "(", "key", "=", "operator", ".", "attrgetter", "(", "\"linkdate\"", ")", ",", "reverse", "=", "False", ")", "for", "entry", "in", "entries_to_download", ":", "if", "entry", ".", "linkdate", ">", "currentdate", ":", "downloaded", "=", "feed", ".", "download_entry", "(", "entry", ")", "entrycounter", "+=", "downloaded", "if", "entrycounter", ">=", "stop", ":", "break", "print", "(", "\"Done\"", ")", "else", ":", "msg", "=", "''", ".", "join", "(", "[", "\"I cannot sync \"", ",", "feed", ",", "\" just now. Are you connected to the internet?\"", "]", ")", "print", "(", "msg", ",", "file", "=", "sys", ".", "stderr", ",", "flush", "=", "True", ")" ]
Implement the 'greg sync' command
[ "Implement", "the", "greg", "sync", "command" ]
train
https://github.com/manolomartinez/greg/blob/63bb24197c13087a01963ac439cd8380007d9467/greg/commands.py#L140-L184
manolomartinez/greg
greg/commands.py
check
def check(args): """ Implement the 'greg check' command """ session = c.Session(args) if str(args["url"]) != 'None': url = args["url"] name = "DEFAULT" else: try: url = session.feeds[args["feed"]]["url"] name = args["feed"] except KeyError: sys.exit("You don't appear to have a feed with that name.") podcast = aux.parse_podcast(url) for entry in enumerate(podcast.entries): listentry = list(entry) print(listentry[0], end=": ") try: print(listentry[1]["title"], end=" (") except: print(listentry[1]["link"], end=" (") try: print(listentry[1]["updated"], end=")") except: print("", end=")") print() dumpfilename = os.path.join(session.data_dir, 'feeddump') with open(dumpfilename, mode='wb') as dumpfile: dump = [name, podcast] pickle.dump(dump, dumpfile)
python
def check(args): """ Implement the 'greg check' command """ session = c.Session(args) if str(args["url"]) != 'None': url = args["url"] name = "DEFAULT" else: try: url = session.feeds[args["feed"]]["url"] name = args["feed"] except KeyError: sys.exit("You don't appear to have a feed with that name.") podcast = aux.parse_podcast(url) for entry in enumerate(podcast.entries): listentry = list(entry) print(listentry[0], end=": ") try: print(listentry[1]["title"], end=" (") except: print(listentry[1]["link"], end=" (") try: print(listentry[1]["updated"], end=")") except: print("", end=")") print() dumpfilename = os.path.join(session.data_dir, 'feeddump') with open(dumpfilename, mode='wb') as dumpfile: dump = [name, podcast] pickle.dump(dump, dumpfile)
[ "def", "check", "(", "args", ")", ":", "session", "=", "c", ".", "Session", "(", "args", ")", "if", "str", "(", "args", "[", "\"url\"", "]", ")", "!=", "'None'", ":", "url", "=", "args", "[", "\"url\"", "]", "name", "=", "\"DEFAULT\"", "else", ":", "try", ":", "url", "=", "session", ".", "feeds", "[", "args", "[", "\"feed\"", "]", "]", "[", "\"url\"", "]", "name", "=", "args", "[", "\"feed\"", "]", "except", "KeyError", ":", "sys", ".", "exit", "(", "\"You don't appear to have a feed with that name.\"", ")", "podcast", "=", "aux", ".", "parse_podcast", "(", "url", ")", "for", "entry", "in", "enumerate", "(", "podcast", ".", "entries", ")", ":", "listentry", "=", "list", "(", "entry", ")", "print", "(", "listentry", "[", "0", "]", ",", "end", "=", "\": \"", ")", "try", ":", "print", "(", "listentry", "[", "1", "]", "[", "\"title\"", "]", ",", "end", "=", "\" (\"", ")", "except", ":", "print", "(", "listentry", "[", "1", "]", "[", "\"link\"", "]", ",", "end", "=", "\" (\"", ")", "try", ":", "print", "(", "listentry", "[", "1", "]", "[", "\"updated\"", "]", ",", "end", "=", "\")\"", ")", "except", ":", "print", "(", "\"\"", ",", "end", "=", "\")\"", ")", "print", "(", ")", "dumpfilename", "=", "os", ".", "path", ".", "join", "(", "session", ".", "data_dir", ",", "'feeddump'", ")", "with", "open", "(", "dumpfilename", ",", "mode", "=", "'wb'", ")", "as", "dumpfile", ":", "dump", "=", "[", "name", ",", "podcast", "]", "pickle", ".", "dump", "(", "dump", ",", "dumpfile", ")" ]
Implement the 'greg check' command
[ "Implement", "the", "greg", "check", "command" ]
train
https://github.com/manolomartinez/greg/blob/63bb24197c13087a01963ac439cd8380007d9467/greg/commands.py#L187-L217
manolomartinez/greg
greg/commands.py
download
def download(args): """ Implement the 'greg download' command """ session = c.Session(args) issues = aux.parse_for_download(args) if issues == ['']: sys.exit( "You need to give a list of issues, of the form ""a, b-c, d...""") dumpfilename = os.path.join(session.data_dir, 'feeddump') if not os.path.isfile(dumpfilename): sys.exit( ("You need to run ""greg check" "<feed>"" before using ""greg download"".")) with open(dumpfilename, mode='rb') as dumpfile: dump = pickle.load(dumpfile) try: feed = c.Feed(session, dump[0], dump[1]) except Exception: sys.exit(( "... something went wrong." "Are you sure your last ""greg check"" went well?")) for number in issues: entry = dump[1].entries[eval(number)] feed.info = [] feed.entrylinks = [] feed.fix_linkdate(entry) feed.download_entry(entry)
python
def download(args): """ Implement the 'greg download' command """ session = c.Session(args) issues = aux.parse_for_download(args) if issues == ['']: sys.exit( "You need to give a list of issues, of the form ""a, b-c, d...""") dumpfilename = os.path.join(session.data_dir, 'feeddump') if not os.path.isfile(dumpfilename): sys.exit( ("You need to run ""greg check" "<feed>"" before using ""greg download"".")) with open(dumpfilename, mode='rb') as dumpfile: dump = pickle.load(dumpfile) try: feed = c.Feed(session, dump[0], dump[1]) except Exception: sys.exit(( "... something went wrong." "Are you sure your last ""greg check"" went well?")) for number in issues: entry = dump[1].entries[eval(number)] feed.info = [] feed.entrylinks = [] feed.fix_linkdate(entry) feed.download_entry(entry)
[ "def", "download", "(", "args", ")", ":", "session", "=", "c", ".", "Session", "(", "args", ")", "issues", "=", "aux", ".", "parse_for_download", "(", "args", ")", "if", "issues", "==", "[", "''", "]", ":", "sys", ".", "exit", "(", "\"You need to give a list of issues, of the form \"", "\"a, b-c, d...\"", "\"\"", ")", "dumpfilename", "=", "os", ".", "path", ".", "join", "(", "session", ".", "data_dir", ",", "'feeddump'", ")", "if", "not", "os", ".", "path", ".", "isfile", "(", "dumpfilename", ")", ":", "sys", ".", "exit", "(", "(", "\"You need to run \"", "\"greg check\"", "\"<feed>\"", "\" before using \"", "\"greg download\"", "\".\"", ")", ")", "with", "open", "(", "dumpfilename", ",", "mode", "=", "'rb'", ")", "as", "dumpfile", ":", "dump", "=", "pickle", ".", "load", "(", "dumpfile", ")", "try", ":", "feed", "=", "c", ".", "Feed", "(", "session", ",", "dump", "[", "0", "]", ",", "dump", "[", "1", "]", ")", "except", "Exception", ":", "sys", ".", "exit", "(", "(", "\"... something went wrong.\"", "\"Are you sure your last \"", "\"greg check\"", "\" went well?\"", ")", ")", "for", "number", "in", "issues", ":", "entry", "=", "dump", "[", "1", "]", ".", "entries", "[", "eval", "(", "number", ")", "]", "feed", ".", "info", "=", "[", "]", "feed", ".", "entrylinks", "=", "[", "]", "feed", ".", "fix_linkdate", "(", "entry", ")", "feed", ".", "download_entry", "(", "entry", ")" ]
Implement the 'greg download' command
[ "Implement", "the", "greg", "download", "command" ]
train
https://github.com/manolomartinez/greg/blob/63bb24197c13087a01963ac439cd8380007d9467/greg/commands.py#L220-L247
manolomartinez/greg
greg/aux_functions.py
parse_podcast
def parse_podcast(url): """ Try to parse podcast """ try: podcast = feedparser.parse(url) wentwrong = "urlopen" in str(podcast["bozo_exception"]) except KeyError: wentwrong = False if wentwrong: print("Error: ", url, ": ", str(podcast["bozo_exception"])) return podcast
python
def parse_podcast(url): """ Try to parse podcast """ try: podcast = feedparser.parse(url) wentwrong = "urlopen" in str(podcast["bozo_exception"]) except KeyError: wentwrong = False if wentwrong: print("Error: ", url, ": ", str(podcast["bozo_exception"])) return podcast
[ "def", "parse_podcast", "(", "url", ")", ":", "try", ":", "podcast", "=", "feedparser", ".", "parse", "(", "url", ")", "wentwrong", "=", "\"urlopen\"", "in", "str", "(", "podcast", "[", "\"bozo_exception\"", "]", ")", "except", "KeyError", ":", "wentwrong", "=", "False", "if", "wentwrong", ":", "print", "(", "\"Error: \"", ",", "url", ",", "\": \"", ",", "str", "(", "podcast", "[", "\"bozo_exception\"", "]", ")", ")", "return", "podcast" ]
Try to parse podcast
[ "Try", "to", "parse", "podcast" ]
train
https://github.com/manolomartinez/greg/blob/63bb24197c13087a01963ac439cd8380007d9467/greg/aux_functions.py#L93-L104