id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
7,100
tchellomello/python-arlo
pyarlo/__init__.py
PyArlo.lookup_camera_by_id
def lookup_camera_by_id(self, device_id): """Return camera object by device_id.""" camera = list(filter( lambda cam: cam.device_id == device_id, self.cameras))[0] if camera: return camera return None
python
def lookup_camera_by_id(self, device_id): """Return camera object by device_id.""" camera = list(filter( lambda cam: cam.device_id == device_id, self.cameras))[0] if camera: return camera return None
[ "def", "lookup_camera_by_id", "(", "self", ",", "device_id", ")", ":", "camera", "=", "list", "(", "filter", "(", "lambda", "cam", ":", "cam", ".", "device_id", "==", "device_id", ",", "self", ".", "cameras", ")", ")", "[", "0", "]", "if", "camera", ":", "return", "camera", "return", "None" ]
Return camera object by device_id.
[ "Return", "camera", "object", "by", "device_id", "." ]
db70aeb81705309c56ad32bbab1094f6cd146524
https://github.com/tchellomello/python-arlo/blob/db70aeb81705309c56ad32bbab1094f6cd146524/pyarlo/__init__.py#L200-L206
7,101
tchellomello/python-arlo
pyarlo/__init__.py
PyArlo.refresh_attributes
def refresh_attributes(self, name): """Refresh attributes from a given Arlo object.""" url = DEVICES_ENDPOINT response = self.query(url) if not response or not isinstance(response, dict): return None for device in response.get('data'): if device.get('deviceName') == name: return device return None
python
def refresh_attributes(self, name): """Refresh attributes from a given Arlo object.""" url = DEVICES_ENDPOINT response = self.query(url) if not response or not isinstance(response, dict): return None for device in response.get('data'): if device.get('deviceName') == name: return device return None
[ "def", "refresh_attributes", "(", "self", ",", "name", ")", ":", "url", "=", "DEVICES_ENDPOINT", "response", "=", "self", ".", "query", "(", "url", ")", "if", "not", "response", "or", "not", "isinstance", "(", "response", ",", "dict", ")", ":", "return", "None", "for", "device", "in", "response", ".", "get", "(", "'data'", ")", ":", "if", "device", ".", "get", "(", "'deviceName'", ")", "==", "name", ":", "return", "device", "return", "None" ]
Refresh attributes from a given Arlo object.
[ "Refresh", "attributes", "from", "a", "given", "Arlo", "object", "." ]
db70aeb81705309c56ad32bbab1094f6cd146524
https://github.com/tchellomello/python-arlo/blob/db70aeb81705309c56ad32bbab1094f6cd146524/pyarlo/__init__.py#L208-L219
7,102
tchellomello/python-arlo
pyarlo/__init__.py
PyArlo.update
def update(self, update_cameras=False, update_base_station=False): """Refresh object.""" self._authenticate() # update attributes in all cameras to avoid duped queries if update_cameras: url = DEVICES_ENDPOINT response = self.query(url) if not response or not isinstance(response, dict): return for camera in self.cameras: for dev_info in response.get('data'): if dev_info.get('deviceName') == camera.name: _LOGGER.debug("Refreshing %s attributes", camera.name) camera.attrs = dev_info # preload cached videos # the user is still able to force a new query by # calling the Arlo.video() camera.make_video_cache() # force update base_station if update_base_station: for base in self.base_stations: base.update()
python
def update(self, update_cameras=False, update_base_station=False): """Refresh object.""" self._authenticate() # update attributes in all cameras to avoid duped queries if update_cameras: url = DEVICES_ENDPOINT response = self.query(url) if not response or not isinstance(response, dict): return for camera in self.cameras: for dev_info in response.get('data'): if dev_info.get('deviceName') == camera.name: _LOGGER.debug("Refreshing %s attributes", camera.name) camera.attrs = dev_info # preload cached videos # the user is still able to force a new query by # calling the Arlo.video() camera.make_video_cache() # force update base_station if update_base_station: for base in self.base_stations: base.update()
[ "def", "update", "(", "self", ",", "update_cameras", "=", "False", ",", "update_base_station", "=", "False", ")", ":", "self", ".", "_authenticate", "(", ")", "# update attributes in all cameras to avoid duped queries", "if", "update_cameras", ":", "url", "=", "DEVICES_ENDPOINT", "response", "=", "self", ".", "query", "(", "url", ")", "if", "not", "response", "or", "not", "isinstance", "(", "response", ",", "dict", ")", ":", "return", "for", "camera", "in", "self", ".", "cameras", ":", "for", "dev_info", "in", "response", ".", "get", "(", "'data'", ")", ":", "if", "dev_info", ".", "get", "(", "'deviceName'", ")", "==", "camera", ".", "name", ":", "_LOGGER", ".", "debug", "(", "\"Refreshing %s attributes\"", ",", "camera", ".", "name", ")", "camera", ".", "attrs", "=", "dev_info", "# preload cached videos", "# the user is still able to force a new query by", "# calling the Arlo.video()", "camera", ".", "make_video_cache", "(", ")", "# force update base_station", "if", "update_base_station", ":", "for", "base", "in", "self", ".", "base_stations", ":", "base", ".", "update", "(", ")" ]
Refresh object.
[ "Refresh", "object", "." ]
db70aeb81705309c56ad32bbab1094f6cd146524
https://github.com/tchellomello/python-arlo/blob/db70aeb81705309c56ad32bbab1094f6cd146524/pyarlo/__init__.py#L249-L274
7,103
tchellomello/python-arlo
pyarlo/media.py
ArloMediaLibrary.load
def load(self, days=PRELOAD_DAYS, only_cameras=None, date_from=None, date_to=None, limit=None): """Load Arlo videos from the given criteria :param days: number of days to retrieve :param only_cameras: retrieve only <ArloCamera> on that list :param date_from: refine from initial date :param date_to: refine final date :param limit: define number of objects to return """ videos = [] url = LIBRARY_ENDPOINT if not (date_from and date_to): now = datetime.today() date_from = (now - timedelta(days=days)).strftime('%Y%m%d') date_to = now.strftime('%Y%m%d') params = {'dateFrom': date_from, 'dateTo': date_to} data = self._session.query(url, method='POST', extra_params=params).get('data') # get all cameras to append to create ArloVideo object all_cameras = self._session.cameras for video in data: # pylint: disable=cell-var-from-loop srccam = \ list(filter( lambda cam: cam.device_id == video.get('deviceId'), all_cameras) )[0] # make sure only_cameras is a list if only_cameras and \ not isinstance(only_cameras, list): only_cameras = [(only_cameras)] # filter by camera only if only_cameras: if list(filter(lambda cam: cam.device_id == srccam.device_id, list(only_cameras))): videos.append(ArloVideo(video, srccam, self._session)) else: videos.append(ArloVideo(video, srccam, self._session)) if limit: return videos[:limit] return videos
python
def load(self, days=PRELOAD_DAYS, only_cameras=None, date_from=None, date_to=None, limit=None): """Load Arlo videos from the given criteria :param days: number of days to retrieve :param only_cameras: retrieve only <ArloCamera> on that list :param date_from: refine from initial date :param date_to: refine final date :param limit: define number of objects to return """ videos = [] url = LIBRARY_ENDPOINT if not (date_from and date_to): now = datetime.today() date_from = (now - timedelta(days=days)).strftime('%Y%m%d') date_to = now.strftime('%Y%m%d') params = {'dateFrom': date_from, 'dateTo': date_to} data = self._session.query(url, method='POST', extra_params=params).get('data') # get all cameras to append to create ArloVideo object all_cameras = self._session.cameras for video in data: # pylint: disable=cell-var-from-loop srccam = \ list(filter( lambda cam: cam.device_id == video.get('deviceId'), all_cameras) )[0] # make sure only_cameras is a list if only_cameras and \ not isinstance(only_cameras, list): only_cameras = [(only_cameras)] # filter by camera only if only_cameras: if list(filter(lambda cam: cam.device_id == srccam.device_id, list(only_cameras))): videos.append(ArloVideo(video, srccam, self._session)) else: videos.append(ArloVideo(video, srccam, self._session)) if limit: return videos[:limit] return videos
[ "def", "load", "(", "self", ",", "days", "=", "PRELOAD_DAYS", ",", "only_cameras", "=", "None", ",", "date_from", "=", "None", ",", "date_to", "=", "None", ",", "limit", "=", "None", ")", ":", "videos", "=", "[", "]", "url", "=", "LIBRARY_ENDPOINT", "if", "not", "(", "date_from", "and", "date_to", ")", ":", "now", "=", "datetime", ".", "today", "(", ")", "date_from", "=", "(", "now", "-", "timedelta", "(", "days", "=", "days", ")", ")", ".", "strftime", "(", "'%Y%m%d'", ")", "date_to", "=", "now", ".", "strftime", "(", "'%Y%m%d'", ")", "params", "=", "{", "'dateFrom'", ":", "date_from", ",", "'dateTo'", ":", "date_to", "}", "data", "=", "self", ".", "_session", ".", "query", "(", "url", ",", "method", "=", "'POST'", ",", "extra_params", "=", "params", ")", ".", "get", "(", "'data'", ")", "# get all cameras to append to create ArloVideo object", "all_cameras", "=", "self", ".", "_session", ".", "cameras", "for", "video", "in", "data", ":", "# pylint: disable=cell-var-from-loop", "srccam", "=", "list", "(", "filter", "(", "lambda", "cam", ":", "cam", ".", "device_id", "==", "video", ".", "get", "(", "'deviceId'", ")", ",", "all_cameras", ")", ")", "[", "0", "]", "# make sure only_cameras is a list", "if", "only_cameras", "and", "not", "isinstance", "(", "only_cameras", ",", "list", ")", ":", "only_cameras", "=", "[", "(", "only_cameras", ")", "]", "# filter by camera only", "if", "only_cameras", ":", "if", "list", "(", "filter", "(", "lambda", "cam", ":", "cam", ".", "device_id", "==", "srccam", ".", "device_id", ",", "list", "(", "only_cameras", ")", ")", ")", ":", "videos", ".", "append", "(", "ArloVideo", "(", "video", ",", "srccam", ",", "self", ".", "_session", ")", ")", "else", ":", "videos", ".", "append", "(", "ArloVideo", "(", "video", ",", "srccam", ",", "self", ".", "_session", ")", ")", "if", "limit", ":", "return", "videos", "[", ":", "limit", "]", "return", "videos" ]
Load Arlo videos from the given criteria :param days: number of days to retrieve :param only_cameras: retrieve only <ArloCamera> on that list :param date_from: refine from initial date :param date_to: refine final date :param limit: define number of objects to return
[ "Load", "Arlo", "videos", "from", "the", "given", "criteria" ]
db70aeb81705309c56ad32bbab1094f6cd146524
https://github.com/tchellomello/python-arlo/blob/db70aeb81705309c56ad32bbab1094f6cd146524/pyarlo/media.py#L38-L87
7,104
tchellomello/python-arlo
pyarlo/media.py
ArloVideo._name
def _name(self): """Define object name.""" return "{0} {1} {2}".format( self._camera.name, pretty_timestamp(self.created_at), self._attrs.get('mediaDuration'))
python
def _name(self): """Define object name.""" return "{0} {1} {2}".format( self._camera.name, pretty_timestamp(self.created_at), self._attrs.get('mediaDuration'))
[ "def", "_name", "(", "self", ")", ":", "return", "\"{0} {1} {2}\"", ".", "format", "(", "self", ".", "_camera", ".", "name", ",", "pretty_timestamp", "(", "self", ".", "created_at", ")", ",", "self", ".", "_attrs", ".", "get", "(", "'mediaDuration'", ")", ")" ]
Define object name.
[ "Define", "object", "name", "." ]
db70aeb81705309c56ad32bbab1094f6cd146524
https://github.com/tchellomello/python-arlo/blob/db70aeb81705309c56ad32bbab1094f6cd146524/pyarlo/media.py#L110-L115
7,105
tchellomello/python-arlo
pyarlo/media.py
ArloVideo.created_at_pretty
def created_at_pretty(self, date_format=None): """Return pretty timestamp.""" if date_format: return pretty_timestamp(self.created_at, date_format=date_format) return pretty_timestamp(self.created_at)
python
def created_at_pretty(self, date_format=None): """Return pretty timestamp.""" if date_format: return pretty_timestamp(self.created_at, date_format=date_format) return pretty_timestamp(self.created_at)
[ "def", "created_at_pretty", "(", "self", ",", "date_format", "=", "None", ")", ":", "if", "date_format", ":", "return", "pretty_timestamp", "(", "self", ".", "created_at", ",", "date_format", "=", "date_format", ")", "return", "pretty_timestamp", "(", "self", ".", "created_at", ")" ]
Return pretty timestamp.
[ "Return", "pretty", "timestamp", "." ]
db70aeb81705309c56ad32bbab1094f6cd146524
https://github.com/tchellomello/python-arlo/blob/db70aeb81705309c56ad32bbab1094f6cd146524/pyarlo/media.py#L132-L136
7,106
tchellomello/python-arlo
pyarlo/media.py
ArloVideo.created_today
def created_today(self): """Return True if created today.""" if self.datetime.date() == datetime.today().date(): return True return False
python
def created_today(self): """Return True if created today.""" if self.datetime.date() == datetime.today().date(): return True return False
[ "def", "created_today", "(", "self", ")", ":", "if", "self", ".", "datetime", ".", "date", "(", ")", "==", "datetime", ".", "today", "(", ")", ".", "date", "(", ")", ":", "return", "True", "return", "False" ]
Return True if created today.
[ "Return", "True", "if", "created", "today", "." ]
db70aeb81705309c56ad32bbab1094f6cd146524
https://github.com/tchellomello/python-arlo/blob/db70aeb81705309c56ad32bbab1094f6cd146524/pyarlo/media.py#L139-L143
7,107
tchellomello/python-arlo
pyarlo/utils.py
to_datetime
def to_datetime(timestamp): """Return datetime object from timestamp.""" return dt.fromtimestamp(time.mktime( time.localtime(int(str(timestamp)[:10]))))
python
def to_datetime(timestamp): """Return datetime object from timestamp.""" return dt.fromtimestamp(time.mktime( time.localtime(int(str(timestamp)[:10]))))
[ "def", "to_datetime", "(", "timestamp", ")", ":", "return", "dt", ".", "fromtimestamp", "(", "time", ".", "mktime", "(", "time", ".", "localtime", "(", "int", "(", "str", "(", "timestamp", ")", "[", ":", "10", "]", ")", ")", ")", ")" ]
Return datetime object from timestamp.
[ "Return", "datetime", "object", "from", "timestamp", "." ]
db70aeb81705309c56ad32bbab1094f6cd146524
https://github.com/tchellomello/python-arlo/blob/db70aeb81705309c56ad32bbab1094f6cd146524/pyarlo/utils.py#L11-L14
7,108
tchellomello/python-arlo
pyarlo/utils.py
pretty_timestamp
def pretty_timestamp(timestamp, date_format='%a-%m_%d_%y:%H:%M:%S'): """Huminize timestamp.""" return time.strftime(date_format, time.localtime(int(str(timestamp)[:10])))
python
def pretty_timestamp(timestamp, date_format='%a-%m_%d_%y:%H:%M:%S'): """Huminize timestamp.""" return time.strftime(date_format, time.localtime(int(str(timestamp)[:10])))
[ "def", "pretty_timestamp", "(", "timestamp", ",", "date_format", "=", "'%a-%m_%d_%y:%H:%M:%S'", ")", ":", "return", "time", ".", "strftime", "(", "date_format", ",", "time", ".", "localtime", "(", "int", "(", "str", "(", "timestamp", ")", "[", ":", "10", "]", ")", ")", ")" ]
Huminize timestamp.
[ "Huminize", "timestamp", "." ]
db70aeb81705309c56ad32bbab1094f6cd146524
https://github.com/tchellomello/python-arlo/blob/db70aeb81705309c56ad32bbab1094f6cd146524/pyarlo/utils.py#L17-L20
7,109
tchellomello/python-arlo
pyarlo/utils.py
http_get
def http_get(url, filename=None): """Download HTTP data.""" try: ret = requests.get(url) except requests.exceptions.SSLError as error: _LOGGER.error(error) return False if ret.status_code != 200: return False if filename is None: return ret.content with open(filename, 'wb') as data: data.write(ret.content) return True
python
def http_get(url, filename=None): """Download HTTP data.""" try: ret = requests.get(url) except requests.exceptions.SSLError as error: _LOGGER.error(error) return False if ret.status_code != 200: return False if filename is None: return ret.content with open(filename, 'wb') as data: data.write(ret.content) return True
[ "def", "http_get", "(", "url", ",", "filename", "=", "None", ")", ":", "try", ":", "ret", "=", "requests", ".", "get", "(", "url", ")", "except", "requests", ".", "exceptions", ".", "SSLError", "as", "error", ":", "_LOGGER", ".", "error", "(", "error", ")", "return", "False", "if", "ret", ".", "status_code", "!=", "200", ":", "return", "False", "if", "filename", "is", "None", ":", "return", "ret", ".", "content", "with", "open", "(", "filename", ",", "'wb'", ")", "as", "data", ":", "data", ".", "write", "(", "ret", ".", "content", ")", "return", "True" ]
Download HTTP data.
[ "Download", "HTTP", "data", "." ]
db70aeb81705309c56ad32bbab1094f6cd146524
https://github.com/tchellomello/python-arlo/blob/db70aeb81705309c56ad32bbab1094f6cd146524/pyarlo/utils.py#L23-L39
7,110
tchellomello/python-arlo
pyarlo/utils.py
http_stream
def http_stream(url, chunk=4096): """Generate stream for a given record video. :param chunk: chunk bytes to read per time :returns generator object """ ret = requests.get(url, stream=True) ret.raise_for_status() for data in ret.iter_content(chunk): yield data
python
def http_stream(url, chunk=4096): """Generate stream for a given record video. :param chunk: chunk bytes to read per time :returns generator object """ ret = requests.get(url, stream=True) ret.raise_for_status() for data in ret.iter_content(chunk): yield data
[ "def", "http_stream", "(", "url", ",", "chunk", "=", "4096", ")", ":", "ret", "=", "requests", ".", "get", "(", "url", ",", "stream", "=", "True", ")", "ret", ".", "raise_for_status", "(", ")", "for", "data", "in", "ret", ".", "iter_content", "(", "chunk", ")", ":", "yield", "data" ]
Generate stream for a given record video. :param chunk: chunk bytes to read per time :returns generator object
[ "Generate", "stream", "for", "a", "given", "record", "video", "." ]
db70aeb81705309c56ad32bbab1094f6cd146524
https://github.com/tchellomello/python-arlo/blob/db70aeb81705309c56ad32bbab1094f6cd146524/pyarlo/utils.py#L42-L51
7,111
tchellomello/python-arlo
pyarlo/camera.py
ArloCamera.unseen_videos_reset
def unseen_videos_reset(self): """Reset the unseen videos counter.""" url = RESET_CAM_ENDPOINT.format(self.unique_id) ret = self._session.query(url).get('success') return ret
python
def unseen_videos_reset(self): """Reset the unseen videos counter.""" url = RESET_CAM_ENDPOINT.format(self.unique_id) ret = self._session.query(url).get('success') return ret
[ "def", "unseen_videos_reset", "(", "self", ")", ":", "url", "=", "RESET_CAM_ENDPOINT", ".", "format", "(", "self", ".", "unique_id", ")", "ret", "=", "self", ".", "_session", ".", "query", "(", "url", ")", ".", "get", "(", "'success'", ")", "return", "ret" ]
Reset the unseen videos counter.
[ "Reset", "the", "unseen", "videos", "counter", "." ]
db70aeb81705309c56ad32bbab1094f6cd146524
https://github.com/tchellomello/python-arlo/blob/db70aeb81705309c56ad32bbab1094f6cd146524/pyarlo/camera.py#L128-L132
7,112
tchellomello/python-arlo
pyarlo/camera.py
ArloCamera.make_video_cache
def make_video_cache(self, days=None): """Save videos on _cache_videos to avoid dups.""" if days is None: days = self._min_days_vdo_cache self._cached_videos = self.videos(days)
python
def make_video_cache(self, days=None): """Save videos on _cache_videos to avoid dups.""" if days is None: days = self._min_days_vdo_cache self._cached_videos = self.videos(days)
[ "def", "make_video_cache", "(", "self", ",", "days", "=", "None", ")", ":", "if", "days", "is", "None", ":", "days", "=", "self", ".", "_min_days_vdo_cache", "self", ".", "_cached_videos", "=", "self", ".", "videos", "(", "days", ")" ]
Save videos on _cache_videos to avoid dups.
[ "Save", "videos", "on", "_cache_videos", "to", "avoid", "dups", "." ]
db70aeb81705309c56ad32bbab1094f6cd146524
https://github.com/tchellomello/python-arlo/blob/db70aeb81705309c56ad32bbab1094f6cd146524/pyarlo/camera.py#L171-L175
7,113
tchellomello/python-arlo
pyarlo/camera.py
ArloCamera.base_station
def base_station(self): """Return the base_station assigned for the given camera.""" try: return list(filter(lambda x: x.device_id == self.parent_id, self._session.base_stations))[0] except (IndexError, AttributeError): return None
python
def base_station(self): """Return the base_station assigned for the given camera.""" try: return list(filter(lambda x: x.device_id == self.parent_id, self._session.base_stations))[0] except (IndexError, AttributeError): return None
[ "def", "base_station", "(", "self", ")", ":", "try", ":", "return", "list", "(", "filter", "(", "lambda", "x", ":", "x", ".", "device_id", "==", "self", ".", "parent_id", ",", "self", ".", "_session", ".", "base_stations", ")", ")", "[", "0", "]", "except", "(", "IndexError", ",", "AttributeError", ")", ":", "return", "None" ]
Return the base_station assigned for the given camera.
[ "Return", "the", "base_station", "assigned", "for", "the", "given", "camera", "." ]
db70aeb81705309c56ad32bbab1094f6cd146524
https://github.com/tchellomello/python-arlo/blob/db70aeb81705309c56ad32bbab1094f6cd146524/pyarlo/camera.py#L216-L222
7,114
tchellomello/python-arlo
pyarlo/camera.py
ArloCamera._get_camera_properties
def _get_camera_properties(self): """Lookup camera properties from base station.""" if self.base_station and self.base_station.camera_properties: for cam in self.base_station.camera_properties: if cam["serialNumber"] == self.device_id: return cam return None
python
def _get_camera_properties(self): """Lookup camera properties from base station.""" if self.base_station and self.base_station.camera_properties: for cam in self.base_station.camera_properties: if cam["serialNumber"] == self.device_id: return cam return None
[ "def", "_get_camera_properties", "(", "self", ")", ":", "if", "self", ".", "base_station", "and", "self", ".", "base_station", ".", "camera_properties", ":", "for", "cam", "in", "self", ".", "base_station", ".", "camera_properties", ":", "if", "cam", "[", "\"serialNumber\"", "]", "==", "self", ".", "device_id", ":", "return", "cam", "return", "None" ]
Lookup camera properties from base station.
[ "Lookup", "camera", "properties", "from", "base", "station", "." ]
db70aeb81705309c56ad32bbab1094f6cd146524
https://github.com/tchellomello/python-arlo/blob/db70aeb81705309c56ad32bbab1094f6cd146524/pyarlo/camera.py#L224-L230
7,115
tchellomello/python-arlo
pyarlo/camera.py
ArloCamera.triggers
def triggers(self): """Get a camera's triggers.""" capabilities = self.capabilities if not capabilities: return None for capability in capabilities: if not isinstance(capability, dict): continue triggers = capability.get("Triggers") if triggers: return triggers return None
python
def triggers(self): """Get a camera's triggers.""" capabilities = self.capabilities if not capabilities: return None for capability in capabilities: if not isinstance(capability, dict): continue triggers = capability.get("Triggers") if triggers: return triggers return None
[ "def", "triggers", "(", "self", ")", ":", "capabilities", "=", "self", ".", "capabilities", "if", "not", "capabilities", ":", "return", "None", "for", "capability", "in", "capabilities", ":", "if", "not", "isinstance", "(", "capability", ",", "dict", ")", ":", "continue", "triggers", "=", "capability", ".", "get", "(", "\"Triggers\"", ")", "if", "triggers", ":", "return", "triggers", "return", "None" ]
Get a camera's triggers.
[ "Get", "a", "camera", "s", "triggers", "." ]
db70aeb81705309c56ad32bbab1094f6cd146524
https://github.com/tchellomello/python-arlo/blob/db70aeb81705309c56ad32bbab1094f6cd146524/pyarlo/camera.py#L244-L258
7,116
tchellomello/python-arlo
pyarlo/camera.py
ArloCamera.motion_detection_sensitivity
def motion_detection_sensitivity(self): """Sensitivity level of Camera motion detection.""" if not self.triggers: return None for trigger in self.triggers: if trigger.get("type") != "pirMotionActive": continue sensitivity = trigger.get("sensitivity") if sensitivity: return sensitivity.get("default") return None
python
def motion_detection_sensitivity(self): """Sensitivity level of Camera motion detection.""" if not self.triggers: return None for trigger in self.triggers: if trigger.get("type") != "pirMotionActive": continue sensitivity = trigger.get("sensitivity") if sensitivity: return sensitivity.get("default") return None
[ "def", "motion_detection_sensitivity", "(", "self", ")", ":", "if", "not", "self", ".", "triggers", ":", "return", "None", "for", "trigger", "in", "self", ".", "triggers", ":", "if", "trigger", ".", "get", "(", "\"type\"", ")", "!=", "\"pirMotionActive\"", ":", "continue", "sensitivity", "=", "trigger", ".", "get", "(", "\"sensitivity\"", ")", "if", "sensitivity", ":", "return", "sensitivity", ".", "get", "(", "\"default\"", ")", "return", "None" ]
Sensitivity level of Camera motion detection.
[ "Sensitivity", "level", "of", "Camera", "motion", "detection", "." ]
db70aeb81705309c56ad32bbab1094f6cd146524
https://github.com/tchellomello/python-arlo/blob/db70aeb81705309c56ad32bbab1094f6cd146524/pyarlo/camera.py#L304-L317
7,117
tchellomello/python-arlo
pyarlo/camera.py
ArloCamera.audio_detection_sensitivity
def audio_detection_sensitivity(self): """Sensitivity level of Camera audio detection.""" if not self.triggers: return None for trigger in self.triggers: if trigger.get("type") != "audioAmplitude": continue sensitivity = trigger.get("sensitivity") if sensitivity: return sensitivity.get("default") return None
python
def audio_detection_sensitivity(self): """Sensitivity level of Camera audio detection.""" if not self.triggers: return None for trigger in self.triggers: if trigger.get("type") != "audioAmplitude": continue sensitivity = trigger.get("sensitivity") if sensitivity: return sensitivity.get("default") return None
[ "def", "audio_detection_sensitivity", "(", "self", ")", ":", "if", "not", "self", ".", "triggers", ":", "return", "None", "for", "trigger", "in", "self", ".", "triggers", ":", "if", "trigger", ".", "get", "(", "\"type\"", ")", "!=", "\"audioAmplitude\"", ":", "continue", "sensitivity", "=", "trigger", ".", "get", "(", "\"sensitivity\"", ")", "if", "sensitivity", ":", "return", "sensitivity", ".", "get", "(", "\"default\"", ")", "return", "None" ]
Sensitivity level of Camera audio detection.
[ "Sensitivity", "level", "of", "Camera", "audio", "detection", "." ]
db70aeb81705309c56ad32bbab1094f6cd146524
https://github.com/tchellomello/python-arlo/blob/db70aeb81705309c56ad32bbab1094f6cd146524/pyarlo/camera.py#L320-L333
7,118
tchellomello/python-arlo
pyarlo/camera.py
ArloCamera.live_streaming
def live_streaming(self): """Return live streaming generator.""" url = STREAM_ENDPOINT # override params params = STREAMING_BODY params['from'] = "{0}_web".format(self.user_id) params['to'] = self.device_id params['resource'] = "cameras/{0}".format(self.device_id) params['transId'] = "web!{0}".format(self.xcloud_id) # override headers headers = {'xCloudId': self.xcloud_id} _LOGGER.debug("Streaming device %s", self.name) _LOGGER.debug("Device params %s", params) _LOGGER.debug("Device headers %s", headers) ret = self._session.query(url, method='POST', extra_params=params, extra_headers=headers) _LOGGER.debug("Streaming results %s", ret) if ret.get('success'): return ret.get('data').get('url') return ret.get('data')
python
def live_streaming(self): """Return live streaming generator.""" url = STREAM_ENDPOINT # override params params = STREAMING_BODY params['from'] = "{0}_web".format(self.user_id) params['to'] = self.device_id params['resource'] = "cameras/{0}".format(self.device_id) params['transId'] = "web!{0}".format(self.xcloud_id) # override headers headers = {'xCloudId': self.xcloud_id} _LOGGER.debug("Streaming device %s", self.name) _LOGGER.debug("Device params %s", params) _LOGGER.debug("Device headers %s", headers) ret = self._session.query(url, method='POST', extra_params=params, extra_headers=headers) _LOGGER.debug("Streaming results %s", ret) if ret.get('success'): return ret.get('data').get('url') return ret.get('data')
[ "def", "live_streaming", "(", "self", ")", ":", "url", "=", "STREAM_ENDPOINT", "# override params", "params", "=", "STREAMING_BODY", "params", "[", "'from'", "]", "=", "\"{0}_web\"", ".", "format", "(", "self", ".", "user_id", ")", "params", "[", "'to'", "]", "=", "self", ".", "device_id", "params", "[", "'resource'", "]", "=", "\"cameras/{0}\"", ".", "format", "(", "self", ".", "device_id", ")", "params", "[", "'transId'", "]", "=", "\"web!{0}\"", ".", "format", "(", "self", ".", "xcloud_id", ")", "# override headers", "headers", "=", "{", "'xCloudId'", ":", "self", ".", "xcloud_id", "}", "_LOGGER", ".", "debug", "(", "\"Streaming device %s\"", ",", "self", ".", "name", ")", "_LOGGER", ".", "debug", "(", "\"Device params %s\"", ",", "params", ")", "_LOGGER", ".", "debug", "(", "\"Device headers %s\"", ",", "headers", ")", "ret", "=", "self", ".", "_session", ".", "query", "(", "url", ",", "method", "=", "'POST'", ",", "extra_params", "=", "params", ",", "extra_headers", "=", "headers", ")", "_LOGGER", ".", "debug", "(", "\"Streaming results %s\"", ",", "ret", ")", "if", "ret", ".", "get", "(", "'success'", ")", ":", "return", "ret", ".", "get", "(", "'data'", ")", ".", "get", "(", "'url'", ")", "return", "ret", ".", "get", "(", "'data'", ")" ]
Return live streaming generator.
[ "Return", "live", "streaming", "generator", "." ]
db70aeb81705309c56ad32bbab1094f6cd146524
https://github.com/tchellomello/python-arlo/blob/db70aeb81705309c56ad32bbab1094f6cd146524/pyarlo/camera.py#L335-L361
7,119
tchellomello/python-arlo
pyarlo/camera.py
ArloCamera.schedule_snapshot
def schedule_snapshot(self): """Trigger snapshot to be uploaded to AWS. Return success state.""" # Notes: # - Snapshots are not immediate. # - Snapshots will be cached for predefined amount # of time. # - Snapshots are not balanced. To get a better # image, it must be taken from the stream, a few # seconds after stream start. url = SNAPSHOTS_ENDPOINT params = SNAPSHOTS_BODY params['from'] = "{0}_web".format(self.user_id) params['to'] = self.device_id params['resource'] = "cameras/{0}".format(self.device_id) params['transId'] = "web!{0}".format(self.xcloud_id) # override headers headers = {'xCloudId': self.xcloud_id} _LOGGER.debug("Snapshot device %s", self.name) _LOGGER.debug("Device params %s", params) _LOGGER.debug("Device headers %s", headers) ret = self._session.query(url, method='POST', extra_params=params, extra_headers=headers) _LOGGER.debug("Snapshot results %s", ret) return ret is not None and ret.get('success')
python
def schedule_snapshot(self): """Trigger snapshot to be uploaded to AWS. Return success state.""" # Notes: # - Snapshots are not immediate. # - Snapshots will be cached for predefined amount # of time. # - Snapshots are not balanced. To get a better # image, it must be taken from the stream, a few # seconds after stream start. url = SNAPSHOTS_ENDPOINT params = SNAPSHOTS_BODY params['from'] = "{0}_web".format(self.user_id) params['to'] = self.device_id params['resource'] = "cameras/{0}".format(self.device_id) params['transId'] = "web!{0}".format(self.xcloud_id) # override headers headers = {'xCloudId': self.xcloud_id} _LOGGER.debug("Snapshot device %s", self.name) _LOGGER.debug("Device params %s", params) _LOGGER.debug("Device headers %s", headers) ret = self._session.query(url, method='POST', extra_params=params, extra_headers=headers) _LOGGER.debug("Snapshot results %s", ret) return ret is not None and ret.get('success')
[ "def", "schedule_snapshot", "(", "self", ")", ":", "# Notes:", "# - Snapshots are not immediate.", "# - Snapshots will be cached for predefined amount", "# of time.", "# - Snapshots are not balanced. To get a better", "# image, it must be taken from the stream, a few", "# seconds after stream start.", "url", "=", "SNAPSHOTS_ENDPOINT", "params", "=", "SNAPSHOTS_BODY", "params", "[", "'from'", "]", "=", "\"{0}_web\"", ".", "format", "(", "self", ".", "user_id", ")", "params", "[", "'to'", "]", "=", "self", ".", "device_id", "params", "[", "'resource'", "]", "=", "\"cameras/{0}\"", ".", "format", "(", "self", ".", "device_id", ")", "params", "[", "'transId'", "]", "=", "\"web!{0}\"", ".", "format", "(", "self", ".", "xcloud_id", ")", "# override headers", "headers", "=", "{", "'xCloudId'", ":", "self", ".", "xcloud_id", "}", "_LOGGER", ".", "debug", "(", "\"Snapshot device %s\"", ",", "self", ".", "name", ")", "_LOGGER", ".", "debug", "(", "\"Device params %s\"", ",", "params", ")", "_LOGGER", ".", "debug", "(", "\"Device headers %s\"", ",", "headers", ")", "ret", "=", "self", ".", "_session", ".", "query", "(", "url", ",", "method", "=", "'POST'", ",", "extra_params", "=", "params", ",", "extra_headers", "=", "headers", ")", "_LOGGER", ".", "debug", "(", "\"Snapshot results %s\"", ",", "ret", ")", "return", "ret", "is", "not", "None", "and", "ret", ".", "get", "(", "'success'", ")" ]
Trigger snapshot to be uploaded to AWS. Return success state.
[ "Trigger", "snapshot", "to", "be", "uploaded", "to", "AWS", ".", "Return", "success", "state", "." ]
db70aeb81705309c56ad32bbab1094f6cd146524
https://github.com/tchellomello/python-arlo/blob/db70aeb81705309c56ad32bbab1094f6cd146524/pyarlo/camera.py#L374-L405
7,120
tchellomello/python-arlo
pyarlo/base_station.py
ArloBaseStation.thread_function
def thread_function(self): """Thread function.""" self.__subscribed = True url = SUBSCRIBE_ENDPOINT + "?token=" + self._session_token data = self._session.query(url, method='GET', raw=True, stream=True) if not data or not data.ok: _LOGGER.debug("Did not receive a valid response. Aborting..") return None self.__sseclient = sseclient.SSEClient(data) try: for event in (self.__sseclient).events(): if not self.__subscribed: break data = json.loads(event.data) if data.get('status') == "connected": _LOGGER.debug("Successfully subscribed this base station") elif data.get('action'): action = data.get('action') resource = data.get('resource') if action == "logout": _LOGGER.debug("Logged out by some other entity") self.__subscribed = False break elif action == "is" and "subscriptions/" not in resource: self.__events.append(data) self.__event_handle.set() except TypeError as error: _LOGGER.debug("Got unexpected error: %s", error) return None return True
python
def thread_function(self): """Thread function.""" self.__subscribed = True url = SUBSCRIBE_ENDPOINT + "?token=" + self._session_token data = self._session.query(url, method='GET', raw=True, stream=True) if not data or not data.ok: _LOGGER.debug("Did not receive a valid response. Aborting..") return None self.__sseclient = sseclient.SSEClient(data) try: for event in (self.__sseclient).events(): if not self.__subscribed: break data = json.loads(event.data) if data.get('status') == "connected": _LOGGER.debug("Successfully subscribed this base station") elif data.get('action'): action = data.get('action') resource = data.get('resource') if action == "logout": _LOGGER.debug("Logged out by some other entity") self.__subscribed = False break elif action == "is" and "subscriptions/" not in resource: self.__events.append(data) self.__event_handle.set() except TypeError as error: _LOGGER.debug("Got unexpected error: %s", error) return None return True
[ "def", "thread_function", "(", "self", ")", ":", "self", ".", "__subscribed", "=", "True", "url", "=", "SUBSCRIBE_ENDPOINT", "+", "\"?token=\"", "+", "self", ".", "_session_token", "data", "=", "self", ".", "_session", ".", "query", "(", "url", ",", "method", "=", "'GET'", ",", "raw", "=", "True", ",", "stream", "=", "True", ")", "if", "not", "data", "or", "not", "data", ".", "ok", ":", "_LOGGER", ".", "debug", "(", "\"Did not receive a valid response. Aborting..\"", ")", "return", "None", "self", ".", "__sseclient", "=", "sseclient", ".", "SSEClient", "(", "data", ")", "try", ":", "for", "event", "in", "(", "self", ".", "__sseclient", ")", ".", "events", "(", ")", ":", "if", "not", "self", ".", "__subscribed", ":", "break", "data", "=", "json", ".", "loads", "(", "event", ".", "data", ")", "if", "data", ".", "get", "(", "'status'", ")", "==", "\"connected\"", ":", "_LOGGER", ".", "debug", "(", "\"Successfully subscribed this base station\"", ")", "elif", "data", ".", "get", "(", "'action'", ")", ":", "action", "=", "data", ".", "get", "(", "'action'", ")", "resource", "=", "data", ".", "get", "(", "'resource'", ")", "if", "action", "==", "\"logout\"", ":", "_LOGGER", ".", "debug", "(", "\"Logged out by some other entity\"", ")", "self", ".", "__subscribed", "=", "False", "break", "elif", "action", "==", "\"is\"", "and", "\"subscriptions/\"", "not", "in", "resource", ":", "self", ".", "__events", ".", "append", "(", "data", ")", "self", ".", "__event_handle", ".", "set", "(", ")", "except", "TypeError", "as", "error", ":", "_LOGGER", ".", "debug", "(", "\"Got unexpected error: %s\"", ",", "error", ")", "return", "None", "return", "True" ]
Thread function.
[ "Thread", "function", "." ]
db70aeb81705309c56ad32bbab1094f6cd146524
https://github.com/tchellomello/python-arlo/blob/db70aeb81705309c56ad32bbab1094f6cd146524/pyarlo/base_station.py#L55-L90
7,121
tchellomello/python-arlo
pyarlo/base_station.py
ArloBaseStation._get_event_stream
def _get_event_stream(self): """Spawn a thread and monitor the Arlo Event Stream.""" self.__event_handle = threading.Event() event_thread = threading.Thread(target=self.thread_function) event_thread.start()
python
def _get_event_stream(self): """Spawn a thread and monitor the Arlo Event Stream.""" self.__event_handle = threading.Event() event_thread = threading.Thread(target=self.thread_function) event_thread.start()
[ "def", "_get_event_stream", "(", "self", ")", ":", "self", ".", "__event_handle", "=", "threading", ".", "Event", "(", ")", "event_thread", "=", "threading", ".", "Thread", "(", "target", "=", "self", ".", "thread_function", ")", "event_thread", ".", "start", "(", ")" ]
Spawn a thread and monitor the Arlo Event Stream.
[ "Spawn", "a", "thread", "and", "monitor", "the", "Arlo", "Event", "Stream", "." ]
db70aeb81705309c56ad32bbab1094f6cd146524
https://github.com/tchellomello/python-arlo/blob/db70aeb81705309c56ad32bbab1094f6cd146524/pyarlo/base_station.py#L92-L96
7,122
tchellomello/python-arlo
pyarlo/base_station.py
ArloBaseStation._unsubscribe_myself
def _unsubscribe_myself(self): """Unsubscribe this base station for all events.""" url = UNSUBSCRIBE_ENDPOINT return self._session.query(url, method='GET', raw=True, stream=False)
python
def _unsubscribe_myself(self): """Unsubscribe this base station for all events.""" url = UNSUBSCRIBE_ENDPOINT return self._session.query(url, method='GET', raw=True, stream=False)
[ "def", "_unsubscribe_myself", "(", "self", ")", ":", "url", "=", "UNSUBSCRIBE_ENDPOINT", "return", "self", ".", "_session", ".", "query", "(", "url", ",", "method", "=", "'GET'", ",", "raw", "=", "True", ",", "stream", "=", "False", ")" ]
Unsubscribe this base station for all events.
[ "Unsubscribe", "this", "base", "station", "for", "all", "events", "." ]
db70aeb81705309c56ad32bbab1094f6cd146524
https://github.com/tchellomello/python-arlo/blob/db70aeb81705309c56ad32bbab1094f6cd146524/pyarlo/base_station.py#L106-L109
7,123
tchellomello/python-arlo
pyarlo/base_station.py
ArloBaseStation._close_event_stream
def _close_event_stream(self): """Stop the Event stream thread.""" self.__subscribed = False del self.__events[:] self.__event_handle.clear()
python
def _close_event_stream(self): """Stop the Event stream thread.""" self.__subscribed = False del self.__events[:] self.__event_handle.clear()
[ "def", "_close_event_stream", "(", "self", ")", ":", "self", ".", "__subscribed", "=", "False", "del", "self", ".", "__events", "[", ":", "]", "self", ".", "__event_handle", ".", "clear", "(", ")" ]
Stop the Event stream thread.
[ "Stop", "the", "Event", "stream", "thread", "." ]
db70aeb81705309c56ad32bbab1094f6cd146524
https://github.com/tchellomello/python-arlo/blob/db70aeb81705309c56ad32bbab1094f6cd146524/pyarlo/base_station.py#L111-L115
7,124
tchellomello/python-arlo
pyarlo/base_station.py
ArloBaseStation.publish_and_get_event
def publish_and_get_event(self, resource): """Publish and get the event from base station.""" l_subscribed = False this_event = None if not self.__subscribed: self._get_event_stream() self._subscribe_myself() l_subscribed = True status = self.publish( action='get', resource=resource, mode=None, publish_response=False) if status == 'success': i = 0 while not this_event and i < 2: self.__event_handle.wait(5.0) self.__event_handle.clear() _LOGGER.debug("Instance %s resource: %s", str(i), resource) for event in self.__events: if event['resource'] == resource: this_event = event self.__events.remove(event) break i = i + 1 if l_subscribed: self._unsubscribe_myself() self._close_event_stream() l_subscribed = False return this_event
python
def publish_and_get_event(self, resource): """Publish and get the event from base station.""" l_subscribed = False this_event = None if not self.__subscribed: self._get_event_stream() self._subscribe_myself() l_subscribed = True status = self.publish( action='get', resource=resource, mode=None, publish_response=False) if status == 'success': i = 0 while not this_event and i < 2: self.__event_handle.wait(5.0) self.__event_handle.clear() _LOGGER.debug("Instance %s resource: %s", str(i), resource) for event in self.__events: if event['resource'] == resource: this_event = event self.__events.remove(event) break i = i + 1 if l_subscribed: self._unsubscribe_myself() self._close_event_stream() l_subscribed = False return this_event
[ "def", "publish_and_get_event", "(", "self", ",", "resource", ")", ":", "l_subscribed", "=", "False", "this_event", "=", "None", "if", "not", "self", ".", "__subscribed", ":", "self", ".", "_get_event_stream", "(", ")", "self", ".", "_subscribe_myself", "(", ")", "l_subscribed", "=", "True", "status", "=", "self", ".", "publish", "(", "action", "=", "'get'", ",", "resource", "=", "resource", ",", "mode", "=", "None", ",", "publish_response", "=", "False", ")", "if", "status", "==", "'success'", ":", "i", "=", "0", "while", "not", "this_event", "and", "i", "<", "2", ":", "self", ".", "__event_handle", ".", "wait", "(", "5.0", ")", "self", ".", "__event_handle", ".", "clear", "(", ")", "_LOGGER", ".", "debug", "(", "\"Instance %s resource: %s\"", ",", "str", "(", "i", ")", ",", "resource", ")", "for", "event", "in", "self", ".", "__events", ":", "if", "event", "[", "'resource'", "]", "==", "resource", ":", "this_event", "=", "event", "self", ".", "__events", ".", "remove", "(", "event", ")", "break", "i", "=", "i", "+", "1", "if", "l_subscribed", ":", "self", ".", "_unsubscribe_myself", "(", ")", "self", ".", "_close_event_stream", "(", ")", "l_subscribed", "=", "False", "return", "this_event" ]
Publish and get the event from base station.
[ "Publish", "and", "get", "the", "event", "from", "base", "station", "." ]
db70aeb81705309c56ad32bbab1094f6cd146524
https://github.com/tchellomello/python-arlo/blob/db70aeb81705309c56ad32bbab1094f6cd146524/pyarlo/base_station.py#L117-L151
7,125
tchellomello/python-arlo
pyarlo/base_station.py
ArloBaseStation.publish
def publish( self, action='get', resource=None, camera_id=None, mode=None, publish_response=None, properties=None): """Run action. :param method: Specify the method GET, POST or PUT. Default is GET. :param resource: Specify one of the resources to fetch from arlo. :param camera_id: Specify the camera ID involved with this action :param mode: Specify the mode to set, else None for GET operations :param publish_response: Set to True for SETs. Default False """ url = NOTIFY_ENDPOINT.format(self.device_id) body = ACTION_BODY.copy() if properties is None: properties = {} if resource: body['resource'] = resource if action == 'get': body['properties'] = None else: # consider moving this logic up a layer if resource == 'schedule': properties.update({'active': True}) elif resource == 'subscribe': body['resource'] = "subscriptions/" + \ "{0}_web".format(self.user_id) dev = [] dev.append(self.device_id) properties.update({'devices': dev}) elif resource == 'modes': available_modes = self.available_modes_with_ids properties.update({'active': available_modes.get(mode)}) elif resource == 'privacy': properties.update({'privacyActive': not mode}) body['resource'] = "cameras/{0}".format(camera_id) body['action'] = action body['properties'] = properties body['publishResponse'] = publish_response body['from'] = "{0}_web".format(self.user_id) body['to'] = self.device_id body['transId'] = "web!{0}".format(self.xcloud_id) _LOGGER.debug("Action body: %s", body) ret = \ self._session.query(url, method='POST', extra_params=body, extra_headers={"xCloudId": self.xcloud_id}) if ret and ret.get('success'): return 'success' return None
python
def publish( self, action='get', resource=None, camera_id=None, mode=None, publish_response=None, properties=None): """Run action. :param method: Specify the method GET, POST or PUT. Default is GET. :param resource: Specify one of the resources to fetch from arlo. :param camera_id: Specify the camera ID involved with this action :param mode: Specify the mode to set, else None for GET operations :param publish_response: Set to True for SETs. Default False """ url = NOTIFY_ENDPOINT.format(self.device_id) body = ACTION_BODY.copy() if properties is None: properties = {} if resource: body['resource'] = resource if action == 'get': body['properties'] = None else: # consider moving this logic up a layer if resource == 'schedule': properties.update({'active': True}) elif resource == 'subscribe': body['resource'] = "subscriptions/" + \ "{0}_web".format(self.user_id) dev = [] dev.append(self.device_id) properties.update({'devices': dev}) elif resource == 'modes': available_modes = self.available_modes_with_ids properties.update({'active': available_modes.get(mode)}) elif resource == 'privacy': properties.update({'privacyActive': not mode}) body['resource'] = "cameras/{0}".format(camera_id) body['action'] = action body['properties'] = properties body['publishResponse'] = publish_response body['from'] = "{0}_web".format(self.user_id) body['to'] = self.device_id body['transId'] = "web!{0}".format(self.xcloud_id) _LOGGER.debug("Action body: %s", body) ret = \ self._session.query(url, method='POST', extra_params=body, extra_headers={"xCloudId": self.xcloud_id}) if ret and ret.get('success'): return 'success' return None
[ "def", "publish", "(", "self", ",", "action", "=", "'get'", ",", "resource", "=", "None", ",", "camera_id", "=", "None", ",", "mode", "=", "None", ",", "publish_response", "=", "None", ",", "properties", "=", "None", ")", ":", "url", "=", "NOTIFY_ENDPOINT", ".", "format", "(", "self", ".", "device_id", ")", "body", "=", "ACTION_BODY", ".", "copy", "(", ")", "if", "properties", "is", "None", ":", "properties", "=", "{", "}", "if", "resource", ":", "body", "[", "'resource'", "]", "=", "resource", "if", "action", "==", "'get'", ":", "body", "[", "'properties'", "]", "=", "None", "else", ":", "# consider moving this logic up a layer", "if", "resource", "==", "'schedule'", ":", "properties", ".", "update", "(", "{", "'active'", ":", "True", "}", ")", "elif", "resource", "==", "'subscribe'", ":", "body", "[", "'resource'", "]", "=", "\"subscriptions/\"", "+", "\"{0}_web\"", ".", "format", "(", "self", ".", "user_id", ")", "dev", "=", "[", "]", "dev", ".", "append", "(", "self", ".", "device_id", ")", "properties", ".", "update", "(", "{", "'devices'", ":", "dev", "}", ")", "elif", "resource", "==", "'modes'", ":", "available_modes", "=", "self", ".", "available_modes_with_ids", "properties", ".", "update", "(", "{", "'active'", ":", "available_modes", ".", "get", "(", "mode", ")", "}", ")", "elif", "resource", "==", "'privacy'", ":", "properties", ".", "update", "(", "{", "'privacyActive'", ":", "not", "mode", "}", ")", "body", "[", "'resource'", "]", "=", "\"cameras/{0}\"", ".", "format", "(", "camera_id", ")", "body", "[", "'action'", "]", "=", "action", "body", "[", "'properties'", "]", "=", "properties", "body", "[", "'publishResponse'", "]", "=", "publish_response", "body", "[", "'from'", "]", "=", "\"{0}_web\"", ".", "format", "(", "self", ".", "user_id", ")", "body", "[", "'to'", "]", "=", "self", ".", "device_id", "body", "[", "'transId'", "]", "=", "\"web!{0}\"", ".", "format", "(", "self", ".", "xcloud_id", ")", "_LOGGER", ".", "debug", "(", "\"Action body: %s\"", ",", "body", ")", "ret", "=", "self", ".", "_session", ".", "query", "(", "url", ",", "method", "=", "'POST'", ",", "extra_params", "=", "body", ",", "extra_headers", "=", "{", "\"xCloudId\"", ":", "self", ".", "xcloud_id", "}", ")", "if", "ret", "and", "ret", ".", "get", "(", "'success'", ")", ":", "return", "'success'", "return", "None" ]
Run action. :param method: Specify the method GET, POST or PUT. Default is GET. :param resource: Specify one of the resources to fetch from arlo. :param camera_id: Specify the camera ID involved with this action :param mode: Specify the mode to set, else None for GET operations :param publish_response: Set to True for SETs. Default False
[ "Run", "action", "." ]
db70aeb81705309c56ad32bbab1094f6cd146524
https://github.com/tchellomello/python-arlo/blob/db70aeb81705309c56ad32bbab1094f6cd146524/pyarlo/base_station.py#L153-L215
7,126
tchellomello/python-arlo
pyarlo/base_station.py
ArloBaseStation.refresh_rate
def refresh_rate(self, value): """Override the refresh_rate attribute.""" if isinstance(value, (int, float)): self._refresh_rate = value
python
def refresh_rate(self, value): """Override the refresh_rate attribute.""" if isinstance(value, (int, float)): self._refresh_rate = value
[ "def", "refresh_rate", "(", "self", ",", "value", ")", ":", "if", "isinstance", "(", "value", ",", "(", "int", ",", "float", ")", ")", ":", "self", ".", "_refresh_rate", "=", "value" ]
Override the refresh_rate attribute.
[ "Override", "the", "refresh_rate", "attribute", "." ]
db70aeb81705309c56ad32bbab1094f6cd146524
https://github.com/tchellomello/python-arlo/blob/db70aeb81705309c56ad32bbab1094f6cd146524/pyarlo/base_station.py#L299-L302
7,127
tchellomello/python-arlo
pyarlo/base_station.py
ArloBaseStation.available_modes
def available_modes(self): """Return list of available mode names.""" if not self._available_modes: modes = self.available_modes_with_ids if not modes: return None self._available_modes = list(modes.keys()) return self._available_modes
python
def available_modes(self): """Return list of available mode names.""" if not self._available_modes: modes = self.available_modes_with_ids if not modes: return None self._available_modes = list(modes.keys()) return self._available_modes
[ "def", "available_modes", "(", "self", ")", ":", "if", "not", "self", ".", "_available_modes", ":", "modes", "=", "self", ".", "available_modes_with_ids", "if", "not", "modes", ":", "return", "None", "self", ".", "_available_modes", "=", "list", "(", "modes", ".", "keys", "(", ")", ")", "return", "self", ".", "_available_modes" ]
Return list of available mode names.
[ "Return", "list", "of", "available", "mode", "names", "." ]
db70aeb81705309c56ad32bbab1094f6cd146524
https://github.com/tchellomello/python-arlo/blob/db70aeb81705309c56ad32bbab1094f6cd146524/pyarlo/base_station.py#L305-L312
7,128
tchellomello/python-arlo
pyarlo/base_station.py
ArloBaseStation.available_modes_with_ids
def available_modes_with_ids(self): """Return list of objects containing available mode name and id.""" if not self._available_mode_ids: all_modes = FIXED_MODES.copy() self._available_mode_ids = all_modes modes = self.get_available_modes() try: if modes: # pylint: disable=consider-using-dict-comprehension simple_modes = dict( [(m.get("type", m.get("name")), m.get("id")) for m in modes] ) all_modes.update(simple_modes) self._available_mode_ids = all_modes except TypeError: _LOGGER.debug("Did not receive a valid response. Passing..") return self._available_mode_ids
python
def available_modes_with_ids(self): """Return list of objects containing available mode name and id.""" if not self._available_mode_ids: all_modes = FIXED_MODES.copy() self._available_mode_ids = all_modes modes = self.get_available_modes() try: if modes: # pylint: disable=consider-using-dict-comprehension simple_modes = dict( [(m.get("type", m.get("name")), m.get("id")) for m in modes] ) all_modes.update(simple_modes) self._available_mode_ids = all_modes except TypeError: _LOGGER.debug("Did not receive a valid response. Passing..") return self._available_mode_ids
[ "def", "available_modes_with_ids", "(", "self", ")", ":", "if", "not", "self", ".", "_available_mode_ids", ":", "all_modes", "=", "FIXED_MODES", ".", "copy", "(", ")", "self", ".", "_available_mode_ids", "=", "all_modes", "modes", "=", "self", ".", "get_available_modes", "(", ")", "try", ":", "if", "modes", ":", "# pylint: disable=consider-using-dict-comprehension", "simple_modes", "=", "dict", "(", "[", "(", "m", ".", "get", "(", "\"type\"", ",", "m", ".", "get", "(", "\"name\"", ")", ")", ",", "m", ".", "get", "(", "\"id\"", ")", ")", "for", "m", "in", "modes", "]", ")", "all_modes", ".", "update", "(", "simple_modes", ")", "self", ".", "_available_mode_ids", "=", "all_modes", "except", "TypeError", ":", "_LOGGER", ".", "debug", "(", "\"Did not receive a valid response. Passing..\"", ")", "return", "self", ".", "_available_mode_ids" ]
Return list of objects containing available mode name and id.
[ "Return", "list", "of", "objects", "containing", "available", "mode", "name", "and", "id", "." ]
db70aeb81705309c56ad32bbab1094f6cd146524
https://github.com/tchellomello/python-arlo/blob/db70aeb81705309c56ad32bbab1094f6cd146524/pyarlo/base_station.py#L315-L332
7,129
tchellomello/python-arlo
pyarlo/base_station.py
ArloBaseStation.mode
def mode(self): """Return current mode key.""" if self.is_in_schedule_mode: return "schedule" resource = "modes" mode_event = self.publish_and_get_event(resource) if mode_event: properties = mode_event.get('properties') active_mode = properties.get('active') modes = properties.get('modes') if not modes: return None for mode in modes: if mode.get('id') == active_mode: return mode.get('type') \ if mode.get('type') is not None else mode.get('name') return None
python
def mode(self): """Return current mode key.""" if self.is_in_schedule_mode: return "schedule" resource = "modes" mode_event = self.publish_and_get_event(resource) if mode_event: properties = mode_event.get('properties') active_mode = properties.get('active') modes = properties.get('modes') if not modes: return None for mode in modes: if mode.get('id') == active_mode: return mode.get('type') \ if mode.get('type') is not None else mode.get('name') return None
[ "def", "mode", "(", "self", ")", ":", "if", "self", ".", "is_in_schedule_mode", ":", "return", "\"schedule\"", "resource", "=", "\"modes\"", "mode_event", "=", "self", ".", "publish_and_get_event", "(", "resource", ")", "if", "mode_event", ":", "properties", "=", "mode_event", ".", "get", "(", "'properties'", ")", "active_mode", "=", "properties", ".", "get", "(", "'active'", ")", "modes", "=", "properties", ".", "get", "(", "'modes'", ")", "if", "not", "modes", ":", "return", "None", "for", "mode", "in", "modes", ":", "if", "mode", ".", "get", "(", "'id'", ")", "==", "active_mode", ":", "return", "mode", ".", "get", "(", "'type'", ")", "if", "mode", ".", "get", "(", "'type'", ")", "is", "not", "None", "else", "mode", ".", "get", "(", "'name'", ")", "return", "None" ]
Return current mode key.
[ "Return", "current", "mode", "key", "." ]
db70aeb81705309c56ad32bbab1094f6cd146524
https://github.com/tchellomello/python-arlo/blob/db70aeb81705309c56ad32bbab1094f6cd146524/pyarlo/base_station.py#L340-L359
7,130
tchellomello/python-arlo
pyarlo/base_station.py
ArloBaseStation.is_in_schedule_mode
def is_in_schedule_mode(self): """Returns True if base_station is currently on a scheduled mode.""" resource = "schedule" mode_event = self.publish_and_get_event(resource) if mode_event and mode_event.get("resource", None) == "schedule": properties = mode_event.get('properties') return properties.get("active", False) return False
python
def is_in_schedule_mode(self): """Returns True if base_station is currently on a scheduled mode.""" resource = "schedule" mode_event = self.publish_and_get_event(resource) if mode_event and mode_event.get("resource", None) == "schedule": properties = mode_event.get('properties') return properties.get("active", False) return False
[ "def", "is_in_schedule_mode", "(", "self", ")", ":", "resource", "=", "\"schedule\"", "mode_event", "=", "self", ".", "publish_and_get_event", "(", "resource", ")", "if", "mode_event", "and", "mode_event", ".", "get", "(", "\"resource\"", ",", "None", ")", "==", "\"schedule\"", ":", "properties", "=", "mode_event", ".", "get", "(", "'properties'", ")", "return", "properties", ".", "get", "(", "\"active\"", ",", "False", ")", "return", "False" ]
Returns True if base_station is currently on a scheduled mode.
[ "Returns", "True", "if", "base_station", "is", "currently", "on", "a", "scheduled", "mode", "." ]
db70aeb81705309c56ad32bbab1094f6cd146524
https://github.com/tchellomello/python-arlo/blob/db70aeb81705309c56ad32bbab1094f6cd146524/pyarlo/base_station.py#L362-L369
7,131
tchellomello/python-arlo
pyarlo/base_station.py
ArloBaseStation.get_available_modes
def get_available_modes(self): """Return a list of available mode objects for an Arlo user.""" resource = "modes" resource_event = self.publish_and_get_event(resource) if resource_event: properties = resource_event.get("properties") return properties.get("modes") return None
python
def get_available_modes(self): """Return a list of available mode objects for an Arlo user.""" resource = "modes" resource_event = self.publish_and_get_event(resource) if resource_event: properties = resource_event.get("properties") return properties.get("modes") return None
[ "def", "get_available_modes", "(", "self", ")", ":", "resource", "=", "\"modes\"", "resource_event", "=", "self", ".", "publish_and_get_event", "(", "resource", ")", "if", "resource_event", ":", "properties", "=", "resource_event", ".", "get", "(", "\"properties\"", ")", "return", "properties", ".", "get", "(", "\"modes\"", ")", "return", "None" ]
Return a list of available mode objects for an Arlo user.
[ "Return", "a", "list", "of", "available", "mode", "objects", "for", "an", "Arlo", "user", "." ]
db70aeb81705309c56ad32bbab1094f6cd146524
https://github.com/tchellomello/python-arlo/blob/db70aeb81705309c56ad32bbab1094f6cd146524/pyarlo/base_station.py#L371-L379
7,132
tchellomello/python-arlo
pyarlo/base_station.py
ArloBaseStation.get_cameras_properties
def get_cameras_properties(self): """Return camera properties.""" resource = "cameras" resource_event = self.publish_and_get_event(resource) if resource_event: self._last_refresh = int(time.time()) self._camera_properties = resource_event.get('properties')
python
def get_cameras_properties(self): """Return camera properties.""" resource = "cameras" resource_event = self.publish_and_get_event(resource) if resource_event: self._last_refresh = int(time.time()) self._camera_properties = resource_event.get('properties')
[ "def", "get_cameras_properties", "(", "self", ")", ":", "resource", "=", "\"cameras\"", "resource_event", "=", "self", ".", "publish_and_get_event", "(", "resource", ")", "if", "resource_event", ":", "self", ".", "_last_refresh", "=", "int", "(", "time", ".", "time", "(", ")", ")", "self", ".", "_camera_properties", "=", "resource_event", ".", "get", "(", "'properties'", ")" ]
Return camera properties.
[ "Return", "camera", "properties", "." ]
db70aeb81705309c56ad32bbab1094f6cd146524
https://github.com/tchellomello/python-arlo/blob/db70aeb81705309c56ad32bbab1094f6cd146524/pyarlo/base_station.py#L388-L394
7,133
tchellomello/python-arlo
pyarlo/base_station.py
ArloBaseStation.get_cameras_battery_level
def get_cameras_battery_level(self): """Return a list of battery levels of all cameras.""" battery_levels = {} if not self.camera_properties: return None for camera in self.camera_properties: serialnum = camera.get('serialNumber') cam_battery = camera.get('batteryLevel') battery_levels[serialnum] = cam_battery return battery_levels
python
def get_cameras_battery_level(self): """Return a list of battery levels of all cameras.""" battery_levels = {} if not self.camera_properties: return None for camera in self.camera_properties: serialnum = camera.get('serialNumber') cam_battery = camera.get('batteryLevel') battery_levels[serialnum] = cam_battery return battery_levels
[ "def", "get_cameras_battery_level", "(", "self", ")", ":", "battery_levels", "=", "{", "}", "if", "not", "self", ".", "camera_properties", ":", "return", "None", "for", "camera", "in", "self", ".", "camera_properties", ":", "serialnum", "=", "camera", ".", "get", "(", "'serialNumber'", ")", "cam_battery", "=", "camera", ".", "get", "(", "'batteryLevel'", ")", "battery_levels", "[", "serialnum", "]", "=", "cam_battery", "return", "battery_levels" ]
Return a list of battery levels of all cameras.
[ "Return", "a", "list", "of", "battery", "levels", "of", "all", "cameras", "." ]
db70aeb81705309c56ad32bbab1094f6cd146524
https://github.com/tchellomello/python-arlo/blob/db70aeb81705309c56ad32bbab1094f6cd146524/pyarlo/base_station.py#L396-L406
7,134
tchellomello/python-arlo
pyarlo/base_station.py
ArloBaseStation.get_cameras_signal_strength
def get_cameras_signal_strength(self): """Return a list of signal strength of all cameras.""" signal_strength = {} if not self.camera_properties: return None for camera in self.camera_properties: serialnum = camera.get('serialNumber') cam_strength = camera.get('signalStrength') signal_strength[serialnum] = cam_strength return signal_strength
python
def get_cameras_signal_strength(self): """Return a list of signal strength of all cameras.""" signal_strength = {} if not self.camera_properties: return None for camera in self.camera_properties: serialnum = camera.get('serialNumber') cam_strength = camera.get('signalStrength') signal_strength[serialnum] = cam_strength return signal_strength
[ "def", "get_cameras_signal_strength", "(", "self", ")", ":", "signal_strength", "=", "{", "}", "if", "not", "self", ".", "camera_properties", ":", "return", "None", "for", "camera", "in", "self", ".", "camera_properties", ":", "serialnum", "=", "camera", ".", "get", "(", "'serialNumber'", ")", "cam_strength", "=", "camera", ".", "get", "(", "'signalStrength'", ")", "signal_strength", "[", "serialnum", "]", "=", "cam_strength", "return", "signal_strength" ]
Return a list of signal strength of all cameras.
[ "Return", "a", "list", "of", "signal", "strength", "of", "all", "cameras", "." ]
db70aeb81705309c56ad32bbab1094f6cd146524
https://github.com/tchellomello/python-arlo/blob/db70aeb81705309c56ad32bbab1094f6cd146524/pyarlo/base_station.py#L408-L418
7,135
tchellomello/python-arlo
pyarlo/base_station.py
ArloBaseStation.get_camera_extended_properties
def get_camera_extended_properties(self): """Return camera extended properties.""" resource = 'cameras/{}'.format(self.device_id) resource_event = self.publish_and_get_event(resource) if resource_event is None: return None self._camera_extended_properties = resource_event.get('properties') return self._camera_extended_properties
python
def get_camera_extended_properties(self): """Return camera extended properties.""" resource = 'cameras/{}'.format(self.device_id) resource_event = self.publish_and_get_event(resource) if resource_event is None: return None self._camera_extended_properties = resource_event.get('properties') return self._camera_extended_properties
[ "def", "get_camera_extended_properties", "(", "self", ")", ":", "resource", "=", "'cameras/{}'", ".", "format", "(", "self", ".", "device_id", ")", "resource_event", "=", "self", ".", "publish_and_get_event", "(", "resource", ")", "if", "resource_event", "is", "None", ":", "return", "None", "self", ".", "_camera_extended_properties", "=", "resource_event", ".", "get", "(", "'properties'", ")", "return", "self", ".", "_camera_extended_properties" ]
Return camera extended properties.
[ "Return", "camera", "extended", "properties", "." ]
db70aeb81705309c56ad32bbab1094f6cd146524
https://github.com/tchellomello/python-arlo/blob/db70aeb81705309c56ad32bbab1094f6cd146524/pyarlo/base_station.py#L427-L436
7,136
tchellomello/python-arlo
pyarlo/base_station.py
ArloBaseStation.get_speaker_muted
def get_speaker_muted(self): """Return whether or not the speaker is muted.""" if not self.camera_extended_properties: return None speaker = self.camera_extended_properties.get('speaker') if not speaker: return None return speaker.get('mute')
python
def get_speaker_muted(self): """Return whether or not the speaker is muted.""" if not self.camera_extended_properties: return None speaker = self.camera_extended_properties.get('speaker') if not speaker: return None return speaker.get('mute')
[ "def", "get_speaker_muted", "(", "self", ")", ":", "if", "not", "self", ".", "camera_extended_properties", ":", "return", "None", "speaker", "=", "self", ".", "camera_extended_properties", ".", "get", "(", "'speaker'", ")", "if", "not", "speaker", ":", "return", "None", "return", "speaker", ".", "get", "(", "'mute'", ")" ]
Return whether or not the speaker is muted.
[ "Return", "whether", "or", "not", "the", "speaker", "is", "muted", "." ]
db70aeb81705309c56ad32bbab1094f6cd146524
https://github.com/tchellomello/python-arlo/blob/db70aeb81705309c56ad32bbab1094f6cd146524/pyarlo/base_station.py#L438-L447
7,137
tchellomello/python-arlo
pyarlo/base_station.py
ArloBaseStation.get_speaker_volume
def get_speaker_volume(self): """Return the volume setting of the speaker.""" if not self.camera_extended_properties: return None speaker = self.camera_extended_properties.get('speaker') if not speaker: return None return speaker.get('volume')
python
def get_speaker_volume(self): """Return the volume setting of the speaker.""" if not self.camera_extended_properties: return None speaker = self.camera_extended_properties.get('speaker') if not speaker: return None return speaker.get('volume')
[ "def", "get_speaker_volume", "(", "self", ")", ":", "if", "not", "self", ".", "camera_extended_properties", ":", "return", "None", "speaker", "=", "self", ".", "camera_extended_properties", ".", "get", "(", "'speaker'", ")", "if", "not", "speaker", ":", "return", "None", "return", "speaker", ".", "get", "(", "'volume'", ")" ]
Return the volume setting of the speaker.
[ "Return", "the", "volume", "setting", "of", "the", "speaker", "." ]
db70aeb81705309c56ad32bbab1094f6cd146524
https://github.com/tchellomello/python-arlo/blob/db70aeb81705309c56ad32bbab1094f6cd146524/pyarlo/base_station.py#L449-L458
7,138
tchellomello/python-arlo
pyarlo/base_station.py
ArloBaseStation.properties
def properties(self): """Return the base station info.""" resource = "basestation" basestn_event = self.publish_and_get_event(resource) if basestn_event: return basestn_event.get('properties') return None
python
def properties(self): """Return the base station info.""" resource = "basestation" basestn_event = self.publish_and_get_event(resource) if basestn_event: return basestn_event.get('properties') return None
[ "def", "properties", "(", "self", ")", ":", "resource", "=", "\"basestation\"", "basestn_event", "=", "self", ".", "publish_and_get_event", "(", "resource", ")", "if", "basestn_event", ":", "return", "basestn_event", ".", "get", "(", "'properties'", ")", "return", "None" ]
Return the base station info.
[ "Return", "the", "base", "station", "info", "." ]
db70aeb81705309c56ad32bbab1094f6cd146524
https://github.com/tchellomello/python-arlo/blob/db70aeb81705309c56ad32bbab1094f6cd146524/pyarlo/base_station.py#L486-L493
7,139
tchellomello/python-arlo
pyarlo/base_station.py
ArloBaseStation.get_cameras_rules
def get_cameras_rules(self): """Return the camera rules.""" resource = "rules" rules_event = self.publish_and_get_event(resource) if rules_event: return rules_event.get('properties') return None
python
def get_cameras_rules(self): """Return the camera rules.""" resource = "rules" rules_event = self.publish_and_get_event(resource) if rules_event: return rules_event.get('properties') return None
[ "def", "get_cameras_rules", "(", "self", ")", ":", "resource", "=", "\"rules\"", "rules_event", "=", "self", ".", "publish_and_get_event", "(", "resource", ")", "if", "rules_event", ":", "return", "rules_event", ".", "get", "(", "'properties'", ")", "return", "None" ]
Return the camera rules.
[ "Return", "the", "camera", "rules", "." ]
db70aeb81705309c56ad32bbab1094f6cd146524
https://github.com/tchellomello/python-arlo/blob/db70aeb81705309c56ad32bbab1094f6cd146524/pyarlo/base_station.py#L495-L502
7,140
tchellomello/python-arlo
pyarlo/base_station.py
ArloBaseStation.get_cameras_schedule
def get_cameras_schedule(self): """Return the schedule set for cameras.""" resource = "schedule" schedule_event = self.publish_and_get_event(resource) if schedule_event: return schedule_event.get('properties') return None
python
def get_cameras_schedule(self): """Return the schedule set for cameras.""" resource = "schedule" schedule_event = self.publish_and_get_event(resource) if schedule_event: return schedule_event.get('properties') return None
[ "def", "get_cameras_schedule", "(", "self", ")", ":", "resource", "=", "\"schedule\"", "schedule_event", "=", "self", ".", "publish_and_get_event", "(", "resource", ")", "if", "schedule_event", ":", "return", "schedule_event", ".", "get", "(", "'properties'", ")", "return", "None" ]
Return the schedule set for cameras.
[ "Return", "the", "schedule", "set", "for", "cameras", "." ]
db70aeb81705309c56ad32bbab1094f6cd146524
https://github.com/tchellomello/python-arlo/blob/db70aeb81705309c56ad32bbab1094f6cd146524/pyarlo/base_station.py#L504-L511
7,141
tchellomello/python-arlo
pyarlo/base_station.py
ArloBaseStation.get_ambient_sensor_data
def get_ambient_sensor_data(self): """Refresh ambient sensor history""" resource = 'cameras/{}/ambientSensors/history'.format(self.device_id) history_event = self.publish_and_get_event(resource) if history_event is None: return None properties = history_event.get('properties') self._ambient_sensor_data = \ ArloBaseStation._decode_sensor_data(properties) return self._ambient_sensor_data
python
def get_ambient_sensor_data(self): """Refresh ambient sensor history""" resource = 'cameras/{}/ambientSensors/history'.format(self.device_id) history_event = self.publish_and_get_event(resource) if history_event is None: return None properties = history_event.get('properties') self._ambient_sensor_data = \ ArloBaseStation._decode_sensor_data(properties) return self._ambient_sensor_data
[ "def", "get_ambient_sensor_data", "(", "self", ")", ":", "resource", "=", "'cameras/{}/ambientSensors/history'", ".", "format", "(", "self", ".", "device_id", ")", "history_event", "=", "self", ".", "publish_and_get_event", "(", "resource", ")", "if", "history_event", "is", "None", ":", "return", "None", "properties", "=", "history_event", ".", "get", "(", "'properties'", ")", "self", ".", "_ambient_sensor_data", "=", "ArloBaseStation", ".", "_decode_sensor_data", "(", "properties", ")", "return", "self", ".", "_ambient_sensor_data" ]
Refresh ambient sensor history
[ "Refresh", "ambient", "sensor", "history" ]
db70aeb81705309c56ad32bbab1094f6cd146524
https://github.com/tchellomello/python-arlo/blob/db70aeb81705309c56ad32bbab1094f6cd146524/pyarlo/base_station.py#L543-L556
7,142
tchellomello/python-arlo
pyarlo/base_station.py
ArloBaseStation._decode_sensor_data
def _decode_sensor_data(properties): """Decode, decompress, and parse the data from the history API""" b64_input = "" for s in properties.get('payload'): # pylint: disable=consider-using-join b64_input += s decoded = base64.b64decode(b64_input) data = zlib.decompress(decoded) points = [] i = 0 while i < len(data): points.append({ 'timestamp': int(1e3 * ArloBaseStation._parse_statistic( data[i:(i + 4)], 0)), 'temperature': ArloBaseStation._parse_statistic( data[(i + 8):(i + 10)], 1), 'humidity': ArloBaseStation._parse_statistic( data[(i + 14):(i + 16)], 1), 'airQuality': ArloBaseStation._parse_statistic( data[(i + 20):(i + 22)], 1) }) i += 22 return points
python
def _decode_sensor_data(properties): """Decode, decompress, and parse the data from the history API""" b64_input = "" for s in properties.get('payload'): # pylint: disable=consider-using-join b64_input += s decoded = base64.b64decode(b64_input) data = zlib.decompress(decoded) points = [] i = 0 while i < len(data): points.append({ 'timestamp': int(1e3 * ArloBaseStation._parse_statistic( data[i:(i + 4)], 0)), 'temperature': ArloBaseStation._parse_statistic( data[(i + 8):(i + 10)], 1), 'humidity': ArloBaseStation._parse_statistic( data[(i + 14):(i + 16)], 1), 'airQuality': ArloBaseStation._parse_statistic( data[(i + 20):(i + 22)], 1) }) i += 22 return points
[ "def", "_decode_sensor_data", "(", "properties", ")", ":", "b64_input", "=", "\"\"", "for", "s", "in", "properties", ".", "get", "(", "'payload'", ")", ":", "# pylint: disable=consider-using-join", "b64_input", "+=", "s", "decoded", "=", "base64", ".", "b64decode", "(", "b64_input", ")", "data", "=", "zlib", ".", "decompress", "(", "decoded", ")", "points", "=", "[", "]", "i", "=", "0", "while", "i", "<", "len", "(", "data", ")", ":", "points", ".", "append", "(", "{", "'timestamp'", ":", "int", "(", "1e3", "*", "ArloBaseStation", ".", "_parse_statistic", "(", "data", "[", "i", ":", "(", "i", "+", "4", ")", "]", ",", "0", ")", ")", ",", "'temperature'", ":", "ArloBaseStation", ".", "_parse_statistic", "(", "data", "[", "(", "i", "+", "8", ")", ":", "(", "i", "+", "10", ")", "]", ",", "1", ")", ",", "'humidity'", ":", "ArloBaseStation", ".", "_parse_statistic", "(", "data", "[", "(", "i", "+", "14", ")", ":", "(", "i", "+", "16", ")", "]", ",", "1", ")", ",", "'airQuality'", ":", "ArloBaseStation", ".", "_parse_statistic", "(", "data", "[", "(", "i", "+", "20", ")", ":", "(", "i", "+", "22", ")", "]", ",", "1", ")", "}", ")", "i", "+=", "22", "return", "points" ]
Decode, decompress, and parse the data from the history API
[ "Decode", "decompress", "and", "parse", "the", "data", "from", "the", "history", "API" ]
db70aeb81705309c56ad32bbab1094f6cd146524
https://github.com/tchellomello/python-arlo/blob/db70aeb81705309c56ad32bbab1094f6cd146524/pyarlo/base_station.py#L559-L584
7,143
tchellomello/python-arlo
pyarlo/base_station.py
ArloBaseStation._parse_statistic
def _parse_statistic(data, scale): """Parse binary statistics returned from the history API""" i = 0 for byte in bytearray(data): i = (i << 8) + byte if i == 32768: return None if scale == 0: return i return float(i) / (scale * 10)
python
def _parse_statistic(data, scale): """Parse binary statistics returned from the history API""" i = 0 for byte in bytearray(data): i = (i << 8) + byte if i == 32768: return None if scale == 0: return i return float(i) / (scale * 10)
[ "def", "_parse_statistic", "(", "data", ",", "scale", ")", ":", "i", "=", "0", "for", "byte", "in", "bytearray", "(", "data", ")", ":", "i", "=", "(", "i", "<<", "8", ")", "+", "byte", "if", "i", "==", "32768", ":", "return", "None", "if", "scale", "==", "0", ":", "return", "i", "return", "float", "(", "i", ")", "/", "(", "scale", "*", "10", ")" ]
Parse binary statistics returned from the history API
[ "Parse", "binary", "statistics", "returned", "from", "the", "history", "API" ]
db70aeb81705309c56ad32bbab1094f6cd146524
https://github.com/tchellomello/python-arlo/blob/db70aeb81705309c56ad32bbab1094f6cd146524/pyarlo/base_station.py#L587-L599
7,144
tchellomello/python-arlo
pyarlo/base_station.py
ArloBaseStation.play_track
def play_track(self, track_id=DEFAULT_TRACK_ID, position=0): """Plays a track at the given position.""" self.publish( action='playTrack', resource='audioPlayback/player', publish_response=False, properties={'trackId': track_id, 'position': position} )
python
def play_track(self, track_id=DEFAULT_TRACK_ID, position=0): """Plays a track at the given position.""" self.publish( action='playTrack', resource='audioPlayback/player', publish_response=False, properties={'trackId': track_id, 'position': position} )
[ "def", "play_track", "(", "self", ",", "track_id", "=", "DEFAULT_TRACK_ID", ",", "position", "=", "0", ")", ":", "self", ".", "publish", "(", "action", "=", "'playTrack'", ",", "resource", "=", "'audioPlayback/player'", ",", "publish_response", "=", "False", ",", "properties", "=", "{", "'trackId'", ":", "track_id", ",", "'position'", ":", "position", "}", ")" ]
Plays a track at the given position.
[ "Plays", "a", "track", "at", "the", "given", "position", "." ]
db70aeb81705309c56ad32bbab1094f6cd146524
https://github.com/tchellomello/python-arlo/blob/db70aeb81705309c56ad32bbab1094f6cd146524/pyarlo/base_station.py#L618-L625
7,145
tchellomello/python-arlo
pyarlo/base_station.py
ArloBaseStation.set_shuffle_on
def set_shuffle_on(self): """Sets playback to shuffle.""" self.publish( action='set', resource='audioPlayback/config', publish_response=False, properties={'config': {'shuffleActive': True}} )
python
def set_shuffle_on(self): """Sets playback to shuffle.""" self.publish( action='set', resource='audioPlayback/config', publish_response=False, properties={'config': {'shuffleActive': True}} )
[ "def", "set_shuffle_on", "(", "self", ")", ":", "self", ".", "publish", "(", "action", "=", "'set'", ",", "resource", "=", "'audioPlayback/config'", ",", "publish_response", "=", "False", ",", "properties", "=", "{", "'config'", ":", "{", "'shuffleActive'", ":", "True", "}", "}", ")" ]
Sets playback to shuffle.
[ "Sets", "playback", "to", "shuffle", "." ]
db70aeb81705309c56ad32bbab1094f6cd146524
https://github.com/tchellomello/python-arlo/blob/db70aeb81705309c56ad32bbab1094f6cd146524/pyarlo/base_station.py#L661-L668
7,146
tchellomello/python-arlo
pyarlo/base_station.py
ArloBaseStation.set_shuffle_off
def set_shuffle_off(self): """Sets playback to sequential.""" self.publish( action='set', resource='audioPlayback/config', publish_response=False, properties={'config': {'shuffleActive': False}} )
python
def set_shuffle_off(self): """Sets playback to sequential.""" self.publish( action='set', resource='audioPlayback/config', publish_response=False, properties={'config': {'shuffleActive': False}} )
[ "def", "set_shuffle_off", "(", "self", ")", ":", "self", ".", "publish", "(", "action", "=", "'set'", ",", "resource", "=", "'audioPlayback/config'", ",", "publish_response", "=", "False", ",", "properties", "=", "{", "'config'", ":", "{", "'shuffleActive'", ":", "False", "}", "}", ")" ]
Sets playback to sequential.
[ "Sets", "playback", "to", "sequential", "." ]
db70aeb81705309c56ad32bbab1094f6cd146524
https://github.com/tchellomello/python-arlo/blob/db70aeb81705309c56ad32bbab1094f6cd146524/pyarlo/base_station.py#L670-L677
7,147
tchellomello/python-arlo
pyarlo/base_station.py
ArloBaseStation.set_night_light_on
def set_night_light_on(self): """Turns on the night light.""" self.publish( action='set', resource='cameras/{}'.format(self.device_id), publish_response=False, properties={'nightLight': {'enabled': True}} )
python
def set_night_light_on(self): """Turns on the night light.""" self.publish( action='set', resource='cameras/{}'.format(self.device_id), publish_response=False, properties={'nightLight': {'enabled': True}} )
[ "def", "set_night_light_on", "(", "self", ")", ":", "self", ".", "publish", "(", "action", "=", "'set'", ",", "resource", "=", "'cameras/{}'", ".", "format", "(", "self", ".", "device_id", ")", ",", "publish_response", "=", "False", ",", "properties", "=", "{", "'nightLight'", ":", "{", "'enabled'", ":", "True", "}", "}", ")" ]
Turns on the night light.
[ "Turns", "on", "the", "night", "light", "." ]
db70aeb81705309c56ad32bbab1094f6cd146524
https://github.com/tchellomello/python-arlo/blob/db70aeb81705309c56ad32bbab1094f6cd146524/pyarlo/base_station.py#L688-L695
7,148
tchellomello/python-arlo
pyarlo/base_station.py
ArloBaseStation.set_night_light_off
def set_night_light_off(self): """Turns off the night light.""" self.publish( action='set', resource='cameras/{}'.format(self.device_id), publish_response=False, properties={'nightLight': {'enabled': False}} )
python
def set_night_light_off(self): """Turns off the night light.""" self.publish( action='set', resource='cameras/{}'.format(self.device_id), publish_response=False, properties={'nightLight': {'enabled': False}} )
[ "def", "set_night_light_off", "(", "self", ")", ":", "self", ".", "publish", "(", "action", "=", "'set'", ",", "resource", "=", "'cameras/{}'", ".", "format", "(", "self", ".", "device_id", ")", ",", "publish_response", "=", "False", ",", "properties", "=", "{", "'nightLight'", ":", "{", "'enabled'", ":", "False", "}", "}", ")" ]
Turns off the night light.
[ "Turns", "off", "the", "night", "light", "." ]
db70aeb81705309c56ad32bbab1094f6cd146524
https://github.com/tchellomello/python-arlo/blob/db70aeb81705309c56ad32bbab1094f6cd146524/pyarlo/base_station.py#L697-L704
7,149
tchellomello/python-arlo
pyarlo/base_station.py
ArloBaseStation.mode
def mode(self, mode): """Set Arlo camera mode. :param mode: arm, disarm """ modes = self.available_modes if (not modes) or (mode not in modes): return self.publish( action='set', resource='modes' if mode != 'schedule' else 'schedule', mode=mode, publish_response=True) self.update()
python
def mode(self, mode): """Set Arlo camera mode. :param mode: arm, disarm """ modes = self.available_modes if (not modes) or (mode not in modes): return self.publish( action='set', resource='modes' if mode != 'schedule' else 'schedule', mode=mode, publish_response=True) self.update()
[ "def", "mode", "(", "self", ",", "mode", ")", ":", "modes", "=", "self", ".", "available_modes", "if", "(", "not", "modes", ")", "or", "(", "mode", "not", "in", "modes", ")", ":", "return", "self", ".", "publish", "(", "action", "=", "'set'", ",", "resource", "=", "'modes'", "if", "mode", "!=", "'schedule'", "else", "'schedule'", ",", "mode", "=", "mode", ",", "publish_response", "=", "True", ")", "self", ".", "update", "(", ")" ]
Set Arlo camera mode. :param mode: arm, disarm
[ "Set", "Arlo", "camera", "mode", "." ]
db70aeb81705309c56ad32bbab1094f6cd146524
https://github.com/tchellomello/python-arlo/blob/db70aeb81705309c56ad32bbab1094f6cd146524/pyarlo/base_station.py#L728-L741
7,150
zestyping/q
q.py
Q.unindent
def unindent(self, lines): """Removes any indentation that is common to all of the given lines.""" indent = min( len(self.re.match(r'^ *', line).group()) for line in lines) return [line[indent:].rstrip() for line in lines]
python
def unindent(self, lines): """Removes any indentation that is common to all of the given lines.""" indent = min( len(self.re.match(r'^ *', line).group()) for line in lines) return [line[indent:].rstrip() for line in lines]
[ "def", "unindent", "(", "self", ",", "lines", ")", ":", "indent", "=", "min", "(", "len", "(", "self", ".", "re", ".", "match", "(", "r'^ *'", ",", "line", ")", ".", "group", "(", ")", ")", "for", "line", "in", "lines", ")", "return", "[", "line", "[", "indent", ":", "]", ".", "rstrip", "(", ")", "for", "line", "in", "lines", "]" ]
Removes any indentation that is common to all of the given lines.
[ "Removes", "any", "indentation", "that", "is", "common", "to", "all", "of", "the", "given", "lines", "." ]
1c178bf3595eb579f29957f674c08f4a1cd00ffe
https://github.com/zestyping/q/blob/1c178bf3595eb579f29957f674c08f4a1cd00ffe/q.py#L194-L198
7,151
zestyping/q
q.py
Q.get_call_exprs
def get_call_exprs(self, line): """Gets the argument expressions from the source of a function call.""" line = line.lstrip() try: tree = self.ast.parse(line) except SyntaxError: return None for node in self.ast.walk(tree): if isinstance(node, self.ast.Call): offsets = [] for arg in node.args: # In Python 3.4 the col_offset is calculated wrong. See # https://bugs.python.org/issue21295 if isinstance(arg, self.ast.Attribute) and ( (3, 4, 0) <= self.sys.version_info <= (3, 4, 3)): offsets.append(arg.col_offset - len(arg.value.id) - 1) else: offsets.append(arg.col_offset) if node.keywords: line = line[:node.keywords[0].value.col_offset] line = self.re.sub(r'\w+\s*=\s*$', '', line) else: line = self.re.sub(r'\s*\)\s*$', '', line) offsets.append(len(line)) args = [] for i in range(len(node.args)): args.append(line[offsets[i]:offsets[i + 1]].rstrip(', ')) return args
python
def get_call_exprs(self, line): """Gets the argument expressions from the source of a function call.""" line = line.lstrip() try: tree = self.ast.parse(line) except SyntaxError: return None for node in self.ast.walk(tree): if isinstance(node, self.ast.Call): offsets = [] for arg in node.args: # In Python 3.4 the col_offset is calculated wrong. See # https://bugs.python.org/issue21295 if isinstance(arg, self.ast.Attribute) and ( (3, 4, 0) <= self.sys.version_info <= (3, 4, 3)): offsets.append(arg.col_offset - len(arg.value.id) - 1) else: offsets.append(arg.col_offset) if node.keywords: line = line[:node.keywords[0].value.col_offset] line = self.re.sub(r'\w+\s*=\s*$', '', line) else: line = self.re.sub(r'\s*\)\s*$', '', line) offsets.append(len(line)) args = [] for i in range(len(node.args)): args.append(line[offsets[i]:offsets[i + 1]].rstrip(', ')) return args
[ "def", "get_call_exprs", "(", "self", ",", "line", ")", ":", "line", "=", "line", ".", "lstrip", "(", ")", "try", ":", "tree", "=", "self", ".", "ast", ".", "parse", "(", "line", ")", "except", "SyntaxError", ":", "return", "None", "for", "node", "in", "self", ".", "ast", ".", "walk", "(", "tree", ")", ":", "if", "isinstance", "(", "node", ",", "self", ".", "ast", ".", "Call", ")", ":", "offsets", "=", "[", "]", "for", "arg", "in", "node", ".", "args", ":", "# In Python 3.4 the col_offset is calculated wrong. See", "# https://bugs.python.org/issue21295", "if", "isinstance", "(", "arg", ",", "self", ".", "ast", ".", "Attribute", ")", "and", "(", "(", "3", ",", "4", ",", "0", ")", "<=", "self", ".", "sys", ".", "version_info", "<=", "(", "3", ",", "4", ",", "3", ")", ")", ":", "offsets", ".", "append", "(", "arg", ".", "col_offset", "-", "len", "(", "arg", ".", "value", ".", "id", ")", "-", "1", ")", "else", ":", "offsets", ".", "append", "(", "arg", ".", "col_offset", ")", "if", "node", ".", "keywords", ":", "line", "=", "line", "[", ":", "node", ".", "keywords", "[", "0", "]", ".", "value", ".", "col_offset", "]", "line", "=", "self", ".", "re", ".", "sub", "(", "r'\\w+\\s*=\\s*$'", ",", "''", ",", "line", ")", "else", ":", "line", "=", "self", ".", "re", ".", "sub", "(", "r'\\s*\\)\\s*$'", ",", "''", ",", "line", ")", "offsets", ".", "append", "(", "len", "(", "line", ")", ")", "args", "=", "[", "]", "for", "i", "in", "range", "(", "len", "(", "node", ".", "args", ")", ")", ":", "args", ".", "append", "(", "line", "[", "offsets", "[", "i", "]", ":", "offsets", "[", "i", "+", "1", "]", "]", ".", "rstrip", "(", "', '", ")", ")", "return", "args" ]
Gets the argument expressions from the source of a function call.
[ "Gets", "the", "argument", "expressions", "from", "the", "source", "of", "a", "function", "call", "." ]
1c178bf3595eb579f29957f674c08f4a1cd00ffe
https://github.com/zestyping/q/blob/1c178bf3595eb579f29957f674c08f4a1cd00ffe/q.py#L214-L241
7,152
zestyping/q
q.py
Q.show
def show(self, func_name, values, labels=None): """Prints out nice representations of the given values.""" s = self.Stanza(self.indent) if func_name == '<module>' and self.in_console: func_name = '<console>' s.add([func_name + ': ']) reprs = map(self.safe_repr, values) if labels: sep = '' for label, repr in zip(labels, reprs): s.add([label + '=', self.CYAN, repr, self.NORMAL], sep) sep = ', ' else: sep = '' for repr in reprs: s.add([self.CYAN, repr, self.NORMAL], sep) sep = ', ' self.writer.write(s.chunks)
python
def show(self, func_name, values, labels=None): """Prints out nice representations of the given values.""" s = self.Stanza(self.indent) if func_name == '<module>' and self.in_console: func_name = '<console>' s.add([func_name + ': ']) reprs = map(self.safe_repr, values) if labels: sep = '' for label, repr in zip(labels, reprs): s.add([label + '=', self.CYAN, repr, self.NORMAL], sep) sep = ', ' else: sep = '' for repr in reprs: s.add([self.CYAN, repr, self.NORMAL], sep) sep = ', ' self.writer.write(s.chunks)
[ "def", "show", "(", "self", ",", "func_name", ",", "values", ",", "labels", "=", "None", ")", ":", "s", "=", "self", ".", "Stanza", "(", "self", ".", "indent", ")", "if", "func_name", "==", "'<module>'", "and", "self", ".", "in_console", ":", "func_name", "=", "'<console>'", "s", ".", "add", "(", "[", "func_name", "+", "': '", "]", ")", "reprs", "=", "map", "(", "self", ".", "safe_repr", ",", "values", ")", "if", "labels", ":", "sep", "=", "''", "for", "label", ",", "repr", "in", "zip", "(", "labels", ",", "reprs", ")", ":", "s", ".", "add", "(", "[", "label", "+", "'='", ",", "self", ".", "CYAN", ",", "repr", ",", "self", ".", "NORMAL", "]", ",", "sep", ")", "sep", "=", "', '", "else", ":", "sep", "=", "''", "for", "repr", "in", "reprs", ":", "s", ".", "add", "(", "[", "self", ".", "CYAN", ",", "repr", ",", "self", ".", "NORMAL", "]", ",", "sep", ")", "sep", "=", "', '", "self", ".", "writer", ".", "write", "(", "s", ".", "chunks", ")" ]
Prints out nice representations of the given values.
[ "Prints", "out", "nice", "representations", "of", "the", "given", "values", "." ]
1c178bf3595eb579f29957f674c08f4a1cd00ffe
https://github.com/zestyping/q/blob/1c178bf3595eb579f29957f674c08f4a1cd00ffe/q.py#L243-L260
7,153
zestyping/q
q.py
Q.trace
def trace(self, func): """Decorator to print out a function's arguments and return value.""" def wrapper(*args, **kwargs): # Print out the call to the function with its arguments. s = self.Stanza(self.indent) s.add([self.GREEN, func.__name__, self.NORMAL, '(']) s.indent += 4 sep = '' for arg in args: s.add([self.CYAN, self.safe_repr(arg), self.NORMAL], sep) sep = ', ' for name, value in sorted(kwargs.items()): s.add([name + '=', self.CYAN, self.safe_repr(value), self.NORMAL], sep) sep = ', ' s.add(')', wrap=False) self.writer.write(s.chunks) # Call the function. self.indent += 2 try: result = func(*args, **kwargs) except: # Display an exception. self.indent -= 2 etype, evalue, etb = self.sys.exc_info() info = self.inspect.getframeinfo(etb.tb_next, context=3) s = self.Stanza(self.indent) s.add([self.RED, '!> ', self.safe_repr(evalue), self.NORMAL]) s.add(['at ', info.filename, ':', info.lineno], ' ') lines = self.unindent(info.code_context) firstlineno = info.lineno - info.index fmt = '%' + str(len(str(firstlineno + len(lines)))) + 'd' for i, line in enumerate(lines): s.newline() s.add([ i == info.index and self.MAGENTA or '', fmt % (i + firstlineno), i == info.index and '> ' or ': ', line, self.NORMAL]) self.writer.write(s.chunks) raise # Display the return value. self.indent -= 2 s = self.Stanza(self.indent) s.add([self.GREEN, '-> ', self.CYAN, self.safe_repr(result), self.NORMAL]) self.writer.write(s.chunks) return result return self.functools.update_wrapper(wrapper, func)
python
def trace(self, func): """Decorator to print out a function's arguments and return value.""" def wrapper(*args, **kwargs): # Print out the call to the function with its arguments. s = self.Stanza(self.indent) s.add([self.GREEN, func.__name__, self.NORMAL, '(']) s.indent += 4 sep = '' for arg in args: s.add([self.CYAN, self.safe_repr(arg), self.NORMAL], sep) sep = ', ' for name, value in sorted(kwargs.items()): s.add([name + '=', self.CYAN, self.safe_repr(value), self.NORMAL], sep) sep = ', ' s.add(')', wrap=False) self.writer.write(s.chunks) # Call the function. self.indent += 2 try: result = func(*args, **kwargs) except: # Display an exception. self.indent -= 2 etype, evalue, etb = self.sys.exc_info() info = self.inspect.getframeinfo(etb.tb_next, context=3) s = self.Stanza(self.indent) s.add([self.RED, '!> ', self.safe_repr(evalue), self.NORMAL]) s.add(['at ', info.filename, ':', info.lineno], ' ') lines = self.unindent(info.code_context) firstlineno = info.lineno - info.index fmt = '%' + str(len(str(firstlineno + len(lines)))) + 'd' for i, line in enumerate(lines): s.newline() s.add([ i == info.index and self.MAGENTA or '', fmt % (i + firstlineno), i == info.index and '> ' or ': ', line, self.NORMAL]) self.writer.write(s.chunks) raise # Display the return value. self.indent -= 2 s = self.Stanza(self.indent) s.add([self.GREEN, '-> ', self.CYAN, self.safe_repr(result), self.NORMAL]) self.writer.write(s.chunks) return result return self.functools.update_wrapper(wrapper, func)
[ "def", "trace", "(", "self", ",", "func", ")", ":", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# Print out the call to the function with its arguments.", "s", "=", "self", ".", "Stanza", "(", "self", ".", "indent", ")", "s", ".", "add", "(", "[", "self", ".", "GREEN", ",", "func", ".", "__name__", ",", "self", ".", "NORMAL", ",", "'('", "]", ")", "s", ".", "indent", "+=", "4", "sep", "=", "''", "for", "arg", "in", "args", ":", "s", ".", "add", "(", "[", "self", ".", "CYAN", ",", "self", ".", "safe_repr", "(", "arg", ")", ",", "self", ".", "NORMAL", "]", ",", "sep", ")", "sep", "=", "', '", "for", "name", ",", "value", "in", "sorted", "(", "kwargs", ".", "items", "(", ")", ")", ":", "s", ".", "add", "(", "[", "name", "+", "'='", ",", "self", ".", "CYAN", ",", "self", ".", "safe_repr", "(", "value", ")", ",", "self", ".", "NORMAL", "]", ",", "sep", ")", "sep", "=", "', '", "s", ".", "add", "(", "')'", ",", "wrap", "=", "False", ")", "self", ".", "writer", ".", "write", "(", "s", ".", "chunks", ")", "# Call the function.", "self", ".", "indent", "+=", "2", "try", ":", "result", "=", "func", "(", "*", "args", ",", "*", "*", "kwargs", ")", "except", ":", "# Display an exception.", "self", ".", "indent", "-=", "2", "etype", ",", "evalue", ",", "etb", "=", "self", ".", "sys", ".", "exc_info", "(", ")", "info", "=", "self", ".", "inspect", ".", "getframeinfo", "(", "etb", ".", "tb_next", ",", "context", "=", "3", ")", "s", "=", "self", ".", "Stanza", "(", "self", ".", "indent", ")", "s", ".", "add", "(", "[", "self", ".", "RED", ",", "'!> '", ",", "self", ".", "safe_repr", "(", "evalue", ")", ",", "self", ".", "NORMAL", "]", ")", "s", ".", "add", "(", "[", "'at '", ",", "info", ".", "filename", ",", "':'", ",", "info", ".", "lineno", "]", ",", "' '", ")", "lines", "=", "self", ".", "unindent", "(", "info", ".", "code_context", ")", "firstlineno", "=", "info", ".", "lineno", "-", "info", ".", "index", "fmt", "=", "'%'", "+", "str", "(", "len", "(", "str", "(", "firstlineno", "+", "len", "(", "lines", ")", ")", ")", ")", "+", "'d'", "for", "i", ",", "line", "in", "enumerate", "(", "lines", ")", ":", "s", ".", "newline", "(", ")", "s", ".", "add", "(", "[", "i", "==", "info", ".", "index", "and", "self", ".", "MAGENTA", "or", "''", ",", "fmt", "%", "(", "i", "+", "firstlineno", ")", ",", "i", "==", "info", ".", "index", "and", "'> '", "or", "': '", ",", "line", ",", "self", ".", "NORMAL", "]", ")", "self", ".", "writer", ".", "write", "(", "s", ".", "chunks", ")", "raise", "# Display the return value.", "self", ".", "indent", "-=", "2", "s", "=", "self", ".", "Stanza", "(", "self", ".", "indent", ")", "s", ".", "add", "(", "[", "self", ".", "GREEN", ",", "'-> '", ",", "self", ".", "CYAN", ",", "self", ".", "safe_repr", "(", "result", ")", ",", "self", ".", "NORMAL", "]", ")", "self", ".", "writer", ".", "write", "(", "s", ".", "chunks", ")", "return", "result", "return", "self", ".", "functools", ".", "update_wrapper", "(", "wrapper", ",", "func", ")" ]
Decorator to print out a function's arguments and return value.
[ "Decorator", "to", "print", "out", "a", "function", "s", "arguments", "and", "return", "value", "." ]
1c178bf3595eb579f29957f674c08f4a1cd00ffe
https://github.com/zestyping/q/blob/1c178bf3595eb579f29957f674c08f4a1cd00ffe/q.py#L262-L312
7,154
zestyping/q
q.py
Q.d
def d(self, depth=1): """Launches an interactive console at the point where it's called.""" info = self.inspect.getframeinfo(self.sys._getframe(1)) s = self.Stanza(self.indent) s.add([info.function + ': ']) s.add([self.MAGENTA, 'Interactive console opened', self.NORMAL]) self.writer.write(s.chunks) frame = self.sys._getframe(depth) env = frame.f_globals.copy() env.update(frame.f_locals) self.indent += 2 self.in_console = True self.code.interact( 'Python console opened by q.d() in ' + info.function, local=env) self.in_console = False self.indent -= 2 s = self.Stanza(self.indent) s.add([info.function + ': ']) s.add([self.MAGENTA, 'Interactive console closed', self.NORMAL]) self.writer.write(s.chunks)
python
def d(self, depth=1): """Launches an interactive console at the point where it's called.""" info = self.inspect.getframeinfo(self.sys._getframe(1)) s = self.Stanza(self.indent) s.add([info.function + ': ']) s.add([self.MAGENTA, 'Interactive console opened', self.NORMAL]) self.writer.write(s.chunks) frame = self.sys._getframe(depth) env = frame.f_globals.copy() env.update(frame.f_locals) self.indent += 2 self.in_console = True self.code.interact( 'Python console opened by q.d() in ' + info.function, local=env) self.in_console = False self.indent -= 2 s = self.Stanza(self.indent) s.add([info.function + ': ']) s.add([self.MAGENTA, 'Interactive console closed', self.NORMAL]) self.writer.write(s.chunks)
[ "def", "d", "(", "self", ",", "depth", "=", "1", ")", ":", "info", "=", "self", ".", "inspect", ".", "getframeinfo", "(", "self", ".", "sys", ".", "_getframe", "(", "1", ")", ")", "s", "=", "self", ".", "Stanza", "(", "self", ".", "indent", ")", "s", ".", "add", "(", "[", "info", ".", "function", "+", "': '", "]", ")", "s", ".", "add", "(", "[", "self", ".", "MAGENTA", ",", "'Interactive console opened'", ",", "self", ".", "NORMAL", "]", ")", "self", ".", "writer", ".", "write", "(", "s", ".", "chunks", ")", "frame", "=", "self", ".", "sys", ".", "_getframe", "(", "depth", ")", "env", "=", "frame", ".", "f_globals", ".", "copy", "(", ")", "env", ".", "update", "(", "frame", ".", "f_locals", ")", "self", ".", "indent", "+=", "2", "self", ".", "in_console", "=", "True", "self", ".", "code", ".", "interact", "(", "'Python console opened by q.d() in '", "+", "info", ".", "function", ",", "local", "=", "env", ")", "self", ".", "in_console", "=", "False", "self", ".", "indent", "-=", "2", "s", "=", "self", ".", "Stanza", "(", "self", ".", "indent", ")", "s", ".", "add", "(", "[", "info", ".", "function", "+", "': '", "]", ")", "s", ".", "add", "(", "[", "self", ".", "MAGENTA", ",", "'Interactive console closed'", ",", "self", ".", "NORMAL", "]", ")", "self", ".", "writer", ".", "write", "(", "s", ".", "chunks", ")" ]
Launches an interactive console at the point where it's called.
[ "Launches", "an", "interactive", "console", "at", "the", "point", "where", "it", "s", "called", "." ]
1c178bf3595eb579f29957f674c08f4a1cd00ffe
https://github.com/zestyping/q/blob/1c178bf3595eb579f29957f674c08f4a1cd00ffe/q.py#L353-L374
7,155
pyopenapi/pyswagger
pyswagger/scanner/v1_2/upgrade.py
Upgrade.swagger
def swagger(self): """ some preparation before returning Swagger object """ # prepare Swagger.host & Swagger.basePath if not self.__swagger: return None common_path = os.path.commonprefix(list(self.__swagger.paths)) # remove tailing slash, # because all paths in Paths Object would prefixed with slah. common_path = common_path[:-1] if common_path[-1] == '/' else common_path if len(common_path) > 0: p = six.moves.urllib.parse.urlparse(common_path) self.__swagger.update_field('host', p.netloc) new_common_path = six.moves.urllib.parse.urlunparse(( p.scheme, p.netloc, '', '', '', '')) new_path = {} for k in self.__swagger.paths.keys(): new_path[k[len(new_common_path):]] = self.__swagger.paths[k] self.__swagger.update_field('paths', new_path) return self.__swagger
python
def swagger(self): """ some preparation before returning Swagger object """ # prepare Swagger.host & Swagger.basePath if not self.__swagger: return None common_path = os.path.commonprefix(list(self.__swagger.paths)) # remove tailing slash, # because all paths in Paths Object would prefixed with slah. common_path = common_path[:-1] if common_path[-1] == '/' else common_path if len(common_path) > 0: p = six.moves.urllib.parse.urlparse(common_path) self.__swagger.update_field('host', p.netloc) new_common_path = six.moves.urllib.parse.urlunparse(( p.scheme, p.netloc, '', '', '', '')) new_path = {} for k in self.__swagger.paths.keys(): new_path[k[len(new_common_path):]] = self.__swagger.paths[k] self.__swagger.update_field('paths', new_path) return self.__swagger
[ "def", "swagger", "(", "self", ")", ":", "# prepare Swagger.host & Swagger.basePath", "if", "not", "self", ".", "__swagger", ":", "return", "None", "common_path", "=", "os", ".", "path", ".", "commonprefix", "(", "list", "(", "self", ".", "__swagger", ".", "paths", ")", ")", "# remove tailing slash,", "# because all paths in Paths Object would prefixed with slah.", "common_path", "=", "common_path", "[", ":", "-", "1", "]", "if", "common_path", "[", "-", "1", "]", "==", "'/'", "else", "common_path", "if", "len", "(", "common_path", ")", ">", "0", ":", "p", "=", "six", ".", "moves", ".", "urllib", ".", "parse", ".", "urlparse", "(", "common_path", ")", "self", ".", "__swagger", ".", "update_field", "(", "'host'", ",", "p", ".", "netloc", ")", "new_common_path", "=", "six", ".", "moves", ".", "urllib", ".", "parse", ".", "urlunparse", "(", "(", "p", ".", "scheme", ",", "p", ".", "netloc", ",", "''", ",", "''", ",", "''", ",", "''", ")", ")", "new_path", "=", "{", "}", "for", "k", "in", "self", ".", "__swagger", ".", "paths", ".", "keys", "(", ")", ":", "new_path", "[", "k", "[", "len", "(", "new_common_path", ")", ":", "]", "]", "=", "self", ".", "__swagger", ".", "paths", "[", "k", "]", "self", ".", "__swagger", ".", "update_field", "(", "'paths'", ",", "new_path", ")", "return", "self", ".", "__swagger" ]
some preparation before returning Swagger object
[ "some", "preparation", "before", "returning", "Swagger", "object" ]
333c4ca08e758cd2194943d9904a3eda3fe43977
https://github.com/pyopenapi/pyswagger/blob/333c4ca08e758cd2194943d9904a3eda3fe43977/pyswagger/scanner/v1_2/upgrade.py#L288-L311
7,156
pyopenapi/pyswagger
pyswagger/utils.py
scope_compose
def scope_compose(scope, name, sep=private.SCOPE_SEPARATOR): """ compose a new scope :param str scope: current scope :param str name: name of next level in scope :return the composed scope """ if name == None: new_scope = scope else: new_scope = scope if scope else name if scope and name: new_scope = scope + sep + name return new_scope
python
def scope_compose(scope, name, sep=private.SCOPE_SEPARATOR): """ compose a new scope :param str scope: current scope :param str name: name of next level in scope :return the composed scope """ if name == None: new_scope = scope else: new_scope = scope if scope else name if scope and name: new_scope = scope + sep + name return new_scope
[ "def", "scope_compose", "(", "scope", ",", "name", ",", "sep", "=", "private", ".", "SCOPE_SEPARATOR", ")", ":", "if", "name", "==", "None", ":", "new_scope", "=", "scope", "else", ":", "new_scope", "=", "scope", "if", "scope", "else", "name", "if", "scope", "and", "name", ":", "new_scope", "=", "scope", "+", "sep", "+", "name", "return", "new_scope" ]
compose a new scope :param str scope: current scope :param str name: name of next level in scope :return the composed scope
[ "compose", "a", "new", "scope" ]
333c4ca08e758cd2194943d9904a3eda3fe43977
https://github.com/pyopenapi/pyswagger/blob/333c4ca08e758cd2194943d9904a3eda3fe43977/pyswagger/utils.py#L15-L31
7,157
pyopenapi/pyswagger
pyswagger/utils.py
nv_tuple_list_replace
def nv_tuple_list_replace(l, v): """ replace a tuple in a tuple list """ _found = False for i, x in enumerate(l): if x[0] == v[0]: l[i] = v _found = True if not _found: l.append(v)
python
def nv_tuple_list_replace(l, v): """ replace a tuple in a tuple list """ _found = False for i, x in enumerate(l): if x[0] == v[0]: l[i] = v _found = True if not _found: l.append(v)
[ "def", "nv_tuple_list_replace", "(", "l", ",", "v", ")", ":", "_found", "=", "False", "for", "i", ",", "x", "in", "enumerate", "(", "l", ")", ":", "if", "x", "[", "0", "]", "==", "v", "[", "0", "]", ":", "l", "[", "i", "]", "=", "v", "_found", "=", "True", "if", "not", "_found", ":", "l", ".", "append", "(", "v", ")" ]
replace a tuple in a tuple list
[ "replace", "a", "tuple", "in", "a", "tuple", "list" ]
333c4ca08e758cd2194943d9904a3eda3fe43977
https://github.com/pyopenapi/pyswagger/blob/333c4ca08e758cd2194943d9904a3eda3fe43977/pyswagger/utils.py#L286-L296
7,158
pyopenapi/pyswagger
pyswagger/utils.py
url_dirname
def url_dirname(url): """ Return the folder containing the '.json' file """ p = six.moves.urllib.parse.urlparse(url) for e in [private.FILE_EXT_JSON, private.FILE_EXT_YAML]: if p.path.endswith(e): return six.moves.urllib.parse.urlunparse( p[:2]+ (os.path.dirname(p.path),)+ p[3:] ) return url
python
def url_dirname(url): """ Return the folder containing the '.json' file """ p = six.moves.urllib.parse.urlparse(url) for e in [private.FILE_EXT_JSON, private.FILE_EXT_YAML]: if p.path.endswith(e): return six.moves.urllib.parse.urlunparse( p[:2]+ (os.path.dirname(p.path),)+ p[3:] ) return url
[ "def", "url_dirname", "(", "url", ")", ":", "p", "=", "six", ".", "moves", ".", "urllib", ".", "parse", ".", "urlparse", "(", "url", ")", "for", "e", "in", "[", "private", ".", "FILE_EXT_JSON", ",", "private", ".", "FILE_EXT_YAML", "]", ":", "if", "p", ".", "path", ".", "endswith", "(", "e", ")", ":", "return", "six", ".", "moves", ".", "urllib", ".", "parse", ".", "urlunparse", "(", "p", "[", ":", "2", "]", "+", "(", "os", ".", "path", ".", "dirname", "(", "p", ".", "path", ")", ",", ")", "+", "p", "[", "3", ":", "]", ")", "return", "url" ]
Return the folder containing the '.json' file
[ "Return", "the", "folder", "containing", "the", ".", "json", "file" ]
333c4ca08e758cd2194943d9904a3eda3fe43977
https://github.com/pyopenapi/pyswagger/blob/333c4ca08e758cd2194943d9904a3eda3fe43977/pyswagger/utils.py#L332-L343
7,159
pyopenapi/pyswagger
pyswagger/utils.py
url_join
def url_join(url, path): """ url version of os.path.join """ p = six.moves.urllib.parse.urlparse(url) t = None if p.path and p.path[-1] == '/': if path and path[0] == '/': path = path[1:] t = ''.join([p.path, path]) else: t = ('' if path and path[0] == '/' else '/').join([p.path, path]) return six.moves.urllib.parse.urlunparse( p[:2]+ (t,)+ # os.sep is different on windows, don't use it here. p[3:] )
python
def url_join(url, path): """ url version of os.path.join """ p = six.moves.urllib.parse.urlparse(url) t = None if p.path and p.path[-1] == '/': if path and path[0] == '/': path = path[1:] t = ''.join([p.path, path]) else: t = ('' if path and path[0] == '/' else '/').join([p.path, path]) return six.moves.urllib.parse.urlunparse( p[:2]+ (t,)+ # os.sep is different on windows, don't use it here. p[3:] )
[ "def", "url_join", "(", "url", ",", "path", ")", ":", "p", "=", "six", ".", "moves", ".", "urllib", ".", "parse", ".", "urlparse", "(", "url", ")", "t", "=", "None", "if", "p", ".", "path", "and", "p", ".", "path", "[", "-", "1", "]", "==", "'/'", ":", "if", "path", "and", "path", "[", "0", "]", "==", "'/'", ":", "path", "=", "path", "[", "1", ":", "]", "t", "=", "''", ".", "join", "(", "[", "p", ".", "path", ",", "path", "]", ")", "else", ":", "t", "=", "(", "''", "if", "path", "and", "path", "[", "0", "]", "==", "'/'", "else", "'/'", ")", ".", "join", "(", "[", "p", ".", "path", ",", "path", "]", ")", "return", "six", ".", "moves", ".", "urllib", ".", "parse", ".", "urlunparse", "(", "p", "[", ":", "2", "]", "+", "(", "t", ",", ")", "+", "# os.sep is different on windows, don't use it here.", "p", "[", "3", ":", "]", ")" ]
url version of os.path.join
[ "url", "version", "of", "os", ".", "path", ".", "join" ]
333c4ca08e758cd2194943d9904a3eda3fe43977
https://github.com/pyopenapi/pyswagger/blob/333c4ca08e758cd2194943d9904a3eda3fe43977/pyswagger/utils.py#L345-L362
7,160
pyopenapi/pyswagger
pyswagger/utils.py
derelativise_url
def derelativise_url(url): ''' Normalizes URLs, gets rid of .. and . ''' parsed = six.moves.urllib.parse.urlparse(url) newpath=[] for chunk in parsed.path[1:].split('/'): if chunk == '.': continue elif chunk == '..': # parent dir. newpath=newpath[:-1] continue # TODO: Verify this behaviour. elif _fullmatch(r'\.{3,}', chunk) is not None: # parent dir. newpath=newpath[:-1] continue newpath += [chunk] return six.moves.urllib.parse.urlunparse(parsed[:2]+('/'+('/'.join(newpath)),)+parsed[3:])
python
def derelativise_url(url): ''' Normalizes URLs, gets rid of .. and . ''' parsed = six.moves.urllib.parse.urlparse(url) newpath=[] for chunk in parsed.path[1:].split('/'): if chunk == '.': continue elif chunk == '..': # parent dir. newpath=newpath[:-1] continue # TODO: Verify this behaviour. elif _fullmatch(r'\.{3,}', chunk) is not None: # parent dir. newpath=newpath[:-1] continue newpath += [chunk] return six.moves.urllib.parse.urlunparse(parsed[:2]+('/'+('/'.join(newpath)),)+parsed[3:])
[ "def", "derelativise_url", "(", "url", ")", ":", "parsed", "=", "six", ".", "moves", ".", "urllib", ".", "parse", ".", "urlparse", "(", "url", ")", "newpath", "=", "[", "]", "for", "chunk", "in", "parsed", ".", "path", "[", "1", ":", "]", ".", "split", "(", "'/'", ")", ":", "if", "chunk", "==", "'.'", ":", "continue", "elif", "chunk", "==", "'..'", ":", "# parent dir.", "newpath", "=", "newpath", "[", ":", "-", "1", "]", "continue", "# TODO: Verify this behaviour.", "elif", "_fullmatch", "(", "r'\\.{3,}'", ",", "chunk", ")", "is", "not", "None", ":", "# parent dir.", "newpath", "=", "newpath", "[", ":", "-", "1", "]", "continue", "newpath", "+=", "[", "chunk", "]", "return", "six", ".", "moves", ".", "urllib", ".", "parse", ".", "urlunparse", "(", "parsed", "[", ":", "2", "]", "+", "(", "'/'", "+", "(", "'/'", ".", "join", "(", "newpath", ")", ")", ",", ")", "+", "parsed", "[", "3", ":", "]", ")" ]
Normalizes URLs, gets rid of .. and .
[ "Normalizes", "URLs", "gets", "rid", "of", "..", "and", "." ]
333c4ca08e758cd2194943d9904a3eda3fe43977
https://github.com/pyopenapi/pyswagger/blob/333c4ca08e758cd2194943d9904a3eda3fe43977/pyswagger/utils.py#L405-L424
7,161
pyopenapi/pyswagger
pyswagger/utils.py
get_swagger_version
def get_swagger_version(obj): """ get swagger version from loaded json """ if isinstance(obj, dict): if 'swaggerVersion' in obj: return obj['swaggerVersion'] elif 'swagger' in obj: return obj['swagger'] return None else: # should be an instance of BaseObj return obj.swaggerVersion if hasattr(obj, 'swaggerVersion') else obj.swagger
python
def get_swagger_version(obj): """ get swagger version from loaded json """ if isinstance(obj, dict): if 'swaggerVersion' in obj: return obj['swaggerVersion'] elif 'swagger' in obj: return obj['swagger'] return None else: # should be an instance of BaseObj return obj.swaggerVersion if hasattr(obj, 'swaggerVersion') else obj.swagger
[ "def", "get_swagger_version", "(", "obj", ")", ":", "if", "isinstance", "(", "obj", ",", "dict", ")", ":", "if", "'swaggerVersion'", "in", "obj", ":", "return", "obj", "[", "'swaggerVersion'", "]", "elif", "'swagger'", "in", "obj", ":", "return", "obj", "[", "'swagger'", "]", "return", "None", "else", ":", "# should be an instance of BaseObj", "return", "obj", ".", "swaggerVersion", "if", "hasattr", "(", "obj", ",", "'swaggerVersion'", ")", "else", "obj", ".", "swagger" ]
get swagger version from loaded json
[ "get", "swagger", "version", "from", "loaded", "json" ]
333c4ca08e758cd2194943d9904a3eda3fe43977
https://github.com/pyopenapi/pyswagger/blob/333c4ca08e758cd2194943d9904a3eda3fe43977/pyswagger/utils.py#L426-L437
7,162
pyopenapi/pyswagger
pyswagger/utils.py
walk
def walk(start, ofn, cyc=None): """ Non recursive DFS to detect cycles :param start: start vertex in graph :param ofn: function to get the list of outgoing edges of a vertex :param cyc: list of existing cycles, cycles are represented in a list started with minimum vertex. :return: cycles :rtype: list of lists """ ctx, stk = {}, [start] cyc = [] if cyc == None else cyc while len(stk): top = stk[-1] if top not in ctx: ctx.update({top:list(ofn(top))}) if len(ctx[top]): n = ctx[top][0] if n in stk: # cycles found, # normalize the representation of cycles, # start from the smallest vertex, ex. # 4 -> 5 -> 2 -> 7 -> 9 would produce # (2, 7, 9, 4, 5) nc = stk[stk.index(n):] ni = nc.index(min(nc)) nc = nc[ni:] + nc[:ni] + [min(nc)] if nc not in cyc: cyc.append(nc) ctx[top].pop(0) else: stk.append(n) else: ctx.pop(top) stk.pop() if len(stk): ctx[stk[-1]].remove(top) return cyc
python
def walk(start, ofn, cyc=None): """ Non recursive DFS to detect cycles :param start: start vertex in graph :param ofn: function to get the list of outgoing edges of a vertex :param cyc: list of existing cycles, cycles are represented in a list started with minimum vertex. :return: cycles :rtype: list of lists """ ctx, stk = {}, [start] cyc = [] if cyc == None else cyc while len(stk): top = stk[-1] if top not in ctx: ctx.update({top:list(ofn(top))}) if len(ctx[top]): n = ctx[top][0] if n in stk: # cycles found, # normalize the representation of cycles, # start from the smallest vertex, ex. # 4 -> 5 -> 2 -> 7 -> 9 would produce # (2, 7, 9, 4, 5) nc = stk[stk.index(n):] ni = nc.index(min(nc)) nc = nc[ni:] + nc[:ni] + [min(nc)] if nc not in cyc: cyc.append(nc) ctx[top].pop(0) else: stk.append(n) else: ctx.pop(top) stk.pop() if len(stk): ctx[stk[-1]].remove(top) return cyc
[ "def", "walk", "(", "start", ",", "ofn", ",", "cyc", "=", "None", ")", ":", "ctx", ",", "stk", "=", "{", "}", ",", "[", "start", "]", "cyc", "=", "[", "]", "if", "cyc", "==", "None", "else", "cyc", "while", "len", "(", "stk", ")", ":", "top", "=", "stk", "[", "-", "1", "]", "if", "top", "not", "in", "ctx", ":", "ctx", ".", "update", "(", "{", "top", ":", "list", "(", "ofn", "(", "top", ")", ")", "}", ")", "if", "len", "(", "ctx", "[", "top", "]", ")", ":", "n", "=", "ctx", "[", "top", "]", "[", "0", "]", "if", "n", "in", "stk", ":", "# cycles found,", "# normalize the representation of cycles,", "# start from the smallest vertex, ex.", "# 4 -> 5 -> 2 -> 7 -> 9 would produce", "# (2, 7, 9, 4, 5)", "nc", "=", "stk", "[", "stk", ".", "index", "(", "n", ")", ":", "]", "ni", "=", "nc", ".", "index", "(", "min", "(", "nc", ")", ")", "nc", "=", "nc", "[", "ni", ":", "]", "+", "nc", "[", ":", "ni", "]", "+", "[", "min", "(", "nc", ")", "]", "if", "nc", "not", "in", "cyc", ":", "cyc", ".", "append", "(", "nc", ")", "ctx", "[", "top", "]", ".", "pop", "(", "0", ")", "else", ":", "stk", ".", "append", "(", "n", ")", "else", ":", "ctx", ".", "pop", "(", "top", ")", "stk", ".", "pop", "(", ")", "if", "len", "(", "stk", ")", ":", "ctx", "[", "stk", "[", "-", "1", "]", "]", ".", "remove", "(", "top", ")", "return", "cyc" ]
Non recursive DFS to detect cycles :param start: start vertex in graph :param ofn: function to get the list of outgoing edges of a vertex :param cyc: list of existing cycles, cycles are represented in a list started with minimum vertex. :return: cycles :rtype: list of lists
[ "Non", "recursive", "DFS", "to", "detect", "cycles" ]
333c4ca08e758cd2194943d9904a3eda3fe43977
https://github.com/pyopenapi/pyswagger/blob/333c4ca08e758cd2194943d9904a3eda3fe43977/pyswagger/utils.py#L439-L480
7,163
pyopenapi/pyswagger
pyswagger/scanner/v1_2/validate.py
Validate._validate_param
def _validate_param(self, path, obj, _): """ validate option combination of Parameter object """ errs = [] if obj.allowMultiple: if not obj.paramType in ('path', 'query', 'header'): errs.append('allowMultiple should be applied on path, header, or query parameters') if obj.type == 'array': errs.append('array Type with allowMultiple is not supported.') if obj.paramType == 'body' and obj.name not in ('', 'body'): errs.append('body parameter with invalid name: {0}'.format(obj.name)) if obj.type == 'File': if obj.paramType != 'form': errs.append('File parameter should be form type: {0}'.format(obj.name)) if 'multipart/form-data' not in obj._parent_.consumes: errs.append('File parameter should consume multipart/form-data: {0}'.format(obj.name)) if obj.type == 'void': errs.append('void is only allowed in Operation object.') return path, obj.__class__.__name__, errs
python
def _validate_param(self, path, obj, _): """ validate option combination of Parameter object """ errs = [] if obj.allowMultiple: if not obj.paramType in ('path', 'query', 'header'): errs.append('allowMultiple should be applied on path, header, or query parameters') if obj.type == 'array': errs.append('array Type with allowMultiple is not supported.') if obj.paramType == 'body' and obj.name not in ('', 'body'): errs.append('body parameter with invalid name: {0}'.format(obj.name)) if obj.type == 'File': if obj.paramType != 'form': errs.append('File parameter should be form type: {0}'.format(obj.name)) if 'multipart/form-data' not in obj._parent_.consumes: errs.append('File parameter should consume multipart/form-data: {0}'.format(obj.name)) if obj.type == 'void': errs.append('void is only allowed in Operation object.') return path, obj.__class__.__name__, errs
[ "def", "_validate_param", "(", "self", ",", "path", ",", "obj", ",", "_", ")", ":", "errs", "=", "[", "]", "if", "obj", ".", "allowMultiple", ":", "if", "not", "obj", ".", "paramType", "in", "(", "'path'", ",", "'query'", ",", "'header'", ")", ":", "errs", ".", "append", "(", "'allowMultiple should be applied on path, header, or query parameters'", ")", "if", "obj", ".", "type", "==", "'array'", ":", "errs", ".", "append", "(", "'array Type with allowMultiple is not supported.'", ")", "if", "obj", ".", "paramType", "==", "'body'", "and", "obj", ".", "name", "not", "in", "(", "''", ",", "'body'", ")", ":", "errs", ".", "append", "(", "'body parameter with invalid name: {0}'", ".", "format", "(", "obj", ".", "name", ")", ")", "if", "obj", ".", "type", "==", "'File'", ":", "if", "obj", ".", "paramType", "!=", "'form'", ":", "errs", ".", "append", "(", "'File parameter should be form type: {0}'", ".", "format", "(", "obj", ".", "name", ")", ")", "if", "'multipart/form-data'", "not", "in", "obj", ".", "_parent_", ".", "consumes", ":", "errs", ".", "append", "(", "'File parameter should consume multipart/form-data: {0}'", ".", "format", "(", "obj", ".", "name", ")", ")", "if", "obj", ".", "type", "==", "'void'", ":", "errs", ".", "append", "(", "'void is only allowed in Operation object.'", ")", "return", "path", ",", "obj", ".", "__class__", ".", "__name__", ",", "errs" ]
validate option combination of Parameter object
[ "validate", "option", "combination", "of", "Parameter", "object" ]
333c4ca08e758cd2194943d9904a3eda3fe43977
https://github.com/pyopenapi/pyswagger/blob/333c4ca08e758cd2194943d9904a3eda3fe43977/pyswagger/scanner/v1_2/validate.py#L53-L75
7,164
pyopenapi/pyswagger
pyswagger/scanner/v1_2/validate.py
Validate._validate_items
def _validate_items(self, path, obj, _): """ validate option combination of Property object """ errs = [] if obj.type == 'void': errs.append('void is only allowed in Operation object.') return path, obj.__class__.__name__, errs
python
def _validate_items(self, path, obj, _): """ validate option combination of Property object """ errs = [] if obj.type == 'void': errs.append('void is only allowed in Operation object.') return path, obj.__class__.__name__, errs
[ "def", "_validate_items", "(", "self", ",", "path", ",", "obj", ",", "_", ")", ":", "errs", "=", "[", "]", "if", "obj", ".", "type", "==", "'void'", ":", "errs", ".", "append", "(", "'void is only allowed in Operation object.'", ")", "return", "path", ",", "obj", ".", "__class__", ".", "__name__", ",", "errs" ]
validate option combination of Property object
[ "validate", "option", "combination", "of", "Property", "object" ]
333c4ca08e758cd2194943d9904a3eda3fe43977
https://github.com/pyopenapi/pyswagger/blob/333c4ca08e758cd2194943d9904a3eda3fe43977/pyswagger/scanner/v1_2/validate.py#L88-L95
7,165
pyopenapi/pyswagger
pyswagger/scanner/v1_2/validate.py
Validate._validate_auth
def _validate_auth(self, path, obj, _): """ validate that apiKey and oauth2 requirements """ errs = [] if obj.type == 'apiKey': if not obj.passAs: errs.append('need "passAs" for apiKey') if not obj.keyname: errs.append('need "keyname" for apiKey') elif obj.type == 'oauth2': if not obj.grantTypes: errs.append('need "grantTypes" for oauth2') return path, obj.__class__.__name__, errs
python
def _validate_auth(self, path, obj, _): """ validate that apiKey and oauth2 requirements """ errs = [] if obj.type == 'apiKey': if not obj.passAs: errs.append('need "passAs" for apiKey') if not obj.keyname: errs.append('need "keyname" for apiKey') elif obj.type == 'oauth2': if not obj.grantTypes: errs.append('need "grantTypes" for oauth2') return path, obj.__class__.__name__, errs
[ "def", "_validate_auth", "(", "self", ",", "path", ",", "obj", ",", "_", ")", ":", "errs", "=", "[", "]", "if", "obj", ".", "type", "==", "'apiKey'", ":", "if", "not", "obj", ".", "passAs", ":", "errs", ".", "append", "(", "'need \"passAs\" for apiKey'", ")", "if", "not", "obj", ".", "keyname", ":", "errs", ".", "append", "(", "'need \"keyname\" for apiKey'", ")", "elif", "obj", ".", "type", "==", "'oauth2'", ":", "if", "not", "obj", ".", "grantTypes", ":", "errs", ".", "append", "(", "'need \"grantTypes\" for oauth2'", ")", "return", "path", ",", "obj", ".", "__class__", ".", "__name__", ",", "errs" ]
validate that apiKey and oauth2 requirements
[ "validate", "that", "apiKey", "and", "oauth2", "requirements" ]
333c4ca08e758cd2194943d9904a3eda3fe43977
https://github.com/pyopenapi/pyswagger/blob/333c4ca08e758cd2194943d9904a3eda3fe43977/pyswagger/scanner/v1_2/validate.py#L98-L112
7,166
pyopenapi/pyswagger
pyswagger/scanner/v1_2/validate.py
Validate._validate_granttype
def _validate_granttype(self, path, obj, _): """ make sure either implicit or authorization_code is defined """ errs = [] if not obj.implicit and not obj.authorization_code: errs.append('Either implicit or authorization_code should be defined.') return path, obj.__class__.__name__, errs
python
def _validate_granttype(self, path, obj, _): """ make sure either implicit or authorization_code is defined """ errs = [] if not obj.implicit and not obj.authorization_code: errs.append('Either implicit or authorization_code should be defined.') return path, obj.__class__.__name__, errs
[ "def", "_validate_granttype", "(", "self", ",", "path", ",", "obj", ",", "_", ")", ":", "errs", "=", "[", "]", "if", "not", "obj", ".", "implicit", "and", "not", "obj", ".", "authorization_code", ":", "errs", ".", "append", "(", "'Either implicit or authorization_code should be defined.'", ")", "return", "path", ",", "obj", ".", "__class__", ".", "__name__", ",", "errs" ]
make sure either implicit or authorization_code is defined
[ "make", "sure", "either", "implicit", "or", "authorization_code", "is", "defined" ]
333c4ca08e758cd2194943d9904a3eda3fe43977
https://github.com/pyopenapi/pyswagger/blob/333c4ca08e758cd2194943d9904a3eda3fe43977/pyswagger/scanner/v1_2/validate.py#L115-L122
7,167
pyopenapi/pyswagger
pyswagger/scanner/v1_2/validate.py
Validate._validate_auths
def _validate_auths(self, path, obj, app): """ make sure that apiKey and basicAuth are empty list in Operation object. """ errs = [] for k, v in six.iteritems(obj.authorizations or {}): if k not in app.raw.authorizations: errs.append('auth {0} not found in resource list'.format(k)) if app.raw.authorizations[k].type in ('basicAuth', 'apiKey') and v != []: errs.append('auth {0} should be an empty list'.format(k)) return path, obj.__class__.__name__, errs
python
def _validate_auths(self, path, obj, app): """ make sure that apiKey and basicAuth are empty list in Operation object. """ errs = [] for k, v in six.iteritems(obj.authorizations or {}): if k not in app.raw.authorizations: errs.append('auth {0} not found in resource list'.format(k)) if app.raw.authorizations[k].type in ('basicAuth', 'apiKey') and v != []: errs.append('auth {0} should be an empty list'.format(k)) return path, obj.__class__.__name__, errs
[ "def", "_validate_auths", "(", "self", ",", "path", ",", "obj", ",", "app", ")", ":", "errs", "=", "[", "]", "for", "k", ",", "v", "in", "six", ".", "iteritems", "(", "obj", ".", "authorizations", "or", "{", "}", ")", ":", "if", "k", "not", "in", "app", ".", "raw", ".", "authorizations", ":", "errs", ".", "append", "(", "'auth {0} not found in resource list'", ".", "format", "(", "k", ")", ")", "if", "app", ".", "raw", ".", "authorizations", "[", "k", "]", ".", "type", "in", "(", "'basicAuth'", ",", "'apiKey'", ")", "and", "v", "!=", "[", "]", ":", "errs", ".", "append", "(", "'auth {0} should be an empty list'", ".", "format", "(", "k", ")", ")", "return", "path", ",", "obj", ".", "__class__", ".", "__name__", ",", "errs" ]
make sure that apiKey and basicAuth are empty list in Operation object.
[ "make", "sure", "that", "apiKey", "and", "basicAuth", "are", "empty", "list", "in", "Operation", "object", "." ]
333c4ca08e758cd2194943d9904a3eda3fe43977
https://github.com/pyopenapi/pyswagger/blob/333c4ca08e758cd2194943d9904a3eda3fe43977/pyswagger/scanner/v1_2/validate.py#L125-L138
7,168
pyopenapi/pyswagger
pyswagger/scan.py
default_tree_traversal
def default_tree_traversal(root, leaves): """ default tree traversal """ objs = [('#', root)] while len(objs) > 0: path, obj = objs.pop() # name of child are json-pointer encoded, we don't have # to encode it again. if obj.__class__ not in leaves: objs.extend(map(lambda i: (path + '/' + i[0],) + (i[1],), six.iteritems(obj._children_))) # the path we expose here follows JsonPointer described here # http://tools.ietf.org/html/draft-ietf-appsawg-json-pointer-07 yield path, obj
python
def default_tree_traversal(root, leaves): """ default tree traversal """ objs = [('#', root)] while len(objs) > 0: path, obj = objs.pop() # name of child are json-pointer encoded, we don't have # to encode it again. if obj.__class__ not in leaves: objs.extend(map(lambda i: (path + '/' + i[0],) + (i[1],), six.iteritems(obj._children_))) # the path we expose here follows JsonPointer described here # http://tools.ietf.org/html/draft-ietf-appsawg-json-pointer-07 yield path, obj
[ "def", "default_tree_traversal", "(", "root", ",", "leaves", ")", ":", "objs", "=", "[", "(", "'#'", ",", "root", ")", "]", "while", "len", "(", "objs", ")", ">", "0", ":", "path", ",", "obj", "=", "objs", ".", "pop", "(", ")", "# name of child are json-pointer encoded, we don't have", "# to encode it again.", "if", "obj", ".", "__class__", "not", "in", "leaves", ":", "objs", ".", "extend", "(", "map", "(", "lambda", "i", ":", "(", "path", "+", "'/'", "+", "i", "[", "0", "]", ",", ")", "+", "(", "i", "[", "1", "]", ",", ")", ",", "six", ".", "iteritems", "(", "obj", ".", "_children_", ")", ")", ")", "# the path we expose here follows JsonPointer described here", "# http://tools.ietf.org/html/draft-ietf-appsawg-json-pointer-07", "yield", "path", ",", "obj" ]
default tree traversal
[ "default", "tree", "traversal" ]
333c4ca08e758cd2194943d9904a3eda3fe43977
https://github.com/pyopenapi/pyswagger/blob/333c4ca08e758cd2194943d9904a3eda3fe43977/pyswagger/scan.py#L6-L19
7,169
pyopenapi/pyswagger
pyswagger/primitives/render.py
Renderer.render_all
def render_all(self, op, exclude=[], opt=None): """ render a set of parameter for an Operation :param op Operation: the swagger spec object :param opt dict: render option :return: a set of parameters that can be passed to Operation.__call__ :rtype: dict """ opt = self.default() if opt == None else opt if not isinstance(op, Operation): raise ValueError('Not a Operation: {0}'.format(op)) if not isinstance(opt, dict): raise ValueError('Not a dict: {0}'.format(opt)) template = opt['parameter_template'] max_p = opt['max_parameter'] out = {} for p in op.parameters: if p.name in exclude: continue if p.name in template: out.update({p.name: template[p.name]}) continue if not max_p and not p.required: if random.randint(0, 1) == 0 or opt['minimal_parameter']: continue out.update({p.name: self.render(p, opt=opt)}) return out
python
def render_all(self, op, exclude=[], opt=None): """ render a set of parameter for an Operation :param op Operation: the swagger spec object :param opt dict: render option :return: a set of parameters that can be passed to Operation.__call__ :rtype: dict """ opt = self.default() if opt == None else opt if not isinstance(op, Operation): raise ValueError('Not a Operation: {0}'.format(op)) if not isinstance(opt, dict): raise ValueError('Not a dict: {0}'.format(opt)) template = opt['parameter_template'] max_p = opt['max_parameter'] out = {} for p in op.parameters: if p.name in exclude: continue if p.name in template: out.update({p.name: template[p.name]}) continue if not max_p and not p.required: if random.randint(0, 1) == 0 or opt['minimal_parameter']: continue out.update({p.name: self.render(p, opt=opt)}) return out
[ "def", "render_all", "(", "self", ",", "op", ",", "exclude", "=", "[", "]", ",", "opt", "=", "None", ")", ":", "opt", "=", "self", ".", "default", "(", ")", "if", "opt", "==", "None", "else", "opt", "if", "not", "isinstance", "(", "op", ",", "Operation", ")", ":", "raise", "ValueError", "(", "'Not a Operation: {0}'", ".", "format", "(", "op", ")", ")", "if", "not", "isinstance", "(", "opt", ",", "dict", ")", ":", "raise", "ValueError", "(", "'Not a dict: {0}'", ".", "format", "(", "opt", ")", ")", "template", "=", "opt", "[", "'parameter_template'", "]", "max_p", "=", "opt", "[", "'max_parameter'", "]", "out", "=", "{", "}", "for", "p", "in", "op", ".", "parameters", ":", "if", "p", ".", "name", "in", "exclude", ":", "continue", "if", "p", ".", "name", "in", "template", ":", "out", ".", "update", "(", "{", "p", ".", "name", ":", "template", "[", "p", ".", "name", "]", "}", ")", "continue", "if", "not", "max_p", "and", "not", "p", ".", "required", ":", "if", "random", ".", "randint", "(", "0", ",", "1", ")", "==", "0", "or", "opt", "[", "'minimal_parameter'", "]", ":", "continue", "out", ".", "update", "(", "{", "p", ".", "name", ":", "self", ".", "render", "(", "p", ",", "opt", "=", "opt", ")", "}", ")", "return", "out" ]
render a set of parameter for an Operation :param op Operation: the swagger spec object :param opt dict: render option :return: a set of parameters that can be passed to Operation.__call__ :rtype: dict
[ "render", "a", "set", "of", "parameter", "for", "an", "Operation" ]
333c4ca08e758cd2194943d9904a3eda3fe43977
https://github.com/pyopenapi/pyswagger/blob/333c4ca08e758cd2194943d9904a3eda3fe43977/pyswagger/primitives/render.py#L287-L314
7,170
pyopenapi/pyswagger
pyswagger/io.py
Request._prepare_forms
def _prepare_forms(self): """ private function to prepare content for paramType=form """ content_type = 'application/x-www-form-urlencoded' if self.__op.consumes and content_type not in self.__op.consumes: raise errs.SchemaError('content type {0} does not present in {1}'.format(content_type, self.__op.consumes)) return content_type, six.moves.urllib.parse.urlencode(self.__p['formData'])
python
def _prepare_forms(self): """ private function to prepare content for paramType=form """ content_type = 'application/x-www-form-urlencoded' if self.__op.consumes and content_type not in self.__op.consumes: raise errs.SchemaError('content type {0} does not present in {1}'.format(content_type, self.__op.consumes)) return content_type, six.moves.urllib.parse.urlencode(self.__p['formData'])
[ "def", "_prepare_forms", "(", "self", ")", ":", "content_type", "=", "'application/x-www-form-urlencoded'", "if", "self", ".", "__op", ".", "consumes", "and", "content_type", "not", "in", "self", ".", "__op", ".", "consumes", ":", "raise", "errs", ".", "SchemaError", "(", "'content type {0} does not present in {1}'", ".", "format", "(", "content_type", ",", "self", ".", "__op", ".", "consumes", ")", ")", "return", "content_type", ",", "six", ".", "moves", ".", "urllib", ".", "parse", ".", "urlencode", "(", "self", ".", "__p", "[", "'formData'", "]", ")" ]
private function to prepare content for paramType=form
[ "private", "function", "to", "prepare", "content", "for", "paramType", "=", "form" ]
333c4ca08e758cd2194943d9904a3eda3fe43977
https://github.com/pyopenapi/pyswagger/blob/333c4ca08e758cd2194943d9904a3eda3fe43977/pyswagger/io.py#L56-L63
7,171
pyopenapi/pyswagger
pyswagger/io.py
Request._prepare_body
def _prepare_body(self): """ private function to prepare content for paramType=body """ content_type = self.__consume if not content_type: content_type = self.__op.consumes[0] if self.__op.consumes else 'application/json' if self.__op.consumes and content_type not in self.__op.consumes: raise errs.SchemaError('content type {0} does not present in {1}'.format(content_type, self.__op.consumes)) # according to spec, payload should be one and only, # so we just return the first value in dict. for parameter in self.__op.parameters: parameter = final(parameter) if getattr(parameter, 'in') == 'body': schema = deref(parameter.schema) _type = schema.type _format = schema.format name = schema.name body = self.__p['body'][parameter.name] return content_type, self.__op._mime_codec.marshal(content_type, body, _type=_type, _format=_format, name=name) return None, None
python
def _prepare_body(self): """ private function to prepare content for paramType=body """ content_type = self.__consume if not content_type: content_type = self.__op.consumes[0] if self.__op.consumes else 'application/json' if self.__op.consumes and content_type not in self.__op.consumes: raise errs.SchemaError('content type {0} does not present in {1}'.format(content_type, self.__op.consumes)) # according to spec, payload should be one and only, # so we just return the first value in dict. for parameter in self.__op.parameters: parameter = final(parameter) if getattr(parameter, 'in') == 'body': schema = deref(parameter.schema) _type = schema.type _format = schema.format name = schema.name body = self.__p['body'][parameter.name] return content_type, self.__op._mime_codec.marshal(content_type, body, _type=_type, _format=_format, name=name) return None, None
[ "def", "_prepare_body", "(", "self", ")", ":", "content_type", "=", "self", ".", "__consume", "if", "not", "content_type", ":", "content_type", "=", "self", ".", "__op", ".", "consumes", "[", "0", "]", "if", "self", ".", "__op", ".", "consumes", "else", "'application/json'", "if", "self", ".", "__op", ".", "consumes", "and", "content_type", "not", "in", "self", ".", "__op", ".", "consumes", ":", "raise", "errs", ".", "SchemaError", "(", "'content type {0} does not present in {1}'", ".", "format", "(", "content_type", ",", "self", ".", "__op", ".", "consumes", ")", ")", "# according to spec, payload should be one and only,", "# so we just return the first value in dict.", "for", "parameter", "in", "self", ".", "__op", ".", "parameters", ":", "parameter", "=", "final", "(", "parameter", ")", "if", "getattr", "(", "parameter", ",", "'in'", ")", "==", "'body'", ":", "schema", "=", "deref", "(", "parameter", ".", "schema", ")", "_type", "=", "schema", ".", "type", "_format", "=", "schema", ".", "format", "name", "=", "schema", ".", "name", "body", "=", "self", ".", "__p", "[", "'body'", "]", "[", "parameter", ".", "name", "]", "return", "content_type", ",", "self", ".", "__op", ".", "_mime_codec", ".", "marshal", "(", "content_type", ",", "body", ",", "_type", "=", "_type", ",", "_format", "=", "_format", ",", "name", "=", "name", ")", "return", "None", ",", "None" ]
private function to prepare content for paramType=body
[ "private", "function", "to", "prepare", "content", "for", "paramType", "=", "body" ]
333c4ca08e758cd2194943d9904a3eda3fe43977
https://github.com/pyopenapi/pyswagger/blob/333c4ca08e758cd2194943d9904a3eda3fe43977/pyswagger/io.py#L65-L85
7,172
pyopenapi/pyswagger
pyswagger/io.py
Request._prepare_files
def _prepare_files(self, encoding): """ private function to prepare content for paramType=form with File """ content_type = 'multipart/form-data' if self.__op.consumes and content_type not in self.__op.consumes: raise errs.SchemaError('content type {0} does not present in {1}'.format(content_type, self.__op.consumes)) boundary = uuid4().hex content_type += '; boundary={0}' content_type = content_type.format(boundary) # init stream body = io.BytesIO() w = codecs.getwriter(encoding) def append(name, obj): body.write(six.b('--{0}\r\n'.format(boundary))) # header w(body).write('Content-Disposition: form-data; name="{0}"; filename="{1}"'.format(name, obj.filename)) body.write(six.b('\r\n')) if 'Content-Type' in obj.header: w(body).write('Content-Type: {0}'.format(obj.header['Content-Type'])) body.write(six.b('\r\n')) if 'Content-Transfer-Encoding' in obj.header: w(body).write('Content-Transfer-Encoding: {0}'.format(obj.header['Content-Transfer-Encoding'])) body.write(six.b('\r\n')) body.write(six.b('\r\n')) # body if not obj.data: with open(obj.filename, 'rb') as f: body.write(f.read()) else: data = obj.data.read() if isinstance(data, six.text_type): w(body).write(data) else: body.write(data) body.write(six.b('\r\n')) for k, v in self.__p['formData']: body.write(six.b('--{0}\r\n'.format(boundary))) w(body).write('Content-Disposition: form-data; name="{0}"'.format(k)) body.write(six.b('\r\n')) body.write(six.b('\r\n')) w(body).write(v) body.write(six.b('\r\n')) # begin of file section for k, v in six.iteritems(self.__p['file']): if isinstance(v, list): for vv in v: append(k, vv) else: append(k, v) # final boundary body.write(six.b('--{0}--\r\n'.format(boundary))) return content_type, body.getvalue()
python
def _prepare_files(self, encoding): """ private function to prepare content for paramType=form with File """ content_type = 'multipart/form-data' if self.__op.consumes and content_type not in self.__op.consumes: raise errs.SchemaError('content type {0} does not present in {1}'.format(content_type, self.__op.consumes)) boundary = uuid4().hex content_type += '; boundary={0}' content_type = content_type.format(boundary) # init stream body = io.BytesIO() w = codecs.getwriter(encoding) def append(name, obj): body.write(six.b('--{0}\r\n'.format(boundary))) # header w(body).write('Content-Disposition: form-data; name="{0}"; filename="{1}"'.format(name, obj.filename)) body.write(six.b('\r\n')) if 'Content-Type' in obj.header: w(body).write('Content-Type: {0}'.format(obj.header['Content-Type'])) body.write(six.b('\r\n')) if 'Content-Transfer-Encoding' in obj.header: w(body).write('Content-Transfer-Encoding: {0}'.format(obj.header['Content-Transfer-Encoding'])) body.write(six.b('\r\n')) body.write(six.b('\r\n')) # body if not obj.data: with open(obj.filename, 'rb') as f: body.write(f.read()) else: data = obj.data.read() if isinstance(data, six.text_type): w(body).write(data) else: body.write(data) body.write(six.b('\r\n')) for k, v in self.__p['formData']: body.write(six.b('--{0}\r\n'.format(boundary))) w(body).write('Content-Disposition: form-data; name="{0}"'.format(k)) body.write(six.b('\r\n')) body.write(six.b('\r\n')) w(body).write(v) body.write(six.b('\r\n')) # begin of file section for k, v in six.iteritems(self.__p['file']): if isinstance(v, list): for vv in v: append(k, vv) else: append(k, v) # final boundary body.write(six.b('--{0}--\r\n'.format(boundary))) return content_type, body.getvalue()
[ "def", "_prepare_files", "(", "self", ",", "encoding", ")", ":", "content_type", "=", "'multipart/form-data'", "if", "self", ".", "__op", ".", "consumes", "and", "content_type", "not", "in", "self", ".", "__op", ".", "consumes", ":", "raise", "errs", ".", "SchemaError", "(", "'content type {0} does not present in {1}'", ".", "format", "(", "content_type", ",", "self", ".", "__op", ".", "consumes", ")", ")", "boundary", "=", "uuid4", "(", ")", ".", "hex", "content_type", "+=", "'; boundary={0}'", "content_type", "=", "content_type", ".", "format", "(", "boundary", ")", "# init stream", "body", "=", "io", ".", "BytesIO", "(", ")", "w", "=", "codecs", ".", "getwriter", "(", "encoding", ")", "def", "append", "(", "name", ",", "obj", ")", ":", "body", ".", "write", "(", "six", ".", "b", "(", "'--{0}\\r\\n'", ".", "format", "(", "boundary", ")", ")", ")", "# header", "w", "(", "body", ")", ".", "write", "(", "'Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"'", ".", "format", "(", "name", ",", "obj", ".", "filename", ")", ")", "body", ".", "write", "(", "six", ".", "b", "(", "'\\r\\n'", ")", ")", "if", "'Content-Type'", "in", "obj", ".", "header", ":", "w", "(", "body", ")", ".", "write", "(", "'Content-Type: {0}'", ".", "format", "(", "obj", ".", "header", "[", "'Content-Type'", "]", ")", ")", "body", ".", "write", "(", "six", ".", "b", "(", "'\\r\\n'", ")", ")", "if", "'Content-Transfer-Encoding'", "in", "obj", ".", "header", ":", "w", "(", "body", ")", ".", "write", "(", "'Content-Transfer-Encoding: {0}'", ".", "format", "(", "obj", ".", "header", "[", "'Content-Transfer-Encoding'", "]", ")", ")", "body", ".", "write", "(", "six", ".", "b", "(", "'\\r\\n'", ")", ")", "body", ".", "write", "(", "six", ".", "b", "(", "'\\r\\n'", ")", ")", "# body", "if", "not", "obj", ".", "data", ":", "with", "open", "(", "obj", ".", "filename", ",", "'rb'", ")", "as", "f", ":", "body", ".", "write", "(", "f", ".", "read", "(", ")", ")", "else", ":", "data", "=", "obj", ".", "data", ".", "read", "(", ")", "if", "isinstance", "(", "data", ",", "six", ".", "text_type", ")", ":", "w", "(", "body", ")", ".", "write", "(", "data", ")", "else", ":", "body", ".", "write", "(", "data", ")", "body", ".", "write", "(", "six", ".", "b", "(", "'\\r\\n'", ")", ")", "for", "k", ",", "v", "in", "self", ".", "__p", "[", "'formData'", "]", ":", "body", ".", "write", "(", "six", ".", "b", "(", "'--{0}\\r\\n'", ".", "format", "(", "boundary", ")", ")", ")", "w", "(", "body", ")", ".", "write", "(", "'Content-Disposition: form-data; name=\"{0}\"'", ".", "format", "(", "k", ")", ")", "body", ".", "write", "(", "six", ".", "b", "(", "'\\r\\n'", ")", ")", "body", ".", "write", "(", "six", ".", "b", "(", "'\\r\\n'", ")", ")", "w", "(", "body", ")", ".", "write", "(", "v", ")", "body", ".", "write", "(", "six", ".", "b", "(", "'\\r\\n'", ")", ")", "# begin of file section", "for", "k", ",", "v", "in", "six", ".", "iteritems", "(", "self", ".", "__p", "[", "'file'", "]", ")", ":", "if", "isinstance", "(", "v", ",", "list", ")", ":", "for", "vv", "in", "v", ":", "append", "(", "k", ",", "vv", ")", "else", ":", "append", "(", "k", ",", "v", ")", "# final boundary", "body", ".", "write", "(", "six", ".", "b", "(", "'--{0}--\\r\\n'", ".", "format", "(", "boundary", ")", ")", ")", "return", "content_type", ",", "body", ".", "getvalue", "(", ")" ]
private function to prepare content for paramType=form with File
[ "private", "function", "to", "prepare", "content", "for", "paramType", "=", "form", "with", "File" ]
333c4ca08e758cd2194943d9904a3eda3fe43977
https://github.com/pyopenapi/pyswagger/blob/333c4ca08e758cd2194943d9904a3eda3fe43977/pyswagger/io.py#L87-L151
7,173
pyopenapi/pyswagger
pyswagger/io.py
Request.prepare
def prepare(self, scheme='http', handle_files=True, encoding='utf-8'): """ make this request ready for Clients :param str scheme: scheme used in this request :param bool handle_files: False to skip multipart/form-data encoding :param str encoding: encoding for body content. :rtype: Request """ if isinstance(scheme, list): if self.__scheme is None: scheme = scheme.pop() else: if self.__scheme in scheme: scheme = self.__scheme else: raise Exception('preferred scheme:{} is not supported by the client or spec:{}'.format(self.__scheme, scheme)) elif not isinstance(scheme, six.string_types): raise ValueError('"scheme" should be a list or string') # combine path parameters into path # TODO: 'dot' is allowed in swagger, but it won't work in python-format path_params = {} for k, v in six.iteritems(self.__p['path']): path_params[k] = six.moves.urllib.parse.quote_plus(v) self.__path = self.__path.format(**path_params) # combine path parameters into url self.__url = ''.join([scheme, ':', self.__url.format(**path_params)]) # header parameters self.__header.update(self.__p['header']) # update data parameter content_type = None if self.__p['file']: if handle_files: content_type, self.__data = self._prepare_files(encoding) else: # client that can encode multipart/form-data, should # access form-data via data property and file from file # property. # only form data can be carried along with files, self.__data = self.__p['formData'] elif self.__p['formData']: content_type, self.__data = self._prepare_forms() elif self.__p['body']: content_type, self.__data = self._prepare_body() else: self.__data = None if content_type: self.__header.update({'Content-Type': content_type}) accept = self.__produce if not accept and self.__op.produces: accept = self.__op.produces[0] if accept: if self.__op.produces and accept not in self.__op.produces: raise errs.SchemaError('accept {0} does not present in {1}'.format(accept, self.__op.produces)) self.__header.update({'Accept': accept}) return self
python
def prepare(self, scheme='http', handle_files=True, encoding='utf-8'): """ make this request ready for Clients :param str scheme: scheme used in this request :param bool handle_files: False to skip multipart/form-data encoding :param str encoding: encoding for body content. :rtype: Request """ if isinstance(scheme, list): if self.__scheme is None: scheme = scheme.pop() else: if self.__scheme in scheme: scheme = self.__scheme else: raise Exception('preferred scheme:{} is not supported by the client or spec:{}'.format(self.__scheme, scheme)) elif not isinstance(scheme, six.string_types): raise ValueError('"scheme" should be a list or string') # combine path parameters into path # TODO: 'dot' is allowed in swagger, but it won't work in python-format path_params = {} for k, v in six.iteritems(self.__p['path']): path_params[k] = six.moves.urllib.parse.quote_plus(v) self.__path = self.__path.format(**path_params) # combine path parameters into url self.__url = ''.join([scheme, ':', self.__url.format(**path_params)]) # header parameters self.__header.update(self.__p['header']) # update data parameter content_type = None if self.__p['file']: if handle_files: content_type, self.__data = self._prepare_files(encoding) else: # client that can encode multipart/form-data, should # access form-data via data property and file from file # property. # only form data can be carried along with files, self.__data = self.__p['formData'] elif self.__p['formData']: content_type, self.__data = self._prepare_forms() elif self.__p['body']: content_type, self.__data = self._prepare_body() else: self.__data = None if content_type: self.__header.update({'Content-Type': content_type}) accept = self.__produce if not accept and self.__op.produces: accept = self.__op.produces[0] if accept: if self.__op.produces and accept not in self.__op.produces: raise errs.SchemaError('accept {0} does not present in {1}'.format(accept, self.__op.produces)) self.__header.update({'Accept': accept}) return self
[ "def", "prepare", "(", "self", ",", "scheme", "=", "'http'", ",", "handle_files", "=", "True", ",", "encoding", "=", "'utf-8'", ")", ":", "if", "isinstance", "(", "scheme", ",", "list", ")", ":", "if", "self", ".", "__scheme", "is", "None", ":", "scheme", "=", "scheme", ".", "pop", "(", ")", "else", ":", "if", "self", ".", "__scheme", "in", "scheme", ":", "scheme", "=", "self", ".", "__scheme", "else", ":", "raise", "Exception", "(", "'preferred scheme:{} is not supported by the client or spec:{}'", ".", "format", "(", "self", ".", "__scheme", ",", "scheme", ")", ")", "elif", "not", "isinstance", "(", "scheme", ",", "six", ".", "string_types", ")", ":", "raise", "ValueError", "(", "'\"scheme\" should be a list or string'", ")", "# combine path parameters into path", "# TODO: 'dot' is allowed in swagger, but it won't work in python-format", "path_params", "=", "{", "}", "for", "k", ",", "v", "in", "six", ".", "iteritems", "(", "self", ".", "__p", "[", "'path'", "]", ")", ":", "path_params", "[", "k", "]", "=", "six", ".", "moves", ".", "urllib", ".", "parse", ".", "quote_plus", "(", "v", ")", "self", ".", "__path", "=", "self", ".", "__path", ".", "format", "(", "*", "*", "path_params", ")", "# combine path parameters into url", "self", ".", "__url", "=", "''", ".", "join", "(", "[", "scheme", ",", "':'", ",", "self", ".", "__url", ".", "format", "(", "*", "*", "path_params", ")", "]", ")", "# header parameters", "self", ".", "__header", ".", "update", "(", "self", ".", "__p", "[", "'header'", "]", ")", "# update data parameter", "content_type", "=", "None", "if", "self", ".", "__p", "[", "'file'", "]", ":", "if", "handle_files", ":", "content_type", ",", "self", ".", "__data", "=", "self", ".", "_prepare_files", "(", "encoding", ")", "else", ":", "# client that can encode multipart/form-data, should", "# access form-data via data property and file from file", "# property.", "# only form data can be carried along with files,", "self", ".", "__data", "=", "self", ".", "__p", "[", "'formData'", "]", "elif", "self", ".", "__p", "[", "'formData'", "]", ":", "content_type", ",", "self", ".", "__data", "=", "self", ".", "_prepare_forms", "(", ")", "elif", "self", ".", "__p", "[", "'body'", "]", ":", "content_type", ",", "self", ".", "__data", "=", "self", ".", "_prepare_body", "(", ")", "else", ":", "self", ".", "__data", "=", "None", "if", "content_type", ":", "self", ".", "__header", ".", "update", "(", "{", "'Content-Type'", ":", "content_type", "}", ")", "accept", "=", "self", ".", "__produce", "if", "not", "accept", "and", "self", ".", "__op", ".", "produces", ":", "accept", "=", "self", ".", "__op", ".", "produces", "[", "0", "]", "if", "accept", ":", "if", "self", ".", "__op", ".", "produces", "and", "accept", "not", "in", "self", ".", "__op", ".", "produces", ":", "raise", "errs", ".", "SchemaError", "(", "'accept {0} does not present in {1}'", ".", "format", "(", "accept", ",", "self", ".", "__op", ".", "produces", ")", ")", "self", ".", "__header", ".", "update", "(", "{", "'Accept'", ":", "accept", "}", ")", "return", "self" ]
make this request ready for Clients :param str scheme: scheme used in this request :param bool handle_files: False to skip multipart/form-data encoding :param str encoding: encoding for body content. :rtype: Request
[ "make", "this", "request", "ready", "for", "Clients" ]
333c4ca08e758cd2194943d9904a3eda3fe43977
https://github.com/pyopenapi/pyswagger/blob/333c4ca08e758cd2194943d9904a3eda3fe43977/pyswagger/io.py#L174-L239
7,174
pyopenapi/pyswagger
pyswagger/io.py
Response.apply_with
def apply_with(self, status=None, raw=None, header=None): """ update header, status code, raw datum, ...etc :param int status: status code :param str raw: body content :param dict header: header section :return: return self for chaining :rtype: Response """ if status != None: self.__status = status r = (final(self.__op.responses.get(str(self.__status), None)) or final(self.__op.responses.get('default', None))) if header != None: if isinstance(header, (collections.Mapping, collections.MutableMapping)): for k, v in six.iteritems(header): self._convert_header(r, k, v) else: for k, v in header: self._convert_header(r, k, v) if raw != None: # update 'raw' self.__raw = raw if self.__status == None: raise Exception('Update status code before assigning raw data') if r and r.schema and not self.__raw_body_only: # update data from Opeartion if succeed else from responseMessage.responseModel content_type = 'application/json' for k, v in six.iteritems(self.header): if k.lower() == 'content-type': content_type = v[0].lower() break schema = deref(r.schema) _type = schema.type _format = schema.format name = schema.name data = self.__op._mime_codec.unmarshal(content_type, self.raw, _type=_type, _format=_format, name=name) self.__data = r.schema._prim_(data, self.__op._prim_factory, ctx=dict(read=True)) return self
python
def apply_with(self, status=None, raw=None, header=None): """ update header, status code, raw datum, ...etc :param int status: status code :param str raw: body content :param dict header: header section :return: return self for chaining :rtype: Response """ if status != None: self.__status = status r = (final(self.__op.responses.get(str(self.__status), None)) or final(self.__op.responses.get('default', None))) if header != None: if isinstance(header, (collections.Mapping, collections.MutableMapping)): for k, v in six.iteritems(header): self._convert_header(r, k, v) else: for k, v in header: self._convert_header(r, k, v) if raw != None: # update 'raw' self.__raw = raw if self.__status == None: raise Exception('Update status code before assigning raw data') if r and r.schema and not self.__raw_body_only: # update data from Opeartion if succeed else from responseMessage.responseModel content_type = 'application/json' for k, v in six.iteritems(self.header): if k.lower() == 'content-type': content_type = v[0].lower() break schema = deref(r.schema) _type = schema.type _format = schema.format name = schema.name data = self.__op._mime_codec.unmarshal(content_type, self.raw, _type=_type, _format=_format, name=name) self.__data = r.schema._prim_(data, self.__op._prim_factory, ctx=dict(read=True)) return self
[ "def", "apply_with", "(", "self", ",", "status", "=", "None", ",", "raw", "=", "None", ",", "header", "=", "None", ")", ":", "if", "status", "!=", "None", ":", "self", ".", "__status", "=", "status", "r", "=", "(", "final", "(", "self", ".", "__op", ".", "responses", ".", "get", "(", "str", "(", "self", ".", "__status", ")", ",", "None", ")", ")", "or", "final", "(", "self", ".", "__op", ".", "responses", ".", "get", "(", "'default'", ",", "None", ")", ")", ")", "if", "header", "!=", "None", ":", "if", "isinstance", "(", "header", ",", "(", "collections", ".", "Mapping", ",", "collections", ".", "MutableMapping", ")", ")", ":", "for", "k", ",", "v", "in", "six", ".", "iteritems", "(", "header", ")", ":", "self", ".", "_convert_header", "(", "r", ",", "k", ",", "v", ")", "else", ":", "for", "k", ",", "v", "in", "header", ":", "self", ".", "_convert_header", "(", "r", ",", "k", ",", "v", ")", "if", "raw", "!=", "None", ":", "# update 'raw'", "self", ".", "__raw", "=", "raw", "if", "self", ".", "__status", "==", "None", ":", "raise", "Exception", "(", "'Update status code before assigning raw data'", ")", "if", "r", "and", "r", ".", "schema", "and", "not", "self", ".", "__raw_body_only", ":", "# update data from Opeartion if succeed else from responseMessage.responseModel", "content_type", "=", "'application/json'", "for", "k", ",", "v", "in", "six", ".", "iteritems", "(", "self", ".", "header", ")", ":", "if", "k", ".", "lower", "(", ")", "==", "'content-type'", ":", "content_type", "=", "v", "[", "0", "]", ".", "lower", "(", ")", "break", "schema", "=", "deref", "(", "r", ".", "schema", ")", "_type", "=", "schema", ".", "type", "_format", "=", "schema", ".", "format", "name", "=", "schema", ".", "name", "data", "=", "self", ".", "__op", ".", "_mime_codec", ".", "unmarshal", "(", "content_type", ",", "self", ".", "raw", ",", "_type", "=", "_type", ",", "_format", "=", "_format", ",", "name", "=", "name", ")", "self", ".", "__data", "=", "r", ".", "schema", ".", "_prim_", "(", "data", ",", "self", ".", "__op", ".", "_prim_factory", ",", "ctx", "=", "dict", "(", "read", "=", "True", ")", ")", "return", "self" ]
update header, status code, raw datum, ...etc :param int status: status code :param str raw: body content :param dict header: header section :return: return self for chaining :rtype: Response
[ "update", "header", "status", "code", "raw", "datum", "...", "etc" ]
333c4ca08e758cd2194943d9904a3eda3fe43977
https://github.com/pyopenapi/pyswagger/blob/333c4ca08e758cd2194943d9904a3eda3fe43977/pyswagger/io.py#L374-L419
7,175
pyopenapi/pyswagger
pyswagger/spec/base.py
Context.parse
def parse(self, obj=None): """ major part do parsing. :param dict obj: json object to be parsed. :raises ValueError: if obj is not a dict type. """ if obj == None: return if not isinstance(obj, dict): raise ValueError('invalid obj passed: ' + str(type(obj))) def _apply(x, kk, ct, v): if key not in self._obj: self._obj[kk] = {} if ct == None else [] with x(self._obj, kk) as ctx: ctx.parse(obj=v) def _apply_dict(x, kk, ct, v, k): if k not in self._obj[kk]: self._obj[kk][k] = {} if ct == ContainerType.dict_ else [] with x(self._obj[kk], k) as ctx: ctx.parse(obj=v) def _apply_dict_before_list(kk, ct, v, k): self._obj[kk][k] = [] if hasattr(self, '__swagger_child__'): # to nested objects for key, (ct, ctx_kls) in six.iteritems(self.__swagger_child__): items = obj.get(key, None) # create an empty child, even it's None in input. # this makes other logic easier. if ct == ContainerType.list_: self._obj[key] = [] elif ct: self._obj[key] = {} if items == None: continue container_apply(ct, items, functools.partial(_apply, ctx_kls, key), functools.partial(_apply_dict, ctx_kls, key), functools.partial(_apply_dict_before_list, key) ) # update _obj with obj if self._obj != None: for key in (set(obj.keys()) - set(self._obj.keys())): self._obj[key] = obj[key] else: self._obj = obj
python
def parse(self, obj=None): """ major part do parsing. :param dict obj: json object to be parsed. :raises ValueError: if obj is not a dict type. """ if obj == None: return if not isinstance(obj, dict): raise ValueError('invalid obj passed: ' + str(type(obj))) def _apply(x, kk, ct, v): if key not in self._obj: self._obj[kk] = {} if ct == None else [] with x(self._obj, kk) as ctx: ctx.parse(obj=v) def _apply_dict(x, kk, ct, v, k): if k not in self._obj[kk]: self._obj[kk][k] = {} if ct == ContainerType.dict_ else [] with x(self._obj[kk], k) as ctx: ctx.parse(obj=v) def _apply_dict_before_list(kk, ct, v, k): self._obj[kk][k] = [] if hasattr(self, '__swagger_child__'): # to nested objects for key, (ct, ctx_kls) in six.iteritems(self.__swagger_child__): items = obj.get(key, None) # create an empty child, even it's None in input. # this makes other logic easier. if ct == ContainerType.list_: self._obj[key] = [] elif ct: self._obj[key] = {} if items == None: continue container_apply(ct, items, functools.partial(_apply, ctx_kls, key), functools.partial(_apply_dict, ctx_kls, key), functools.partial(_apply_dict_before_list, key) ) # update _obj with obj if self._obj != None: for key in (set(obj.keys()) - set(self._obj.keys())): self._obj[key] = obj[key] else: self._obj = obj
[ "def", "parse", "(", "self", ",", "obj", "=", "None", ")", ":", "if", "obj", "==", "None", ":", "return", "if", "not", "isinstance", "(", "obj", ",", "dict", ")", ":", "raise", "ValueError", "(", "'invalid obj passed: '", "+", "str", "(", "type", "(", "obj", ")", ")", ")", "def", "_apply", "(", "x", ",", "kk", ",", "ct", ",", "v", ")", ":", "if", "key", "not", "in", "self", ".", "_obj", ":", "self", ".", "_obj", "[", "kk", "]", "=", "{", "}", "if", "ct", "==", "None", "else", "[", "]", "with", "x", "(", "self", ".", "_obj", ",", "kk", ")", "as", "ctx", ":", "ctx", ".", "parse", "(", "obj", "=", "v", ")", "def", "_apply_dict", "(", "x", ",", "kk", ",", "ct", ",", "v", ",", "k", ")", ":", "if", "k", "not", "in", "self", ".", "_obj", "[", "kk", "]", ":", "self", ".", "_obj", "[", "kk", "]", "[", "k", "]", "=", "{", "}", "if", "ct", "==", "ContainerType", ".", "dict_", "else", "[", "]", "with", "x", "(", "self", ".", "_obj", "[", "kk", "]", ",", "k", ")", "as", "ctx", ":", "ctx", ".", "parse", "(", "obj", "=", "v", ")", "def", "_apply_dict_before_list", "(", "kk", ",", "ct", ",", "v", ",", "k", ")", ":", "self", ".", "_obj", "[", "kk", "]", "[", "k", "]", "=", "[", "]", "if", "hasattr", "(", "self", ",", "'__swagger_child__'", ")", ":", "# to nested objects", "for", "key", ",", "(", "ct", ",", "ctx_kls", ")", "in", "six", ".", "iteritems", "(", "self", ".", "__swagger_child__", ")", ":", "items", "=", "obj", ".", "get", "(", "key", ",", "None", ")", "# create an empty child, even it's None in input.", "# this makes other logic easier.", "if", "ct", "==", "ContainerType", ".", "list_", ":", "self", ".", "_obj", "[", "key", "]", "=", "[", "]", "elif", "ct", ":", "self", ".", "_obj", "[", "key", "]", "=", "{", "}", "if", "items", "==", "None", ":", "continue", "container_apply", "(", "ct", ",", "items", ",", "functools", ".", "partial", "(", "_apply", ",", "ctx_kls", ",", "key", ")", ",", "functools", ".", "partial", "(", "_apply_dict", ",", "ctx_kls", ",", "key", ")", ",", "functools", ".", "partial", "(", "_apply_dict_before_list", ",", "key", ")", ")", "# update _obj with obj", "if", "self", ".", "_obj", "!=", "None", ":", "for", "key", "in", "(", "set", "(", "obj", ".", "keys", "(", ")", ")", "-", "set", "(", "self", ".", "_obj", ".", "keys", "(", ")", ")", ")", ":", "self", ".", "_obj", "[", "key", "]", "=", "obj", "[", "key", "]", "else", ":", "self", ".", "_obj", "=", "obj" ]
major part do parsing. :param dict obj: json object to be parsed. :raises ValueError: if obj is not a dict type.
[ "major", "part", "do", "parsing", "." ]
333c4ca08e758cd2194943d9904a3eda3fe43977
https://github.com/pyopenapi/pyswagger/blob/333c4ca08e758cd2194943d9904a3eda3fe43977/pyswagger/spec/base.py#L118-L171
7,176
pyopenapi/pyswagger
pyswagger/spec/base.py
BaseObj._assign_parent
def _assign_parent(self, ctx): """ parent assignment, internal usage only """ def _assign(cls, _, obj): if obj == None: return if cls.is_produced(obj): if isinstance(obj, BaseObj): obj._parent__ = self else: raise ValueError('Object is not instance of {0} but {1}'.format(cls.__swagger_ref_object__.__name__, obj.__class__.__name__)) # set self as childrent's parent for name, (ct, ctx) in six.iteritems(ctx.__swagger_child__): obj = getattr(self, name) if obj == None: continue container_apply(ct, obj, functools.partial(_assign, ctx))
python
def _assign_parent(self, ctx): """ parent assignment, internal usage only """ def _assign(cls, _, obj): if obj == None: return if cls.is_produced(obj): if isinstance(obj, BaseObj): obj._parent__ = self else: raise ValueError('Object is not instance of {0} but {1}'.format(cls.__swagger_ref_object__.__name__, obj.__class__.__name__)) # set self as childrent's parent for name, (ct, ctx) in six.iteritems(ctx.__swagger_child__): obj = getattr(self, name) if obj == None: continue container_apply(ct, obj, functools.partial(_assign, ctx))
[ "def", "_assign_parent", "(", "self", ",", "ctx", ")", ":", "def", "_assign", "(", "cls", ",", "_", ",", "obj", ")", ":", "if", "obj", "==", "None", ":", "return", "if", "cls", ".", "is_produced", "(", "obj", ")", ":", "if", "isinstance", "(", "obj", ",", "BaseObj", ")", ":", "obj", ".", "_parent__", "=", "self", "else", ":", "raise", "ValueError", "(", "'Object is not instance of {0} but {1}'", ".", "format", "(", "cls", ".", "__swagger_ref_object__", ".", "__name__", ",", "obj", ".", "__class__", ".", "__name__", ")", ")", "# set self as childrent's parent", "for", "name", ",", "(", "ct", ",", "ctx", ")", "in", "six", ".", "iteritems", "(", "ctx", ".", "__swagger_child__", ")", ":", "obj", "=", "getattr", "(", "self", ",", "name", ")", "if", "obj", "==", "None", ":", "continue", "container_apply", "(", "ct", ",", "obj", ",", "functools", ".", "partial", "(", "_assign", ",", "ctx", ")", ")" ]
parent assignment, internal usage only
[ "parent", "assignment", "internal", "usage", "only" ]
333c4ca08e758cd2194943d9904a3eda3fe43977
https://github.com/pyopenapi/pyswagger/blob/333c4ca08e758cd2194943d9904a3eda3fe43977/pyswagger/spec/base.py#L217-L236
7,177
pyopenapi/pyswagger
pyswagger/spec/base.py
BaseObj.get_private_name
def get_private_name(self, f): """ get private protected name of an attribute :param str f: name of the private attribute to be accessed. """ f = self.__swagger_rename__[f] if f in self.__swagger_rename__.keys() else f return '_' + self.__class__.__name__ + '__' + f
python
def get_private_name(self, f): """ get private protected name of an attribute :param str f: name of the private attribute to be accessed. """ f = self.__swagger_rename__[f] if f in self.__swagger_rename__.keys() else f return '_' + self.__class__.__name__ + '__' + f
[ "def", "get_private_name", "(", "self", ",", "f", ")", ":", "f", "=", "self", ".", "__swagger_rename__", "[", "f", "]", "if", "f", "in", "self", ".", "__swagger_rename__", ".", "keys", "(", ")", "else", "f", "return", "'_'", "+", "self", ".", "__class__", ".", "__name__", "+", "'__'", "+", "f" ]
get private protected name of an attribute :param str f: name of the private attribute to be accessed.
[ "get", "private", "protected", "name", "of", "an", "attribute" ]
333c4ca08e758cd2194943d9904a3eda3fe43977
https://github.com/pyopenapi/pyswagger/blob/333c4ca08e758cd2194943d9904a3eda3fe43977/pyswagger/spec/base.py#L238-L244
7,178
pyopenapi/pyswagger
pyswagger/spec/base.py
BaseObj.update_field
def update_field(self, f, obj): """ update a field :param str f: name of field to be updated. :param obj: value of field to be updated. """ n = self.get_private_name(f) if not hasattr(self, n): raise AttributeError('{0} is not in {1}'.format(n, self.__class__.__name__)) setattr(self, n, obj) self.__origin_keys.add(f)
python
def update_field(self, f, obj): """ update a field :param str f: name of field to be updated. :param obj: value of field to be updated. """ n = self.get_private_name(f) if not hasattr(self, n): raise AttributeError('{0} is not in {1}'.format(n, self.__class__.__name__)) setattr(self, n, obj) self.__origin_keys.add(f)
[ "def", "update_field", "(", "self", ",", "f", ",", "obj", ")", ":", "n", "=", "self", ".", "get_private_name", "(", "f", ")", "if", "not", "hasattr", "(", "self", ",", "n", ")", ":", "raise", "AttributeError", "(", "'{0} is not in {1}'", ".", "format", "(", "n", ",", "self", ".", "__class__", ".", "__name__", ")", ")", "setattr", "(", "self", ",", "n", ",", "obj", ")", "self", ".", "__origin_keys", ".", "add", "(", "f", ")" ]
update a field :param str f: name of field to be updated. :param obj: value of field to be updated.
[ "update", "a", "field" ]
333c4ca08e758cd2194943d9904a3eda3fe43977
https://github.com/pyopenapi/pyswagger/blob/333c4ca08e758cd2194943d9904a3eda3fe43977/pyswagger/spec/base.py#L246-L257
7,179
pyopenapi/pyswagger
pyswagger/spec/base.py
BaseObj.resolve
def resolve(self, ts): """ resolve a list of tokens to an child object :param list ts: list of tokens """ if isinstance(ts, six.string_types): ts = [ts] obj = self while len(ts) > 0: t = ts.pop(0) if issubclass(obj.__class__, BaseObj): obj = getattr(obj, t) elif isinstance(obj, list): obj = obj[int(t)] elif isinstance(obj, dict): obj = obj[t] return obj
python
def resolve(self, ts): """ resolve a list of tokens to an child object :param list ts: list of tokens """ if isinstance(ts, six.string_types): ts = [ts] obj = self while len(ts) > 0: t = ts.pop(0) if issubclass(obj.__class__, BaseObj): obj = getattr(obj, t) elif isinstance(obj, list): obj = obj[int(t)] elif isinstance(obj, dict): obj = obj[t] return obj
[ "def", "resolve", "(", "self", ",", "ts", ")", ":", "if", "isinstance", "(", "ts", ",", "six", ".", "string_types", ")", ":", "ts", "=", "[", "ts", "]", "obj", "=", "self", "while", "len", "(", "ts", ")", ">", "0", ":", "t", "=", "ts", ".", "pop", "(", "0", ")", "if", "issubclass", "(", "obj", ".", "__class__", ",", "BaseObj", ")", ":", "obj", "=", "getattr", "(", "obj", ",", "t", ")", "elif", "isinstance", "(", "obj", ",", "list", ")", ":", "obj", "=", "obj", "[", "int", "(", "t", ")", "]", "elif", "isinstance", "(", "obj", ",", "dict", ")", ":", "obj", "=", "obj", "[", "t", "]", "return", "obj" ]
resolve a list of tokens to an child object :param list ts: list of tokens
[ "resolve", "a", "list", "of", "tokens", "to", "an", "child", "object" ]
333c4ca08e758cd2194943d9904a3eda3fe43977
https://github.com/pyopenapi/pyswagger/blob/333c4ca08e758cd2194943d9904a3eda3fe43977/pyswagger/spec/base.py#L259-L278
7,180
pyopenapi/pyswagger
pyswagger/spec/base.py
BaseObj.compare
def compare(self, other, base=None): """ comparison, will return the first difference """ if self.__class__ != other.__class__: return False, '' names = self._field_names_ def cmp_func(name, s, o): # special case for string types if isinstance(s, six.string_types) and isinstance(o, six.string_types): return s == o, name if s.__class__ != o.__class__: return False, name if isinstance(s, BaseObj): if not isinstance(s, weakref.ProxyTypes): return s.compare(o, name) elif isinstance(s, list): for i, v in zip(range(len(s)), s): same, n = cmp_func(jp_compose(str(i), name), v, o[i]) if not same: return same, n elif isinstance(s, dict): # compare if any key diff diff = list(set(s.keys()) - set(o.keys())) if diff: return False, jp_compose(str(diff[0]), name) diff = list(set(o.keys()) - set(s.keys())) if diff: return False, jp_compose(str(diff[0]), name) for k, v in six.iteritems(s): same, n = cmp_func(jp_compose(k, name), v, o[k]) if not same: return same, n else: return s == o, name return True, name for n in names: same, n = cmp_func(jp_compose(n, base), getattr(self, n), getattr(other, n)) if not same: return same, n return True, ''
python
def compare(self, other, base=None): """ comparison, will return the first difference """ if self.__class__ != other.__class__: return False, '' names = self._field_names_ def cmp_func(name, s, o): # special case for string types if isinstance(s, six.string_types) and isinstance(o, six.string_types): return s == o, name if s.__class__ != o.__class__: return False, name if isinstance(s, BaseObj): if not isinstance(s, weakref.ProxyTypes): return s.compare(o, name) elif isinstance(s, list): for i, v in zip(range(len(s)), s): same, n = cmp_func(jp_compose(str(i), name), v, o[i]) if not same: return same, n elif isinstance(s, dict): # compare if any key diff diff = list(set(s.keys()) - set(o.keys())) if diff: return False, jp_compose(str(diff[0]), name) diff = list(set(o.keys()) - set(s.keys())) if diff: return False, jp_compose(str(diff[0]), name) for k, v in six.iteritems(s): same, n = cmp_func(jp_compose(k, name), v, o[k]) if not same: return same, n else: return s == o, name return True, name for n in names: same, n = cmp_func(jp_compose(n, base), getattr(self, n), getattr(other, n)) if not same: return same, n return True, ''
[ "def", "compare", "(", "self", ",", "other", ",", "base", "=", "None", ")", ":", "if", "self", ".", "__class__", "!=", "other", ".", "__class__", ":", "return", "False", ",", "''", "names", "=", "self", ".", "_field_names_", "def", "cmp_func", "(", "name", ",", "s", ",", "o", ")", ":", "# special case for string types", "if", "isinstance", "(", "s", ",", "six", ".", "string_types", ")", "and", "isinstance", "(", "o", ",", "six", ".", "string_types", ")", ":", "return", "s", "==", "o", ",", "name", "if", "s", ".", "__class__", "!=", "o", ".", "__class__", ":", "return", "False", ",", "name", "if", "isinstance", "(", "s", ",", "BaseObj", ")", ":", "if", "not", "isinstance", "(", "s", ",", "weakref", ".", "ProxyTypes", ")", ":", "return", "s", ".", "compare", "(", "o", ",", "name", ")", "elif", "isinstance", "(", "s", ",", "list", ")", ":", "for", "i", ",", "v", "in", "zip", "(", "range", "(", "len", "(", "s", ")", ")", ",", "s", ")", ":", "same", ",", "n", "=", "cmp_func", "(", "jp_compose", "(", "str", "(", "i", ")", ",", "name", ")", ",", "v", ",", "o", "[", "i", "]", ")", "if", "not", "same", ":", "return", "same", ",", "n", "elif", "isinstance", "(", "s", ",", "dict", ")", ":", "# compare if any key diff", "diff", "=", "list", "(", "set", "(", "s", ".", "keys", "(", ")", ")", "-", "set", "(", "o", ".", "keys", "(", ")", ")", ")", "if", "diff", ":", "return", "False", ",", "jp_compose", "(", "str", "(", "diff", "[", "0", "]", ")", ",", "name", ")", "diff", "=", "list", "(", "set", "(", "o", ".", "keys", "(", ")", ")", "-", "set", "(", "s", ".", "keys", "(", ")", ")", ")", "if", "diff", ":", "return", "False", ",", "jp_compose", "(", "str", "(", "diff", "[", "0", "]", ")", ",", "name", ")", "for", "k", ",", "v", "in", "six", ".", "iteritems", "(", "s", ")", ":", "same", ",", "n", "=", "cmp_func", "(", "jp_compose", "(", "k", ",", "name", ")", ",", "v", ",", "o", "[", "k", "]", ")", "if", "not", "same", ":", "return", "same", ",", "n", "else", ":", "return", "s", "==", "o", ",", "name", "return", "True", ",", "name", "for", "n", "in", "names", ":", "same", ",", "n", "=", "cmp_func", "(", "jp_compose", "(", "n", ",", "base", ")", ",", "getattr", "(", "self", ",", "n", ")", ",", "getattr", "(", "other", ",", "n", ")", ")", "if", "not", "same", ":", "return", "same", ",", "n", "return", "True", ",", "''" ]
comparison, will return the first difference
[ "comparison", "will", "return", "the", "first", "difference" ]
333c4ca08e758cd2194943d9904a3eda3fe43977
https://github.com/pyopenapi/pyswagger/blob/333c4ca08e758cd2194943d9904a3eda3fe43977/pyswagger/spec/base.py#L345-L391
7,181
pyopenapi/pyswagger
pyswagger/spec/base.py
BaseObj._field_names_
def _field_names_(self): """ get list of field names defined in Swagger spec :return: a list of field names :rtype: a list of str """ ret = [] for n in six.iterkeys(self.__swagger_fields__): new_n = self.__swagger_rename__.get(n, None) ret.append(new_n) if new_n else ret.append(n) return ret
python
def _field_names_(self): """ get list of field names defined in Swagger spec :return: a list of field names :rtype: a list of str """ ret = [] for n in six.iterkeys(self.__swagger_fields__): new_n = self.__swagger_rename__.get(n, None) ret.append(new_n) if new_n else ret.append(n) return ret
[ "def", "_field_names_", "(", "self", ")", ":", "ret", "=", "[", "]", "for", "n", "in", "six", ".", "iterkeys", "(", "self", ".", "__swagger_fields__", ")", ":", "new_n", "=", "self", ".", "__swagger_rename__", ".", "get", "(", "n", ",", "None", ")", "ret", ".", "append", "(", "new_n", ")", "if", "new_n", "else", "ret", ".", "append", "(", "n", ")", "return", "ret" ]
get list of field names defined in Swagger spec :return: a list of field names :rtype: a list of str
[ "get", "list", "of", "field", "names", "defined", "in", "Swagger", "spec" ]
333c4ca08e758cd2194943d9904a3eda3fe43977
https://github.com/pyopenapi/pyswagger/blob/333c4ca08e758cd2194943d9904a3eda3fe43977/pyswagger/spec/base.py#L438-L449
7,182
pyopenapi/pyswagger
pyswagger/spec/base.py
BaseObj._children_
def _children_(self): """ get children objects :rtype: a dict of children {child_name: child_object} """ ret = {} names = self._field_names_ def down(name, obj): if isinstance(obj, BaseObj): if not isinstance(obj, weakref.ProxyTypes): ret[name] = obj elif isinstance(obj, list): for i, v in zip(range(len(obj)), obj): down(jp_compose(str(i), name), v) elif isinstance(obj, dict): for k, v in six.iteritems(obj): down(jp_compose(k, name), v) for n in names: down(jp_compose(n), getattr(self, n)) return ret
python
def _children_(self): """ get children objects :rtype: a dict of children {child_name: child_object} """ ret = {} names = self._field_names_ def down(name, obj): if isinstance(obj, BaseObj): if not isinstance(obj, weakref.ProxyTypes): ret[name] = obj elif isinstance(obj, list): for i, v in zip(range(len(obj)), obj): down(jp_compose(str(i), name), v) elif isinstance(obj, dict): for k, v in six.iteritems(obj): down(jp_compose(k, name), v) for n in names: down(jp_compose(n), getattr(self, n)) return ret
[ "def", "_children_", "(", "self", ")", ":", "ret", "=", "{", "}", "names", "=", "self", ".", "_field_names_", "def", "down", "(", "name", ",", "obj", ")", ":", "if", "isinstance", "(", "obj", ",", "BaseObj", ")", ":", "if", "not", "isinstance", "(", "obj", ",", "weakref", ".", "ProxyTypes", ")", ":", "ret", "[", "name", "]", "=", "obj", "elif", "isinstance", "(", "obj", ",", "list", ")", ":", "for", "i", ",", "v", "in", "zip", "(", "range", "(", "len", "(", "obj", ")", ")", ",", "obj", ")", ":", "down", "(", "jp_compose", "(", "str", "(", "i", ")", ",", "name", ")", ",", "v", ")", "elif", "isinstance", "(", "obj", ",", "dict", ")", ":", "for", "k", ",", "v", "in", "six", ".", "iteritems", "(", "obj", ")", ":", "down", "(", "jp_compose", "(", "k", ",", "name", ")", ",", "v", ")", "for", "n", "in", "names", ":", "down", "(", "jp_compose", "(", "n", ")", ",", "getattr", "(", "self", ",", "n", ")", ")", "return", "ret" ]
get children objects :rtype: a dict of children {child_name: child_object}
[ "get", "children", "objects" ]
333c4ca08e758cd2194943d9904a3eda3fe43977
https://github.com/pyopenapi/pyswagger/blob/333c4ca08e758cd2194943d9904a3eda3fe43977/pyswagger/spec/base.py#L452-L474
7,183
pyopenapi/pyswagger
pyswagger/core.py
App.load
def load(kls, url, getter=None, parser=None, url_load_hook=None, sep=consts.private.SCOPE_SEPARATOR, prim=None, mime_codec=None, resolver=None): """ load json as a raw App :param str url: url of path of Swagger API definition :param getter: customized Getter :type getter: sub class/instance of Getter :param parser: the parser to parse the loaded json. :type parser: pyswagger.base.Context :param dict app_cache: the cache shared by related App :param func url_load_hook: hook to patch the url to load json :param str sep: scope-separater used in this App :param prim pyswager.primitives.Primitive: factory for primitives in Swagger :param mime_codec pyswagger.primitives.MimeCodec: MIME codec :param resolver: pyswagger.resolve.Resolver: customized resolver used as default when none is provided when resolving :return: the created App object :rtype: App :raises ValueError: if url is wrong :raises NotImplementedError: the swagger version is not supported. """ logger.info('load with [{0}]'.format(url)) url = utils.normalize_url(url) app = kls(url, url_load_hook=url_load_hook, sep=sep, prim=prim, mime_codec=mime_codec, resolver=resolver) app.__raw, app.__version = app.load_obj(url, getter=getter, parser=parser) if app.__version not in ['1.2', '2.0']: raise NotImplementedError('Unsupported Version: {0}'.format(self.__version)) # update scheme if any p = six.moves.urllib.parse.urlparse(url) if p.scheme: app.schemes.append(p.scheme) return app
python
def load(kls, url, getter=None, parser=None, url_load_hook=None, sep=consts.private.SCOPE_SEPARATOR, prim=None, mime_codec=None, resolver=None): """ load json as a raw App :param str url: url of path of Swagger API definition :param getter: customized Getter :type getter: sub class/instance of Getter :param parser: the parser to parse the loaded json. :type parser: pyswagger.base.Context :param dict app_cache: the cache shared by related App :param func url_load_hook: hook to patch the url to load json :param str sep: scope-separater used in this App :param prim pyswager.primitives.Primitive: factory for primitives in Swagger :param mime_codec pyswagger.primitives.MimeCodec: MIME codec :param resolver: pyswagger.resolve.Resolver: customized resolver used as default when none is provided when resolving :return: the created App object :rtype: App :raises ValueError: if url is wrong :raises NotImplementedError: the swagger version is not supported. """ logger.info('load with [{0}]'.format(url)) url = utils.normalize_url(url) app = kls(url, url_load_hook=url_load_hook, sep=sep, prim=prim, mime_codec=mime_codec, resolver=resolver) app.__raw, app.__version = app.load_obj(url, getter=getter, parser=parser) if app.__version not in ['1.2', '2.0']: raise NotImplementedError('Unsupported Version: {0}'.format(self.__version)) # update scheme if any p = six.moves.urllib.parse.urlparse(url) if p.scheme: app.schemes.append(p.scheme) return app
[ "def", "load", "(", "kls", ",", "url", ",", "getter", "=", "None", ",", "parser", "=", "None", ",", "url_load_hook", "=", "None", ",", "sep", "=", "consts", ".", "private", ".", "SCOPE_SEPARATOR", ",", "prim", "=", "None", ",", "mime_codec", "=", "None", ",", "resolver", "=", "None", ")", ":", "logger", ".", "info", "(", "'load with [{0}]'", ".", "format", "(", "url", ")", ")", "url", "=", "utils", ".", "normalize_url", "(", "url", ")", "app", "=", "kls", "(", "url", ",", "url_load_hook", "=", "url_load_hook", ",", "sep", "=", "sep", ",", "prim", "=", "prim", ",", "mime_codec", "=", "mime_codec", ",", "resolver", "=", "resolver", ")", "app", ".", "__raw", ",", "app", ".", "__version", "=", "app", ".", "load_obj", "(", "url", ",", "getter", "=", "getter", ",", "parser", "=", "parser", ")", "if", "app", ".", "__version", "not", "in", "[", "'1.2'", ",", "'2.0'", "]", ":", "raise", "NotImplementedError", "(", "'Unsupported Version: {0}'", ".", "format", "(", "self", ".", "__version", ")", ")", "# update scheme if any", "p", "=", "six", ".", "moves", ".", "urllib", ".", "parse", ".", "urlparse", "(", "url", ")", "if", "p", ".", "scheme", ":", "app", ".", "schemes", ".", "append", "(", "p", ".", "scheme", ")", "return", "app" ]
load json as a raw App :param str url: url of path of Swagger API definition :param getter: customized Getter :type getter: sub class/instance of Getter :param parser: the parser to parse the loaded json. :type parser: pyswagger.base.Context :param dict app_cache: the cache shared by related App :param func url_load_hook: hook to patch the url to load json :param str sep: scope-separater used in this App :param prim pyswager.primitives.Primitive: factory for primitives in Swagger :param mime_codec pyswagger.primitives.MimeCodec: MIME codec :param resolver: pyswagger.resolve.Resolver: customized resolver used as default when none is provided when resolving :return: the created App object :rtype: App :raises ValueError: if url is wrong :raises NotImplementedError: the swagger version is not supported.
[ "load", "json", "as", "a", "raw", "App" ]
333c4ca08e758cd2194943d9904a3eda3fe43977
https://github.com/pyopenapi/pyswagger/blob/333c4ca08e758cd2194943d9904a3eda3fe43977/pyswagger/core.py#L261-L294
7,184
pyopenapi/pyswagger
pyswagger/core.py
App.prepare
def prepare(self, strict=True): """ preparation for loaded json :param bool strict: when in strict mode, exception would be raised if not valid. """ self.__root = self.prepare_obj(self.raw, self.__url) self.validate(strict=strict) if hasattr(self.__root, 'schemes') and self.__root.schemes: if len(self.__root.schemes) > 0: self.__schemes = self.__root.schemes else: # extract schemes from the url to load spec self.__schemes = [six.moves.urlparse(self.__url).schemes] s = Scanner(self) s.scan(root=self.__root, route=[Merge()]) s.scan(root=self.__root, route=[PatchObject()]) s.scan(root=self.__root, route=[Aggregate()]) # reducer for Operation tr = TypeReduce(self.__sep) cy = CycleDetector() s.scan(root=self.__root, route=[tr, cy]) # 'op' -- shortcut for Operation with tag and operaionId self.__op = utils.ScopeDict(tr.op) # 'm' -- shortcut for model in Swagger 1.2 if hasattr(self.__root, 'definitions') and self.__root.definitions != None: self.__m = utils.ScopeDict(self.__root.definitions) else: self.__m = utils.ScopeDict({}) # update scope-separater self.__m.sep = self.__sep self.__op.sep = self.__sep # cycle detection if len(cy.cycles['schema']) > 0 and strict: raise errs.CycleDetectionError('Cycles detected in Schema Object: {0}'.format(cy.cycles['schema']))
python
def prepare(self, strict=True): """ preparation for loaded json :param bool strict: when in strict mode, exception would be raised if not valid. """ self.__root = self.prepare_obj(self.raw, self.__url) self.validate(strict=strict) if hasattr(self.__root, 'schemes') and self.__root.schemes: if len(self.__root.schemes) > 0: self.__schemes = self.__root.schemes else: # extract schemes from the url to load spec self.__schemes = [six.moves.urlparse(self.__url).schemes] s = Scanner(self) s.scan(root=self.__root, route=[Merge()]) s.scan(root=self.__root, route=[PatchObject()]) s.scan(root=self.__root, route=[Aggregate()]) # reducer for Operation tr = TypeReduce(self.__sep) cy = CycleDetector() s.scan(root=self.__root, route=[tr, cy]) # 'op' -- shortcut for Operation with tag and operaionId self.__op = utils.ScopeDict(tr.op) # 'm' -- shortcut for model in Swagger 1.2 if hasattr(self.__root, 'definitions') and self.__root.definitions != None: self.__m = utils.ScopeDict(self.__root.definitions) else: self.__m = utils.ScopeDict({}) # update scope-separater self.__m.sep = self.__sep self.__op.sep = self.__sep # cycle detection if len(cy.cycles['schema']) > 0 and strict: raise errs.CycleDetectionError('Cycles detected in Schema Object: {0}'.format(cy.cycles['schema']))
[ "def", "prepare", "(", "self", ",", "strict", "=", "True", ")", ":", "self", ".", "__root", "=", "self", ".", "prepare_obj", "(", "self", ".", "raw", ",", "self", ".", "__url", ")", "self", ".", "validate", "(", "strict", "=", "strict", ")", "if", "hasattr", "(", "self", ".", "__root", ",", "'schemes'", ")", "and", "self", ".", "__root", ".", "schemes", ":", "if", "len", "(", "self", ".", "__root", ".", "schemes", ")", ">", "0", ":", "self", ".", "__schemes", "=", "self", ".", "__root", ".", "schemes", "else", ":", "# extract schemes from the url to load spec", "self", ".", "__schemes", "=", "[", "six", ".", "moves", ".", "urlparse", "(", "self", ".", "__url", ")", ".", "schemes", "]", "s", "=", "Scanner", "(", "self", ")", "s", ".", "scan", "(", "root", "=", "self", ".", "__root", ",", "route", "=", "[", "Merge", "(", ")", "]", ")", "s", ".", "scan", "(", "root", "=", "self", ".", "__root", ",", "route", "=", "[", "PatchObject", "(", ")", "]", ")", "s", ".", "scan", "(", "root", "=", "self", ".", "__root", ",", "route", "=", "[", "Aggregate", "(", ")", "]", ")", "# reducer for Operation", "tr", "=", "TypeReduce", "(", "self", ".", "__sep", ")", "cy", "=", "CycleDetector", "(", ")", "s", ".", "scan", "(", "root", "=", "self", ".", "__root", ",", "route", "=", "[", "tr", ",", "cy", "]", ")", "# 'op' -- shortcut for Operation with tag and operaionId", "self", ".", "__op", "=", "utils", ".", "ScopeDict", "(", "tr", ".", "op", ")", "# 'm' -- shortcut for model in Swagger 1.2", "if", "hasattr", "(", "self", ".", "__root", ",", "'definitions'", ")", "and", "self", ".", "__root", ".", "definitions", "!=", "None", ":", "self", ".", "__m", "=", "utils", ".", "ScopeDict", "(", "self", ".", "__root", ".", "definitions", ")", "else", ":", "self", ".", "__m", "=", "utils", ".", "ScopeDict", "(", "{", "}", ")", "# update scope-separater", "self", ".", "__m", ".", "sep", "=", "self", ".", "__sep", "self", ".", "__op", ".", "sep", "=", "self", ".", "__sep", "# cycle detection", "if", "len", "(", "cy", ".", "cycles", "[", "'schema'", "]", ")", ">", "0", "and", "strict", ":", "raise", "errs", ".", "CycleDetectionError", "(", "'Cycles detected in Schema Object: {0}'", ".", "format", "(", "cy", ".", "cycles", "[", "'schema'", "]", ")", ")" ]
preparation for loaded json :param bool strict: when in strict mode, exception would be raised if not valid.
[ "preparation", "for", "loaded", "json" ]
333c4ca08e758cd2194943d9904a3eda3fe43977
https://github.com/pyopenapi/pyswagger/blob/333c4ca08e758cd2194943d9904a3eda3fe43977/pyswagger/core.py#L312-L351
7,185
pyopenapi/pyswagger
pyswagger/core.py
App.create
def create(kls, url, strict=True): """ factory of App :param str url: url of path of Swagger API definition :param bool strict: when in strict mode, exception would be raised if not valid. :return: the created App object :rtype: App :raises ValueError: if url is wrong :raises NotImplementedError: the swagger version is not supported. """ app = kls.load(url) app.prepare(strict=strict) return app
python
def create(kls, url, strict=True): """ factory of App :param str url: url of path of Swagger API definition :param bool strict: when in strict mode, exception would be raised if not valid. :return: the created App object :rtype: App :raises ValueError: if url is wrong :raises NotImplementedError: the swagger version is not supported. """ app = kls.load(url) app.prepare(strict=strict) return app
[ "def", "create", "(", "kls", ",", "url", ",", "strict", "=", "True", ")", ":", "app", "=", "kls", ".", "load", "(", "url", ")", "app", ".", "prepare", "(", "strict", "=", "strict", ")", "return", "app" ]
factory of App :param str url: url of path of Swagger API definition :param bool strict: when in strict mode, exception would be raised if not valid. :return: the created App object :rtype: App :raises ValueError: if url is wrong :raises NotImplementedError: the swagger version is not supported.
[ "factory", "of", "App" ]
333c4ca08e758cd2194943d9904a3eda3fe43977
https://github.com/pyopenapi/pyswagger/blob/333c4ca08e758cd2194943d9904a3eda3fe43977/pyswagger/core.py#L354-L367
7,186
pyopenapi/pyswagger
pyswagger/core.py
App.resolve
def resolve(self, jref, parser=None): """ JSON reference resolver :param str jref: a JSON Reference, refer to http://tools.ietf.org/html/draft-pbryan-zyp-json-ref-03 for details. :param parser: the parser corresponding to target object. :type parser: pyswagger.base.Context :return: the referenced object, wrapped by weakref.ProxyType :rtype: weakref.ProxyType :raises ValueError: if path is not valid """ logger.info('resolving: [{0}]'.format(jref)) if jref == None or len(jref) == 0: raise ValueError('Empty Path is not allowed') obj = None url, jp = utils.jr_split(jref) # check cacahed object against json reference by # comparing url first, and find those object prefixed with # the JSON pointer. o = self.__objs.get(url, None) if o: if isinstance(o, BaseObj): obj = o.resolve(utils.jp_split(jp)[1:]) elif isinstance(o, dict): for k, v in six.iteritems(o): if jp.startswith(k): obj = v.resolve(utils.jp_split(jp[len(k):])[1:]) break else: raise Exception('Unknown Cached Object: {0}'.format(str(type(o)))) # this object is not found in cache if obj == None: if url: obj, _ = self.load_obj(jref, parser=parser) if obj: obj = self.prepare_obj(obj, jref) else: # a local reference, 'jref' is just a json-pointer if not jp.startswith('#'): raise ValueError('Invalid Path, root element should be \'#\', but [{0}]'.format(jref)) obj = self.root.resolve(utils.jp_split(jp)[1:]) # heading element is #, mapping to self.root if obj == None: raise ValueError('Unable to resolve path, [{0}]'.format(jref)) if isinstance(obj, (six.string_types, six.integer_types, list, dict)): return obj return weakref.proxy(obj)
python
def resolve(self, jref, parser=None): """ JSON reference resolver :param str jref: a JSON Reference, refer to http://tools.ietf.org/html/draft-pbryan-zyp-json-ref-03 for details. :param parser: the parser corresponding to target object. :type parser: pyswagger.base.Context :return: the referenced object, wrapped by weakref.ProxyType :rtype: weakref.ProxyType :raises ValueError: if path is not valid """ logger.info('resolving: [{0}]'.format(jref)) if jref == None or len(jref) == 0: raise ValueError('Empty Path is not allowed') obj = None url, jp = utils.jr_split(jref) # check cacahed object against json reference by # comparing url first, and find those object prefixed with # the JSON pointer. o = self.__objs.get(url, None) if o: if isinstance(o, BaseObj): obj = o.resolve(utils.jp_split(jp)[1:]) elif isinstance(o, dict): for k, v in six.iteritems(o): if jp.startswith(k): obj = v.resolve(utils.jp_split(jp[len(k):])[1:]) break else: raise Exception('Unknown Cached Object: {0}'.format(str(type(o)))) # this object is not found in cache if obj == None: if url: obj, _ = self.load_obj(jref, parser=parser) if obj: obj = self.prepare_obj(obj, jref) else: # a local reference, 'jref' is just a json-pointer if not jp.startswith('#'): raise ValueError('Invalid Path, root element should be \'#\', but [{0}]'.format(jref)) obj = self.root.resolve(utils.jp_split(jp)[1:]) # heading element is #, mapping to self.root if obj == None: raise ValueError('Unable to resolve path, [{0}]'.format(jref)) if isinstance(obj, (six.string_types, six.integer_types, list, dict)): return obj return weakref.proxy(obj)
[ "def", "resolve", "(", "self", ",", "jref", ",", "parser", "=", "None", ")", ":", "logger", ".", "info", "(", "'resolving: [{0}]'", ".", "format", "(", "jref", ")", ")", "if", "jref", "==", "None", "or", "len", "(", "jref", ")", "==", "0", ":", "raise", "ValueError", "(", "'Empty Path is not allowed'", ")", "obj", "=", "None", "url", ",", "jp", "=", "utils", ".", "jr_split", "(", "jref", ")", "# check cacahed object against json reference by", "# comparing url first, and find those object prefixed with", "# the JSON pointer.", "o", "=", "self", ".", "__objs", ".", "get", "(", "url", ",", "None", ")", "if", "o", ":", "if", "isinstance", "(", "o", ",", "BaseObj", ")", ":", "obj", "=", "o", ".", "resolve", "(", "utils", ".", "jp_split", "(", "jp", ")", "[", "1", ":", "]", ")", "elif", "isinstance", "(", "o", ",", "dict", ")", ":", "for", "k", ",", "v", "in", "six", ".", "iteritems", "(", "o", ")", ":", "if", "jp", ".", "startswith", "(", "k", ")", ":", "obj", "=", "v", ".", "resolve", "(", "utils", ".", "jp_split", "(", "jp", "[", "len", "(", "k", ")", ":", "]", ")", "[", "1", ":", "]", ")", "break", "else", ":", "raise", "Exception", "(", "'Unknown Cached Object: {0}'", ".", "format", "(", "str", "(", "type", "(", "o", ")", ")", ")", ")", "# this object is not found in cache", "if", "obj", "==", "None", ":", "if", "url", ":", "obj", ",", "_", "=", "self", ".", "load_obj", "(", "jref", ",", "parser", "=", "parser", ")", "if", "obj", ":", "obj", "=", "self", ".", "prepare_obj", "(", "obj", ",", "jref", ")", "else", ":", "# a local reference, 'jref' is just a json-pointer", "if", "not", "jp", ".", "startswith", "(", "'#'", ")", ":", "raise", "ValueError", "(", "'Invalid Path, root element should be \\'#\\', but [{0}]'", ".", "format", "(", "jref", ")", ")", "obj", "=", "self", ".", "root", ".", "resolve", "(", "utils", ".", "jp_split", "(", "jp", ")", "[", "1", ":", "]", ")", "# heading element is #, mapping to self.root", "if", "obj", "==", "None", ":", "raise", "ValueError", "(", "'Unable to resolve path, [{0}]'", ".", "format", "(", "jref", ")", ")", "if", "isinstance", "(", "obj", ",", "(", "six", ".", "string_types", ",", "six", ".", "integer_types", ",", "list", ",", "dict", ")", ")", ":", "return", "obj", "return", "weakref", ".", "proxy", "(", "obj", ")" ]
JSON reference resolver :param str jref: a JSON Reference, refer to http://tools.ietf.org/html/draft-pbryan-zyp-json-ref-03 for details. :param parser: the parser corresponding to target object. :type parser: pyswagger.base.Context :return: the referenced object, wrapped by weakref.ProxyType :rtype: weakref.ProxyType :raises ValueError: if path is not valid
[ "JSON", "reference", "resolver" ]
333c4ca08e758cd2194943d9904a3eda3fe43977
https://github.com/pyopenapi/pyswagger/blob/333c4ca08e758cd2194943d9904a3eda3fe43977/pyswagger/core.py#L374-L426
7,187
pyopenapi/pyswagger
pyswagger/core.py
BaseClient.prepare_schemes
def prepare_schemes(self, req): """ make sure this client support schemes required by current request :param pyswagger.io.Request req: current request object """ # fix test bug when in python3 scheme, more details in commint msg ret = sorted(self.__schemes__ & set(req.schemes), reverse=True) if len(ret) == 0: raise ValueError('No schemes available: {0}'.format(req.schemes)) return ret
python
def prepare_schemes(self, req): """ make sure this client support schemes required by current request :param pyswagger.io.Request req: current request object """ # fix test bug when in python3 scheme, more details in commint msg ret = sorted(self.__schemes__ & set(req.schemes), reverse=True) if len(ret) == 0: raise ValueError('No schemes available: {0}'.format(req.schemes)) return ret
[ "def", "prepare_schemes", "(", "self", ",", "req", ")", ":", "# fix test bug when in python3 scheme, more details in commint msg", "ret", "=", "sorted", "(", "self", ".", "__schemes__", "&", "set", "(", "req", ".", "schemes", ")", ",", "reverse", "=", "True", ")", "if", "len", "(", "ret", ")", "==", "0", ":", "raise", "ValueError", "(", "'No schemes available: {0}'", ".", "format", "(", "req", ".", "schemes", ")", ")", "return", "ret" ]
make sure this client support schemes required by current request :param pyswagger.io.Request req: current request object
[ "make", "sure", "this", "client", "support", "schemes", "required", "by", "current", "request" ]
333c4ca08e758cd2194943d9904a3eda3fe43977
https://github.com/pyopenapi/pyswagger/blob/333c4ca08e758cd2194943d9904a3eda3fe43977/pyswagger/core.py#L558-L569
7,188
pyopenapi/pyswagger
pyswagger/core.py
BaseClient.compose_headers
def compose_headers(self, req, headers=None, opt=None, as_dict=False): """ a utility to compose headers from pyswagger.io.Request and customized headers :return: list of tuple (key, value) when as_dict is False, else dict """ if headers is None: return list(req.header.items()) if not as_dict else req.header opt = opt or {} join_headers = opt.pop(BaseClient.join_headers, None) if as_dict and not join_headers: # pick the most efficient way for special case headers = dict(headers) if isinstance(headers, list) else headers headers.update(req.header) return headers # include Request.headers aggregated_headers = list(req.header.items()) # include customized headers if isinstance(headers, list): aggregated_headers.extend(headers) elif isinstance(headers, dict): aggregated_headers.extend(headers.items()) else: raise Exception('unknown type as header: {}'.format(str(type(headers)))) if join_headers: joined = {} for h in aggregated_headers: key = h[0] if key in joined: joined[key] = ','.join([joined[key], h[1]]) else: joined[key] = h[1] aggregated_headers = list(joined.items()) return dict(aggregated_headers) if as_dict else aggregated_headers
python
def compose_headers(self, req, headers=None, opt=None, as_dict=False): """ a utility to compose headers from pyswagger.io.Request and customized headers :return: list of tuple (key, value) when as_dict is False, else dict """ if headers is None: return list(req.header.items()) if not as_dict else req.header opt = opt or {} join_headers = opt.pop(BaseClient.join_headers, None) if as_dict and not join_headers: # pick the most efficient way for special case headers = dict(headers) if isinstance(headers, list) else headers headers.update(req.header) return headers # include Request.headers aggregated_headers = list(req.header.items()) # include customized headers if isinstance(headers, list): aggregated_headers.extend(headers) elif isinstance(headers, dict): aggregated_headers.extend(headers.items()) else: raise Exception('unknown type as header: {}'.format(str(type(headers)))) if join_headers: joined = {} for h in aggregated_headers: key = h[0] if key in joined: joined[key] = ','.join([joined[key], h[1]]) else: joined[key] = h[1] aggregated_headers = list(joined.items()) return dict(aggregated_headers) if as_dict else aggregated_headers
[ "def", "compose_headers", "(", "self", ",", "req", ",", "headers", "=", "None", ",", "opt", "=", "None", ",", "as_dict", "=", "False", ")", ":", "if", "headers", "is", "None", ":", "return", "list", "(", "req", ".", "header", ".", "items", "(", ")", ")", "if", "not", "as_dict", "else", "req", ".", "header", "opt", "=", "opt", "or", "{", "}", "join_headers", "=", "opt", ".", "pop", "(", "BaseClient", ".", "join_headers", ",", "None", ")", "if", "as_dict", "and", "not", "join_headers", ":", "# pick the most efficient way for special case", "headers", "=", "dict", "(", "headers", ")", "if", "isinstance", "(", "headers", ",", "list", ")", "else", "headers", "headers", ".", "update", "(", "req", ".", "header", ")", "return", "headers", "# include Request.headers", "aggregated_headers", "=", "list", "(", "req", ".", "header", ".", "items", "(", ")", ")", "# include customized headers", "if", "isinstance", "(", "headers", ",", "list", ")", ":", "aggregated_headers", ".", "extend", "(", "headers", ")", "elif", "isinstance", "(", "headers", ",", "dict", ")", ":", "aggregated_headers", ".", "extend", "(", "headers", ".", "items", "(", ")", ")", "else", ":", "raise", "Exception", "(", "'unknown type as header: {}'", ".", "format", "(", "str", "(", "type", "(", "headers", ")", ")", ")", ")", "if", "join_headers", ":", "joined", "=", "{", "}", "for", "h", "in", "aggregated_headers", ":", "key", "=", "h", "[", "0", "]", "if", "key", "in", "joined", ":", "joined", "[", "key", "]", "=", "','", ".", "join", "(", "[", "joined", "[", "key", "]", ",", "h", "[", "1", "]", "]", ")", "else", ":", "joined", "[", "key", "]", "=", "h", "[", "1", "]", "aggregated_headers", "=", "list", "(", "joined", ".", "items", "(", ")", ")", "return", "dict", "(", "aggregated_headers", ")", "if", "as_dict", "else", "aggregated_headers" ]
a utility to compose headers from pyswagger.io.Request and customized headers :return: list of tuple (key, value) when as_dict is False, else dict
[ "a", "utility", "to", "compose", "headers", "from", "pyswagger", ".", "io", ".", "Request", "and", "customized", "headers" ]
333c4ca08e758cd2194943d9904a3eda3fe43977
https://github.com/pyopenapi/pyswagger/blob/333c4ca08e758cd2194943d9904a3eda3fe43977/pyswagger/core.py#L571-L608
7,189
pyopenapi/pyswagger
pyswagger/core.py
BaseClient.request
def request(self, req_and_resp, opt=None, headers=None): """ preprocess before performing a request, usually some patching. authorization also applied here. :param req_and_resp: tuple of Request and Response :type req_and_resp: (Request, Response) :param opt: customized options :type opt: dict :param headers: customized headers :type headers: dict of 'string', or list of tuple: (string, string) for multiple values for one key :return: patched request and response :rtype: Request, Response """ req, resp = req_and_resp # dump info for debugging logger.info('request.url: {0}'.format(req.url)) logger.info('request.header: {0}'.format(req.header)) logger.info('request.query: {0}'.format(req.query)) logger.info('request.file: {0}'.format(req.files)) logger.info('request.schemes: {0}'.format(req.schemes)) # apply authorizations if self.__security: self.__security(req) return req, resp
python
def request(self, req_and_resp, opt=None, headers=None): """ preprocess before performing a request, usually some patching. authorization also applied here. :param req_and_resp: tuple of Request and Response :type req_and_resp: (Request, Response) :param opt: customized options :type opt: dict :param headers: customized headers :type headers: dict of 'string', or list of tuple: (string, string) for multiple values for one key :return: patched request and response :rtype: Request, Response """ req, resp = req_and_resp # dump info for debugging logger.info('request.url: {0}'.format(req.url)) logger.info('request.header: {0}'.format(req.header)) logger.info('request.query: {0}'.format(req.query)) logger.info('request.file: {0}'.format(req.files)) logger.info('request.schemes: {0}'.format(req.schemes)) # apply authorizations if self.__security: self.__security(req) return req, resp
[ "def", "request", "(", "self", ",", "req_and_resp", ",", "opt", "=", "None", ",", "headers", "=", "None", ")", ":", "req", ",", "resp", "=", "req_and_resp", "# dump info for debugging", "logger", ".", "info", "(", "'request.url: {0}'", ".", "format", "(", "req", ".", "url", ")", ")", "logger", ".", "info", "(", "'request.header: {0}'", ".", "format", "(", "req", ".", "header", ")", ")", "logger", ".", "info", "(", "'request.query: {0}'", ".", "format", "(", "req", ".", "query", ")", ")", "logger", ".", "info", "(", "'request.file: {0}'", ".", "format", "(", "req", ".", "files", ")", ")", "logger", ".", "info", "(", "'request.schemes: {0}'", ".", "format", "(", "req", ".", "schemes", ")", ")", "# apply authorizations", "if", "self", ".", "__security", ":", "self", ".", "__security", "(", "req", ")", "return", "req", ",", "resp" ]
preprocess before performing a request, usually some patching. authorization also applied here. :param req_and_resp: tuple of Request and Response :type req_and_resp: (Request, Response) :param opt: customized options :type opt: dict :param headers: customized headers :type headers: dict of 'string', or list of tuple: (string, string) for multiple values for one key :return: patched request and response :rtype: Request, Response
[ "preprocess", "before", "performing", "a", "request", "usually", "some", "patching", ".", "authorization", "also", "applied", "here", "." ]
333c4ca08e758cd2194943d9904a3eda3fe43977
https://github.com/pyopenapi/pyswagger/blob/333c4ca08e758cd2194943d9904a3eda3fe43977/pyswagger/core.py#L610-L636
7,190
pyopenapi/pyswagger
pyswagger/primitives/_array.py
Array.to_url
def to_url(self): """ special function for handling 'multi', refer to Swagger 2.0, Parameter Object, collectionFormat """ if self.__collection_format == 'multi': return [str(s) for s in self] else: return [str(self)]
python
def to_url(self): """ special function for handling 'multi', refer to Swagger 2.0, Parameter Object, collectionFormat """ if self.__collection_format == 'multi': return [str(s) for s in self] else: return [str(self)]
[ "def", "to_url", "(", "self", ")", ":", "if", "self", ".", "__collection_format", "==", "'multi'", ":", "return", "[", "str", "(", "s", ")", "for", "s", "in", "self", "]", "else", ":", "return", "[", "str", "(", "self", ")", "]" ]
special function for handling 'multi', refer to Swagger 2.0, Parameter Object, collectionFormat
[ "special", "function", "for", "handling", "multi", "refer", "to", "Swagger", "2", ".", "0", "Parameter", "Object", "collectionFormat" ]
333c4ca08e758cd2194943d9904a3eda3fe43977
https://github.com/pyopenapi/pyswagger/blob/333c4ca08e758cd2194943d9904a3eda3fe43977/pyswagger/primitives/_array.py#L83-L90
7,191
pyopenapi/pyswagger
pyswagger/primitives/_model.py
Model.apply_with
def apply_with(self, obj, val, ctx): """ recursively apply Schema object :param obj.Model obj: model object to instruct how to create this model :param dict val: things used to construct this model """ for k, v in six.iteritems(val): if k in obj.properties: pobj = obj.properties.get(k) if pobj.readOnly == True and ctx['read'] == False: raise Exception('read-only property is set in write context.') self[k] = ctx['factory'].produce(pobj, v) # TODO: patternProperties here # TODO: fix bug, everything would not go into additionalProperties, instead of recursive elif obj.additionalProperties == True: ctx['addp'] = True elif obj.additionalProperties not in (None, False): ctx['addp_schema'] = obj in_obj = set(six.iterkeys(obj.properties)) in_self = set(six.iterkeys(self)) other_prop = in_obj - in_self for k in other_prop: p = obj.properties[k] if p.is_set("default"): self[k] = ctx['factory'].produce(p, p.default) not_found = set(obj.required) - set(six.iterkeys(self)) if len(not_found): raise ValueError('Model missing required key(s): {0}'.format(', '.join(not_found))) # remove assigned properties to avoid duplicated # primitive creation _val = {} for k in set(six.iterkeys(val)) - in_obj: _val[k] = val[k] if obj.discriminator: self[obj.discriminator] = ctx['name'] return _val
python
def apply_with(self, obj, val, ctx): """ recursively apply Schema object :param obj.Model obj: model object to instruct how to create this model :param dict val: things used to construct this model """ for k, v in six.iteritems(val): if k in obj.properties: pobj = obj.properties.get(k) if pobj.readOnly == True and ctx['read'] == False: raise Exception('read-only property is set in write context.') self[k] = ctx['factory'].produce(pobj, v) # TODO: patternProperties here # TODO: fix bug, everything would not go into additionalProperties, instead of recursive elif obj.additionalProperties == True: ctx['addp'] = True elif obj.additionalProperties not in (None, False): ctx['addp_schema'] = obj in_obj = set(six.iterkeys(obj.properties)) in_self = set(six.iterkeys(self)) other_prop = in_obj - in_self for k in other_prop: p = obj.properties[k] if p.is_set("default"): self[k] = ctx['factory'].produce(p, p.default) not_found = set(obj.required) - set(six.iterkeys(self)) if len(not_found): raise ValueError('Model missing required key(s): {0}'.format(', '.join(not_found))) # remove assigned properties to avoid duplicated # primitive creation _val = {} for k in set(six.iterkeys(val)) - in_obj: _val[k] = val[k] if obj.discriminator: self[obj.discriminator] = ctx['name'] return _val
[ "def", "apply_with", "(", "self", ",", "obj", ",", "val", ",", "ctx", ")", ":", "for", "k", ",", "v", "in", "six", ".", "iteritems", "(", "val", ")", ":", "if", "k", "in", "obj", ".", "properties", ":", "pobj", "=", "obj", ".", "properties", ".", "get", "(", "k", ")", "if", "pobj", ".", "readOnly", "==", "True", "and", "ctx", "[", "'read'", "]", "==", "False", ":", "raise", "Exception", "(", "'read-only property is set in write context.'", ")", "self", "[", "k", "]", "=", "ctx", "[", "'factory'", "]", ".", "produce", "(", "pobj", ",", "v", ")", "# TODO: patternProperties here", "# TODO: fix bug, everything would not go into additionalProperties, instead of recursive", "elif", "obj", ".", "additionalProperties", "==", "True", ":", "ctx", "[", "'addp'", "]", "=", "True", "elif", "obj", ".", "additionalProperties", "not", "in", "(", "None", ",", "False", ")", ":", "ctx", "[", "'addp_schema'", "]", "=", "obj", "in_obj", "=", "set", "(", "six", ".", "iterkeys", "(", "obj", ".", "properties", ")", ")", "in_self", "=", "set", "(", "six", ".", "iterkeys", "(", "self", ")", ")", "other_prop", "=", "in_obj", "-", "in_self", "for", "k", "in", "other_prop", ":", "p", "=", "obj", ".", "properties", "[", "k", "]", "if", "p", ".", "is_set", "(", "\"default\"", ")", ":", "self", "[", "k", "]", "=", "ctx", "[", "'factory'", "]", ".", "produce", "(", "p", ",", "p", ".", "default", ")", "not_found", "=", "set", "(", "obj", ".", "required", ")", "-", "set", "(", "six", ".", "iterkeys", "(", "self", ")", ")", "if", "len", "(", "not_found", ")", ":", "raise", "ValueError", "(", "'Model missing required key(s): {0}'", ".", "format", "(", "', '", ".", "join", "(", "not_found", ")", ")", ")", "# remove assigned properties to avoid duplicated", "# primitive creation", "_val", "=", "{", "}", "for", "k", "in", "set", "(", "six", ".", "iterkeys", "(", "val", ")", ")", "-", "in_obj", ":", "_val", "[", "k", "]", "=", "val", "[", "k", "]", "if", "obj", ".", "discriminator", ":", "self", "[", "obj", ".", "discriminator", "]", "=", "ctx", "[", "'name'", "]", "return", "_val" ]
recursively apply Schema object :param obj.Model obj: model object to instruct how to create this model :param dict val: things used to construct this model
[ "recursively", "apply", "Schema", "object" ]
333c4ca08e758cd2194943d9904a3eda3fe43977
https://github.com/pyopenapi/pyswagger/blob/333c4ca08e758cd2194943d9904a3eda3fe43977/pyswagger/primitives/_model.py#L17-L60
7,192
pyopenapi/pyswagger
pyswagger/scanner/v2_0/yaml.py
YamlFixer._op
def _op(self, _, obj, app): """ convert status code in Responses from int to string """ if obj.responses == None: return tmp = {} for k, v in six.iteritems(obj.responses): if isinstance(k, six.integer_types): tmp[str(k)] = v else: tmp[k] = v obj.update_field('responses', tmp)
python
def _op(self, _, obj, app): """ convert status code in Responses from int to string """ if obj.responses == None: return tmp = {} for k, v in six.iteritems(obj.responses): if isinstance(k, six.integer_types): tmp[str(k)] = v else: tmp[k] = v obj.update_field('responses', tmp)
[ "def", "_op", "(", "self", ",", "_", ",", "obj", ",", "app", ")", ":", "if", "obj", ".", "responses", "==", "None", ":", "return", "tmp", "=", "{", "}", "for", "k", ",", "v", "in", "six", ".", "iteritems", "(", "obj", ".", "responses", ")", ":", "if", "isinstance", "(", "k", ",", "six", ".", "integer_types", ")", ":", "tmp", "[", "str", "(", "k", ")", "]", "=", "v", "else", ":", "tmp", "[", "k", "]", "=", "v", "obj", ".", "update_field", "(", "'responses'", ",", "tmp", ")" ]
convert status code in Responses from int to string
[ "convert", "status", "code", "in", "Responses", "from", "int", "to", "string" ]
333c4ca08e758cd2194943d9904a3eda3fe43977
https://github.com/pyopenapi/pyswagger/blob/333c4ca08e758cd2194943d9904a3eda3fe43977/pyswagger/scanner/v2_0/yaml.py#L15-L26
7,193
pyopenapi/pyswagger
pyswagger/primitives/__init__.py
Primitive.produce
def produce(self, obj, val, ctx=None): """ factory function to create primitives :param pyswagger.spec.v2_0.objects.Schema obj: spec to construct primitives :param val: value to construct primitives :return: the created primitive """ val = obj.default if val == None else val if val == None: return None obj = deref(obj) ctx = {} if ctx == None else ctx if 'name' not in ctx and hasattr(obj, 'name'): ctx['name'] = obj.name if 'guard' not in ctx: ctx['guard'] = CycleGuard() if 'addp_schema' not in ctx: # Schema Object of additionalProperties ctx['addp_schema'] = None if 'addp' not in ctx: # additionalProperties ctx['addp'] = False if '2nd_pass' not in ctx: # 2nd pass processing function ctx['2nd_pass'] = None if 'factory' not in ctx: # primitive factory ctx['factory'] = self if 'read' not in ctx: # default is in 'read' context ctx['read'] = True # cycle guard ctx['guard'].update(obj) ret = None if obj.type: creater, _2nd = self.get(_type=obj.type, _format=obj.format) if not creater: raise ValueError('Can\'t resolve type from:(' + str(obj.type) + ', ' + str(obj.format) + ')') ret = creater(obj, val, ctx) if _2nd: val = _2nd(obj, ret, val, ctx) ctx['2nd_pass'] = _2nd elif len(obj.properties) or obj.additionalProperties: ret = Model() val = ret.apply_with(obj, val, ctx) if isinstance(ret, (Date, Datetime, Byte, File)): # it's meanless to handle allOf for these types. return ret def _apply(o, r, v, c): if hasattr(ret, 'apply_with'): v = r.apply_with(o, v, c) else: _2nd = c['2nd_pass'] if _2nd == None: _, _2nd = self.get(_type=o.type, _format=o.format) if _2nd: _2nd(o, r, v, c) # update it back to context c['2nd_pass'] = _2nd return v # handle allOf for Schema Object allOf = getattr(obj, 'allOf', None) if allOf: not_applied = [] for a in allOf: a = deref(a) if not ret: # try to find right type for this primitive. ret = self.produce(a, val, ctx) is_member = hasattr(ret, 'apply_with') else: val = _apply(a, ret, val, ctx) if not ret: # if we still can't determine the type, # keep this Schema object for later use. not_applied.append(a) if ret: for a in not_applied: val = _apply(a, ret, val, ctx) if ret != None and hasattr(ret, 'cleanup'): val = ret.cleanup(val, ctx) return ret
python
def produce(self, obj, val, ctx=None): """ factory function to create primitives :param pyswagger.spec.v2_0.objects.Schema obj: spec to construct primitives :param val: value to construct primitives :return: the created primitive """ val = obj.default if val == None else val if val == None: return None obj = deref(obj) ctx = {} if ctx == None else ctx if 'name' not in ctx and hasattr(obj, 'name'): ctx['name'] = obj.name if 'guard' not in ctx: ctx['guard'] = CycleGuard() if 'addp_schema' not in ctx: # Schema Object of additionalProperties ctx['addp_schema'] = None if 'addp' not in ctx: # additionalProperties ctx['addp'] = False if '2nd_pass' not in ctx: # 2nd pass processing function ctx['2nd_pass'] = None if 'factory' not in ctx: # primitive factory ctx['factory'] = self if 'read' not in ctx: # default is in 'read' context ctx['read'] = True # cycle guard ctx['guard'].update(obj) ret = None if obj.type: creater, _2nd = self.get(_type=obj.type, _format=obj.format) if not creater: raise ValueError('Can\'t resolve type from:(' + str(obj.type) + ', ' + str(obj.format) + ')') ret = creater(obj, val, ctx) if _2nd: val = _2nd(obj, ret, val, ctx) ctx['2nd_pass'] = _2nd elif len(obj.properties) or obj.additionalProperties: ret = Model() val = ret.apply_with(obj, val, ctx) if isinstance(ret, (Date, Datetime, Byte, File)): # it's meanless to handle allOf for these types. return ret def _apply(o, r, v, c): if hasattr(ret, 'apply_with'): v = r.apply_with(o, v, c) else: _2nd = c['2nd_pass'] if _2nd == None: _, _2nd = self.get(_type=o.type, _format=o.format) if _2nd: _2nd(o, r, v, c) # update it back to context c['2nd_pass'] = _2nd return v # handle allOf for Schema Object allOf = getattr(obj, 'allOf', None) if allOf: not_applied = [] for a in allOf: a = deref(a) if not ret: # try to find right type for this primitive. ret = self.produce(a, val, ctx) is_member = hasattr(ret, 'apply_with') else: val = _apply(a, ret, val, ctx) if not ret: # if we still can't determine the type, # keep this Schema object for later use. not_applied.append(a) if ret: for a in not_applied: val = _apply(a, ret, val, ctx) if ret != None and hasattr(ret, 'cleanup'): val = ret.cleanup(val, ctx) return ret
[ "def", "produce", "(", "self", ",", "obj", ",", "val", ",", "ctx", "=", "None", ")", ":", "val", "=", "obj", ".", "default", "if", "val", "==", "None", "else", "val", "if", "val", "==", "None", ":", "return", "None", "obj", "=", "deref", "(", "obj", ")", "ctx", "=", "{", "}", "if", "ctx", "==", "None", "else", "ctx", "if", "'name'", "not", "in", "ctx", "and", "hasattr", "(", "obj", ",", "'name'", ")", ":", "ctx", "[", "'name'", "]", "=", "obj", ".", "name", "if", "'guard'", "not", "in", "ctx", ":", "ctx", "[", "'guard'", "]", "=", "CycleGuard", "(", ")", "if", "'addp_schema'", "not", "in", "ctx", ":", "# Schema Object of additionalProperties", "ctx", "[", "'addp_schema'", "]", "=", "None", "if", "'addp'", "not", "in", "ctx", ":", "# additionalProperties", "ctx", "[", "'addp'", "]", "=", "False", "if", "'2nd_pass'", "not", "in", "ctx", ":", "# 2nd pass processing function", "ctx", "[", "'2nd_pass'", "]", "=", "None", "if", "'factory'", "not", "in", "ctx", ":", "# primitive factory", "ctx", "[", "'factory'", "]", "=", "self", "if", "'read'", "not", "in", "ctx", ":", "# default is in 'read' context", "ctx", "[", "'read'", "]", "=", "True", "# cycle guard", "ctx", "[", "'guard'", "]", ".", "update", "(", "obj", ")", "ret", "=", "None", "if", "obj", ".", "type", ":", "creater", ",", "_2nd", "=", "self", ".", "get", "(", "_type", "=", "obj", ".", "type", ",", "_format", "=", "obj", ".", "format", ")", "if", "not", "creater", ":", "raise", "ValueError", "(", "'Can\\'t resolve type from:('", "+", "str", "(", "obj", ".", "type", ")", "+", "', '", "+", "str", "(", "obj", ".", "format", ")", "+", "')'", ")", "ret", "=", "creater", "(", "obj", ",", "val", ",", "ctx", ")", "if", "_2nd", ":", "val", "=", "_2nd", "(", "obj", ",", "ret", ",", "val", ",", "ctx", ")", "ctx", "[", "'2nd_pass'", "]", "=", "_2nd", "elif", "len", "(", "obj", ".", "properties", ")", "or", "obj", ".", "additionalProperties", ":", "ret", "=", "Model", "(", ")", "val", "=", "ret", ".", "apply_with", "(", "obj", ",", "val", ",", "ctx", ")", "if", "isinstance", "(", "ret", ",", "(", "Date", ",", "Datetime", ",", "Byte", ",", "File", ")", ")", ":", "# it's meanless to handle allOf for these types.", "return", "ret", "def", "_apply", "(", "o", ",", "r", ",", "v", ",", "c", ")", ":", "if", "hasattr", "(", "ret", ",", "'apply_with'", ")", ":", "v", "=", "r", ".", "apply_with", "(", "o", ",", "v", ",", "c", ")", "else", ":", "_2nd", "=", "c", "[", "'2nd_pass'", "]", "if", "_2nd", "==", "None", ":", "_", ",", "_2nd", "=", "self", ".", "get", "(", "_type", "=", "o", ".", "type", ",", "_format", "=", "o", ".", "format", ")", "if", "_2nd", ":", "_2nd", "(", "o", ",", "r", ",", "v", ",", "c", ")", "# update it back to context", "c", "[", "'2nd_pass'", "]", "=", "_2nd", "return", "v", "# handle allOf for Schema Object", "allOf", "=", "getattr", "(", "obj", ",", "'allOf'", ",", "None", ")", "if", "allOf", ":", "not_applied", "=", "[", "]", "for", "a", "in", "allOf", ":", "a", "=", "deref", "(", "a", ")", "if", "not", "ret", ":", "# try to find right type for this primitive.", "ret", "=", "self", ".", "produce", "(", "a", ",", "val", ",", "ctx", ")", "is_member", "=", "hasattr", "(", "ret", ",", "'apply_with'", ")", "else", ":", "val", "=", "_apply", "(", "a", ",", "ret", ",", "val", ",", "ctx", ")", "if", "not", "ret", ":", "# if we still can't determine the type,", "# keep this Schema object for later use.", "not_applied", ".", "append", "(", "a", ")", "if", "ret", ":", "for", "a", "in", "not_applied", ":", "val", "=", "_apply", "(", "a", ",", "ret", ",", "val", ",", "ctx", ")", "if", "ret", "!=", "None", "and", "hasattr", "(", "ret", ",", "'cleanup'", ")", ":", "val", "=", "ret", ".", "cleanup", "(", "val", ",", "ctx", ")", "return", "ret" ]
factory function to create primitives :param pyswagger.spec.v2_0.objects.Schema obj: spec to construct primitives :param val: value to construct primitives :return: the created primitive
[ "factory", "function", "to", "create", "primitives" ]
333c4ca08e758cd2194943d9904a3eda3fe43977
https://github.com/pyopenapi/pyswagger/blob/333c4ca08e758cd2194943d9904a3eda3fe43977/pyswagger/primitives/__init__.py#L151-L243
7,194
arogozhnikov/einops
einops/einops.py
_check_elementary_axis_name
def _check_elementary_axis_name(name: str) -> bool: """ Valid elementary axes contain only lower latin letters and digits and start with a letter. """ if len(name) == 0: return False if not 'a' <= name[0] <= 'z': return False for letter in name: if (not letter.isdigit()) and not ('a' <= letter <= 'z'): return False return True
python
def _check_elementary_axis_name(name: str) -> bool: """ Valid elementary axes contain only lower latin letters and digits and start with a letter. """ if len(name) == 0: return False if not 'a' <= name[0] <= 'z': return False for letter in name: if (not letter.isdigit()) and not ('a' <= letter <= 'z'): return False return True
[ "def", "_check_elementary_axis_name", "(", "name", ":", "str", ")", "->", "bool", ":", "if", "len", "(", "name", ")", "==", "0", ":", "return", "False", "if", "not", "'a'", "<=", "name", "[", "0", "]", "<=", "'z'", ":", "return", "False", "for", "letter", "in", "name", ":", "if", "(", "not", "letter", ".", "isdigit", "(", ")", ")", "and", "not", "(", "'a'", "<=", "letter", "<=", "'z'", ")", ":", "return", "False", "return", "True" ]
Valid elementary axes contain only lower latin letters and digits and start with a letter.
[ "Valid", "elementary", "axes", "contain", "only", "lower", "latin", "letters", "and", "digits", "and", "start", "with", "a", "letter", "." ]
9698f0f5efa6c5a79daa75253137ba5d79a95615
https://github.com/arogozhnikov/einops/blob/9698f0f5efa6c5a79daa75253137ba5d79a95615/einops/einops.py#L268-L279
7,195
Kautenja/nes-py
nes_py/_image_viewer.py
ImageViewer.open
def open(self): """Open the window.""" self._window = Window( caption=self.caption, height=self.height, width=self.width, vsync=False, resizable=True, )
python
def open(self): """Open the window.""" self._window = Window( caption=self.caption, height=self.height, width=self.width, vsync=False, resizable=True, )
[ "def", "open", "(", "self", ")", ":", "self", ".", "_window", "=", "Window", "(", "caption", "=", "self", ".", "caption", ",", "height", "=", "self", ".", "height", ",", "width", "=", "self", ".", "width", ",", "vsync", "=", "False", ",", "resizable", "=", "True", ",", ")" ]
Open the window.
[ "Open", "the", "window", "." ]
a113885198d418f38fcf24b8f79ac508975788c2
https://github.com/Kautenja/nes-py/blob/a113885198d418f38fcf24b8f79ac508975788c2/nes_py/_image_viewer.py#L40-L48
7,196
Kautenja/nes-py
nes_py/_image_viewer.py
ImageViewer.show
def show(self, frame): """ Show an array of pixels on the window. Args: frame (numpy.ndarray): the frame to show on the window Returns: None """ # check that the frame has the correct dimensions if len(frame.shape) != 3: raise ValueError('frame should have shape with only 3 dimensions') # open the window if it isn't open already if not self.is_open: self.open() # prepare the window for the next frame self._window.clear() self._window.switch_to() self._window.dispatch_events() # create an image data object image = ImageData( frame.shape[1], frame.shape[0], 'RGB', frame.tobytes(), pitch=frame.shape[1]*-3 ) # send the image to the window image.blit(0, 0, width=self._window.width, height=self._window.height) self._window.flip()
python
def show(self, frame): """ Show an array of pixels on the window. Args: frame (numpy.ndarray): the frame to show on the window Returns: None """ # check that the frame has the correct dimensions if len(frame.shape) != 3: raise ValueError('frame should have shape with only 3 dimensions') # open the window if it isn't open already if not self.is_open: self.open() # prepare the window for the next frame self._window.clear() self._window.switch_to() self._window.dispatch_events() # create an image data object image = ImageData( frame.shape[1], frame.shape[0], 'RGB', frame.tobytes(), pitch=frame.shape[1]*-3 ) # send the image to the window image.blit(0, 0, width=self._window.width, height=self._window.height) self._window.flip()
[ "def", "show", "(", "self", ",", "frame", ")", ":", "# check that the frame has the correct dimensions", "if", "len", "(", "frame", ".", "shape", ")", "!=", "3", ":", "raise", "ValueError", "(", "'frame should have shape with only 3 dimensions'", ")", "# open the window if it isn't open already", "if", "not", "self", ".", "is_open", ":", "self", ".", "open", "(", ")", "# prepare the window for the next frame", "self", ".", "_window", ".", "clear", "(", ")", "self", ".", "_window", ".", "switch_to", "(", ")", "self", ".", "_window", ".", "dispatch_events", "(", ")", "# create an image data object", "image", "=", "ImageData", "(", "frame", ".", "shape", "[", "1", "]", ",", "frame", ".", "shape", "[", "0", "]", ",", "'RGB'", ",", "frame", ".", "tobytes", "(", ")", ",", "pitch", "=", "frame", ".", "shape", "[", "1", "]", "*", "-", "3", ")", "# send the image to the window", "image", ".", "blit", "(", "0", ",", "0", ",", "width", "=", "self", ".", "_window", ".", "width", ",", "height", "=", "self", ".", "_window", ".", "height", ")", "self", ".", "_window", ".", "flip", "(", ")" ]
Show an array of pixels on the window. Args: frame (numpy.ndarray): the frame to show on the window Returns: None
[ "Show", "an", "array", "of", "pixels", "on", "the", "window", "." ]
a113885198d418f38fcf24b8f79ac508975788c2
https://github.com/Kautenja/nes-py/blob/a113885198d418f38fcf24b8f79ac508975788c2/nes_py/_image_viewer.py#L50-L80
7,197
Kautenja/nes-py
nes_py/app/play_human.py
display_arr
def display_arr(screen, arr, video_size, transpose): """ Display an image to the pygame screen. Args: screen (pygame.Surface): the pygame surface to write frames to arr (np.ndarray): numpy array representing a single frame of gameplay video_size (tuple): the size to render the frame as transpose (bool): whether to transpose the frame before displaying Returns: None """ # take the transpose if necessary if transpose: pyg_img = pygame.surfarray.make_surface(arr.swapaxes(0, 1)) else: pyg_img = arr # resize the image according to given image size pyg_img = pygame.transform.scale(pyg_img, video_size) # blit the image to the surface screen.blit(pyg_img, (0, 0))
python
def display_arr(screen, arr, video_size, transpose): """ Display an image to the pygame screen. Args: screen (pygame.Surface): the pygame surface to write frames to arr (np.ndarray): numpy array representing a single frame of gameplay video_size (tuple): the size to render the frame as transpose (bool): whether to transpose the frame before displaying Returns: None """ # take the transpose if necessary if transpose: pyg_img = pygame.surfarray.make_surface(arr.swapaxes(0, 1)) else: pyg_img = arr # resize the image according to given image size pyg_img = pygame.transform.scale(pyg_img, video_size) # blit the image to the surface screen.blit(pyg_img, (0, 0))
[ "def", "display_arr", "(", "screen", ",", "arr", ",", "video_size", ",", "transpose", ")", ":", "# take the transpose if necessary", "if", "transpose", ":", "pyg_img", "=", "pygame", ".", "surfarray", ".", "make_surface", "(", "arr", ".", "swapaxes", "(", "0", ",", "1", ")", ")", "else", ":", "pyg_img", "=", "arr", "# resize the image according to given image size", "pyg_img", "=", "pygame", ".", "transform", ".", "scale", "(", "pyg_img", ",", "video_size", ")", "# blit the image to the surface", "screen", ".", "blit", "(", "pyg_img", ",", "(", "0", ",", "0", ")", ")" ]
Display an image to the pygame screen. Args: screen (pygame.Surface): the pygame surface to write frames to arr (np.ndarray): numpy array representing a single frame of gameplay video_size (tuple): the size to render the frame as transpose (bool): whether to transpose the frame before displaying Returns: None
[ "Display", "an", "image", "to", "the", "pygame", "screen", "." ]
a113885198d418f38fcf24b8f79ac508975788c2
https://github.com/Kautenja/nes-py/blob/a113885198d418f38fcf24b8f79ac508975788c2/nes_py/app/play_human.py#L6-L28
7,198
Kautenja/nes-py
nes_py/app/play_human.py
play
def play(env, transpose=True, fps=30, nop_=0): """Play the game using the keyboard as a human. Args: env (gym.Env): the environment to use for playing transpose (bool): whether to transpose frame before viewing them fps (int): number of steps of the environment to execute every second nop_ (any): the object to use as a null op action for the environment Returns: None """ # ensure the observation space is a box of pixels assert isinstance(env.observation_space, gym.spaces.box.Box) # ensure the observation space is either B&W pixels or RGB Pixels obs_s = env.observation_space is_bw = len(obs_s.shape) == 2 is_rgb = len(obs_s.shape) == 3 and obs_s.shape[2] in [1, 3] assert is_bw or is_rgb # get the mapping of keyboard keys to actions in the environment if hasattr(env, 'get_keys_to_action'): keys_to_action = env.get_keys_to_action() # get the mapping of keyboard keys to actions in the unwrapped environment elif hasattr(env.unwrapped, 'get_keys_to_action'): keys_to_action = env.unwrapped.get_keys_to_action() else: raise ValueError('env has no get_keys_to_action method') relevant_keys = set(sum(map(list, keys_to_action.keys()), [])) # determine the size of the video in pixels video_size = env.observation_space.shape[0], env.observation_space.shape[1] if transpose: video_size = tuple(reversed(video_size)) # generate variables to determine the running state of the game pressed_keys = [] running = True env_done = True # setup the screen using pygame flags = pygame.RESIZABLE | pygame.HWSURFACE | pygame.DOUBLEBUF screen = pygame.display.set_mode(video_size, flags) pygame.event.set_blocked(pygame.MOUSEMOTION) # set the caption for the pygame window. if the env has a spec use its id if env.spec is not None: pygame.display.set_caption(env.spec.id) # otherwise just use the default nes-py caption else: pygame.display.set_caption('nes-py') # start a clock for limiting the frame rate to the given FPS clock = pygame.time.Clock() # start the main game loop while running: # reset if the environment is done if env_done: env_done = False obs = env.reset() # otherwise take a normal step else: # unwrap the action based on pressed relevant keys action = keys_to_action.get(tuple(sorted(pressed_keys)), nop_) obs, rew, env_done, info = env.step(action) # make sure the observation exists if obs is not None: # if the observation is just height and width (B&W) if len(obs.shape) == 2: # add a dummy channel for pygame display obs = obs[:, :, None] # if the observation is single channel (B&W) if obs.shape[2] == 1: # repeat the single channel 3 times for RGB encoding of B&W obs = obs.repeat(3, axis=2) # display the observation on the pygame screen display_arr(screen, obs, video_size, transpose) # process keyboard events for event in pygame.event.get(): # handle a key being pressed if event.type == pygame.KEYDOWN: # make sure the key is in the relevant key list if event.key in relevant_keys: # add the key to pressed keys pressed_keys.append(event.key) # ASCII code 27 is the "escape" key elif event.key == 27: running = False # handle the backup and reset functions elif event.key == ord('e'): env.unwrapped._backup() elif event.key == ord('r'): env.unwrapped._restore() # handle a key being released elif event.type == pygame.KEYUP: # make sure the key is in the relevant key list if event.key in relevant_keys: # remove the key from the pressed keys pressed_keys.remove(event.key) # if the event is quit, set running to False elif event.type == pygame.QUIT: running = False # flip the pygame screen pygame.display.flip() # throttle to maintain the framerate clock.tick(fps) # quite the pygame setup pygame.quit()
python
def play(env, transpose=True, fps=30, nop_=0): """Play the game using the keyboard as a human. Args: env (gym.Env): the environment to use for playing transpose (bool): whether to transpose frame before viewing them fps (int): number of steps of the environment to execute every second nop_ (any): the object to use as a null op action for the environment Returns: None """ # ensure the observation space is a box of pixels assert isinstance(env.observation_space, gym.spaces.box.Box) # ensure the observation space is either B&W pixels or RGB Pixels obs_s = env.observation_space is_bw = len(obs_s.shape) == 2 is_rgb = len(obs_s.shape) == 3 and obs_s.shape[2] in [1, 3] assert is_bw or is_rgb # get the mapping of keyboard keys to actions in the environment if hasattr(env, 'get_keys_to_action'): keys_to_action = env.get_keys_to_action() # get the mapping of keyboard keys to actions in the unwrapped environment elif hasattr(env.unwrapped, 'get_keys_to_action'): keys_to_action = env.unwrapped.get_keys_to_action() else: raise ValueError('env has no get_keys_to_action method') relevant_keys = set(sum(map(list, keys_to_action.keys()), [])) # determine the size of the video in pixels video_size = env.observation_space.shape[0], env.observation_space.shape[1] if transpose: video_size = tuple(reversed(video_size)) # generate variables to determine the running state of the game pressed_keys = [] running = True env_done = True # setup the screen using pygame flags = pygame.RESIZABLE | pygame.HWSURFACE | pygame.DOUBLEBUF screen = pygame.display.set_mode(video_size, flags) pygame.event.set_blocked(pygame.MOUSEMOTION) # set the caption for the pygame window. if the env has a spec use its id if env.spec is not None: pygame.display.set_caption(env.spec.id) # otherwise just use the default nes-py caption else: pygame.display.set_caption('nes-py') # start a clock for limiting the frame rate to the given FPS clock = pygame.time.Clock() # start the main game loop while running: # reset if the environment is done if env_done: env_done = False obs = env.reset() # otherwise take a normal step else: # unwrap the action based on pressed relevant keys action = keys_to_action.get(tuple(sorted(pressed_keys)), nop_) obs, rew, env_done, info = env.step(action) # make sure the observation exists if obs is not None: # if the observation is just height and width (B&W) if len(obs.shape) == 2: # add a dummy channel for pygame display obs = obs[:, :, None] # if the observation is single channel (B&W) if obs.shape[2] == 1: # repeat the single channel 3 times for RGB encoding of B&W obs = obs.repeat(3, axis=2) # display the observation on the pygame screen display_arr(screen, obs, video_size, transpose) # process keyboard events for event in pygame.event.get(): # handle a key being pressed if event.type == pygame.KEYDOWN: # make sure the key is in the relevant key list if event.key in relevant_keys: # add the key to pressed keys pressed_keys.append(event.key) # ASCII code 27 is the "escape" key elif event.key == 27: running = False # handle the backup and reset functions elif event.key == ord('e'): env.unwrapped._backup() elif event.key == ord('r'): env.unwrapped._restore() # handle a key being released elif event.type == pygame.KEYUP: # make sure the key is in the relevant key list if event.key in relevant_keys: # remove the key from the pressed keys pressed_keys.remove(event.key) # if the event is quit, set running to False elif event.type == pygame.QUIT: running = False # flip the pygame screen pygame.display.flip() # throttle to maintain the framerate clock.tick(fps) # quite the pygame setup pygame.quit()
[ "def", "play", "(", "env", ",", "transpose", "=", "True", ",", "fps", "=", "30", ",", "nop_", "=", "0", ")", ":", "# ensure the observation space is a box of pixels", "assert", "isinstance", "(", "env", ".", "observation_space", ",", "gym", ".", "spaces", ".", "box", ".", "Box", ")", "# ensure the observation space is either B&W pixels or RGB Pixels", "obs_s", "=", "env", ".", "observation_space", "is_bw", "=", "len", "(", "obs_s", ".", "shape", ")", "==", "2", "is_rgb", "=", "len", "(", "obs_s", ".", "shape", ")", "==", "3", "and", "obs_s", ".", "shape", "[", "2", "]", "in", "[", "1", ",", "3", "]", "assert", "is_bw", "or", "is_rgb", "# get the mapping of keyboard keys to actions in the environment", "if", "hasattr", "(", "env", ",", "'get_keys_to_action'", ")", ":", "keys_to_action", "=", "env", ".", "get_keys_to_action", "(", ")", "# get the mapping of keyboard keys to actions in the unwrapped environment", "elif", "hasattr", "(", "env", ".", "unwrapped", ",", "'get_keys_to_action'", ")", ":", "keys_to_action", "=", "env", ".", "unwrapped", ".", "get_keys_to_action", "(", ")", "else", ":", "raise", "ValueError", "(", "'env has no get_keys_to_action method'", ")", "relevant_keys", "=", "set", "(", "sum", "(", "map", "(", "list", ",", "keys_to_action", ".", "keys", "(", ")", ")", ",", "[", "]", ")", ")", "# determine the size of the video in pixels", "video_size", "=", "env", ".", "observation_space", ".", "shape", "[", "0", "]", ",", "env", ".", "observation_space", ".", "shape", "[", "1", "]", "if", "transpose", ":", "video_size", "=", "tuple", "(", "reversed", "(", "video_size", ")", ")", "# generate variables to determine the running state of the game", "pressed_keys", "=", "[", "]", "running", "=", "True", "env_done", "=", "True", "# setup the screen using pygame", "flags", "=", "pygame", ".", "RESIZABLE", "|", "pygame", ".", "HWSURFACE", "|", "pygame", ".", "DOUBLEBUF", "screen", "=", "pygame", ".", "display", ".", "set_mode", "(", "video_size", ",", "flags", ")", "pygame", ".", "event", ".", "set_blocked", "(", "pygame", ".", "MOUSEMOTION", ")", "# set the caption for the pygame window. if the env has a spec use its id", "if", "env", ".", "spec", "is", "not", "None", ":", "pygame", ".", "display", ".", "set_caption", "(", "env", ".", "spec", ".", "id", ")", "# otherwise just use the default nes-py caption", "else", ":", "pygame", ".", "display", ".", "set_caption", "(", "'nes-py'", ")", "# start a clock for limiting the frame rate to the given FPS", "clock", "=", "pygame", ".", "time", ".", "Clock", "(", ")", "# start the main game loop", "while", "running", ":", "# reset if the environment is done", "if", "env_done", ":", "env_done", "=", "False", "obs", "=", "env", ".", "reset", "(", ")", "# otherwise take a normal step", "else", ":", "# unwrap the action based on pressed relevant keys", "action", "=", "keys_to_action", ".", "get", "(", "tuple", "(", "sorted", "(", "pressed_keys", ")", ")", ",", "nop_", ")", "obs", ",", "rew", ",", "env_done", ",", "info", "=", "env", ".", "step", "(", "action", ")", "# make sure the observation exists", "if", "obs", "is", "not", "None", ":", "# if the observation is just height and width (B&W)", "if", "len", "(", "obs", ".", "shape", ")", "==", "2", ":", "# add a dummy channel for pygame display", "obs", "=", "obs", "[", ":", ",", ":", ",", "None", "]", "# if the observation is single channel (B&W)", "if", "obs", ".", "shape", "[", "2", "]", "==", "1", ":", "# repeat the single channel 3 times for RGB encoding of B&W", "obs", "=", "obs", ".", "repeat", "(", "3", ",", "axis", "=", "2", ")", "# display the observation on the pygame screen", "display_arr", "(", "screen", ",", "obs", ",", "video_size", ",", "transpose", ")", "# process keyboard events", "for", "event", "in", "pygame", ".", "event", ".", "get", "(", ")", ":", "# handle a key being pressed", "if", "event", ".", "type", "==", "pygame", ".", "KEYDOWN", ":", "# make sure the key is in the relevant key list", "if", "event", ".", "key", "in", "relevant_keys", ":", "# add the key to pressed keys", "pressed_keys", ".", "append", "(", "event", ".", "key", ")", "# ASCII code 27 is the \"escape\" key", "elif", "event", ".", "key", "==", "27", ":", "running", "=", "False", "# handle the backup and reset functions", "elif", "event", ".", "key", "==", "ord", "(", "'e'", ")", ":", "env", ".", "unwrapped", ".", "_backup", "(", ")", "elif", "event", ".", "key", "==", "ord", "(", "'r'", ")", ":", "env", ".", "unwrapped", ".", "_restore", "(", ")", "# handle a key being released", "elif", "event", ".", "type", "==", "pygame", ".", "KEYUP", ":", "# make sure the key is in the relevant key list", "if", "event", ".", "key", "in", "relevant_keys", ":", "# remove the key from the pressed keys", "pressed_keys", ".", "remove", "(", "event", ".", "key", ")", "# if the event is quit, set running to False", "elif", "event", ".", "type", "==", "pygame", ".", "QUIT", ":", "running", "=", "False", "# flip the pygame screen", "pygame", ".", "display", ".", "flip", "(", ")", "# throttle to maintain the framerate", "clock", ".", "tick", "(", "fps", ")", "# quite the pygame setup", "pygame", ".", "quit", "(", ")" ]
Play the game using the keyboard as a human. Args: env (gym.Env): the environment to use for playing transpose (bool): whether to transpose frame before viewing them fps (int): number of steps of the environment to execute every second nop_ (any): the object to use as a null op action for the environment Returns: None
[ "Play", "the", "game", "using", "the", "keyboard", "as", "a", "human", "." ]
a113885198d418f38fcf24b8f79ac508975788c2
https://github.com/Kautenja/nes-py/blob/a113885198d418f38fcf24b8f79ac508975788c2/nes_py/app/play_human.py#L31-L135
7,199
Kautenja/nes-py
nes_py/app/play_human.py
play_human
def play_human(env): """ Play the environment using keyboard as a human. Args: env (gym.Env): the initialized gym environment to play Returns: None """ # play the game and catch a potential keyboard interrupt try: play(env, fps=env.metadata['video.frames_per_second']) except KeyboardInterrupt: pass # reset and close the environment env.close()
python
def play_human(env): """ Play the environment using keyboard as a human. Args: env (gym.Env): the initialized gym environment to play Returns: None """ # play the game and catch a potential keyboard interrupt try: play(env, fps=env.metadata['video.frames_per_second']) except KeyboardInterrupt: pass # reset and close the environment env.close()
[ "def", "play_human", "(", "env", ")", ":", "# play the game and catch a potential keyboard interrupt", "try", ":", "play", "(", "env", ",", "fps", "=", "env", ".", "metadata", "[", "'video.frames_per_second'", "]", ")", "except", "KeyboardInterrupt", ":", "pass", "# reset and close the environment", "env", ".", "close", "(", ")" ]
Play the environment using keyboard as a human. Args: env (gym.Env): the initialized gym environment to play Returns: None
[ "Play", "the", "environment", "using", "keyboard", "as", "a", "human", "." ]
a113885198d418f38fcf24b8f79ac508975788c2
https://github.com/Kautenja/nes-py/blob/a113885198d418f38fcf24b8f79ac508975788c2/nes_py/app/play_human.py#L138-L155