id
int64
0
843k
repository_name
stringlengths
7
55
file_path
stringlengths
9
332
class_name
stringlengths
3
290
human_written_code
stringlengths
12
4.36M
class_skeleton
stringlengths
19
2.2M
total_program_units
int64
1
9.57k
total_doc_str
int64
0
4.2k
AvgCountLine
float64
0
7.89k
AvgCountLineBlank
float64
0
300
AvgCountLineCode
float64
0
7.89k
AvgCountLineComment
float64
0
7.89k
AvgCyclomatic
float64
0
130
CommentToCodeRatio
float64
0
176
CountClassBase
float64
0
48
CountClassCoupled
float64
0
589
CountClassCoupledModified
float64
0
581
CountClassDerived
float64
0
5.37k
CountDeclInstanceMethod
float64
0
4.2k
CountDeclInstanceVariable
float64
0
299
CountDeclMethod
float64
0
4.2k
CountDeclMethodAll
float64
0
4.2k
CountLine
float64
1
115k
CountLineBlank
float64
0
9.01k
CountLineCode
float64
0
94.4k
CountLineCodeDecl
float64
0
46.1k
CountLineCodeExe
float64
0
91.3k
CountLineComment
float64
0
27k
CountStmt
float64
1
93.2k
CountStmtDecl
float64
0
46.1k
CountStmtExe
float64
0
90.2k
MaxCyclomatic
float64
0
759
MaxInheritanceTree
float64
0
16
MaxNesting
float64
0
34
SumCyclomatic
float64
0
6k
140,448
Julius2342/pyvlx
Julius2342_pyvlx/old_api/pyvlx/scenes.py
pyvlx.scenes.Scenes
class Scenes: """Object for storing scenes.""" def __init__(self, pyvlx): """Initialize Scenes class.""" self.pyvlx = pyvlx self.__scenes = [] def __iter__(self): """Iterator.""" yield from self.__scenes def __getitem__(self, key): """Return scene by name or by index.""" for scene in self.__scenes: if scene.name == key: return scene if isinstance(key, int): return self.__scenes[key] raise KeyError def __len__(self): """Return number of scenes.""" return len(self.__scenes) def add(self, scene): """Add scene.""" if not isinstance(scene, Scene): raise TypeError() self.__scenes.append(scene) async def load(self): """Load scenes from KLF 200.""" json_response = await self.pyvlx.interface.api_call('scenes', 'get') self.data_import(json_response) def data_import(self, json_response): """Import scenes from JSON response.""" if 'data' not in json_response: raise PyVLXException('no element data found: {0}'.format( json.dumps(json_response))) data = json_response['data'] for item in data: self.load_scene(item) def load_scene(self, item): """Load scene from json.""" scene = Scene.from_config(self.pyvlx, item) self.add(scene)
class Scenes: '''Object for storing scenes.''' def __init__(self, pyvlx): '''Initialize Scenes class.''' pass def __iter__(self): '''Iterator.''' pass def __getitem__(self, key): '''Return scene by name or by index.''' pass def __len__(self): '''Return number of scenes.''' pass def add(self, scene): '''Add scene.''' pass async def load(self): '''Load scenes from KLF 200.''' pass def data_import(self, json_response): '''Import scenes from JSON response.''' pass def load_scene(self, item): '''Load scene from json.''' pass
9
9
5
0
4
1
2
0.28
0
5
2
0
8
2
8
8
49
8
32
16
23
9
31
16
22
4
0
2
14
140,449
Julius2342/pyvlx
Julius2342_pyvlx/pyvlx/scene.py
pyvlx.scene.Scene
class Scene: """Object for scene.""" def __init__(self, pyvlx: "PyVLX", scene_id: int, name: str): """Initialize Scene object. Parameters: * pyvlx: PyVLX object * scene_id: internal id for addressing scenes. Provided by KLF 200 device * name: scene name """ self.pyvlx = pyvlx self.scene_id = scene_id self.name = name async def run(self, wait_for_completion: bool = True) -> None: """Run scene. Parameters: * wait_for_completion: If set, function will return after device has reached target position. """ activate_scene = ActivateScene( pyvlx=self.pyvlx, wait_for_completion=wait_for_completion, scene_id=self.scene_id, ) await activate_scene.do_api_call() if not activate_scene.success: raise PyVLXException("Unable to activate scene") def __str__(self) -> str: """Return object as readable string.""" return '<{} name="{}" id="{}"/>'.format( type(self).__name__, self.name, self.scene_id ) def __eq__(self, other: Any) -> bool: """Equal operator.""" return self.__dict__ == other.__dict__
class Scene: '''Object for scene.''' def __init__(self, pyvlx: "PyVLX", scene_id: int, name: str): '''Initialize Scene object. Parameters: * pyvlx: PyVLX object * scene_id: internal id for addressing scenes. Provided by KLF 200 device * name: scene name ''' pass async def run(self, wait_for_completion: bool = True) -> None: '''Run scene. Parameters: * wait_for_completion: If set, function will return after device has reached target position. ''' pass def __str__(self) -> str: '''Return object as readable string.''' pass def __eq__(self, other: Any) -> bool: '''Equal operator.''' pass
5
5
9
1
5
4
1
0.75
0
7
2
0
4
3
4
4
43
8
20
9
15
15
14
9
9
2
0
1
5
140,450
Julius2342/pyvlx
Julius2342_pyvlx/old_api/pyvlx/scene.py
pyvlx.scene.Scene
class Scene: """Object for scene.""" def __init__(self, pyvlx, ident, name): """Initialize Scene object.""" self.pyvlx = pyvlx self.ident = ident self.name = name @classmethod def from_config(cls, pyvlx, item): """Read scene from configuration.""" name = item['name'] ident = item['id'] return cls(pyvlx, ident, name) async def run(self): """Run scene.""" await self.pyvlx.interface.api_call('scenes', 'run', {'id': self.ident}) def get_name(self): """Return name of object.""" return self.name def __str__(self) -> str: """Return object as readable string.""" return '<Scene name="{0}" ' \ 'id="{1}" />' \ .format( self.name, self.ident) def __eq__(self, other): """Equal operator.""" return self.__dict__ == other.__dict__
class Scene: '''Object for scene.''' def __init__(self, pyvlx, ident, name): '''Initialize Scene object.''' pass @classmethod def from_config(cls, pyvlx, item): '''Read scene from configuration.''' pass async def run(self): '''Run scene.''' pass def get_name(self): '''Return name of object.''' pass def __str__(self) -> str: '''Return object as readable string.''' pass def __eq__(self, other): '''Equal operator.''' pass
8
7
4
0
3
1
1
0.32
0
1
0
0
5
3
6
6
35
6
22
13
14
7
17
12
10
1
0
0
6
140,451
Julius2342/pyvlx
Julius2342_pyvlx/old_api/pyvlx/rollershutter.py
pyvlx.rollershutter.RollerShutter
class RollerShutter(Device): """Class for roller shutters.""" def __init__(self, pyvlx, ident, name, subtype, typeid): """Initialize roller shutter class.""" self.pyvlx = pyvlx self.ident = ident self.name = name self.subtype = subtype self.typeid = typeid Device.__init__(self, pyvlx, ident, name) @classmethod def from_config(cls, pyvlx, item): """Read roller shutter from config.""" name = item['name'] ident = item['id'] subtype = item['subtype'] typeid = item['typeId'] return cls(pyvlx, ident, name, subtype, typeid) def __str__(self) -> str: """Return object as readable string.""" return '<RollerShutter name="{0}" ' \ 'id="{1}" ' \ 'subtype="{2}" ' \ 'typeId="{3}" />' \ .format( self.name, self.ident, self.subtype, self.typeid) def __eq__(self, other): """Equal operator.""" return self.__dict__ == other.__dict__
class RollerShutter(Device): '''Class for roller shutters.''' def __init__(self, pyvlx, ident, name, subtype, typeid): '''Initialize roller shutter class.''' pass @classmethod def from_config(cls, pyvlx, item): '''Read roller shutter from config.''' pass def __str__(self) -> str: '''Return object as readable string.''' pass def __eq__(self, other): '''Equal operator.''' pass
6
5
7
0
6
1
1
0.19
1
1
0
0
3
5
4
6
36
4
27
15
21
5
18
14
13
1
1
0
4
140,452
Julius2342/pyvlx
Julius2342_pyvlx/pyvlx/pyvlx.py
pyvlx.pyvlx.PyVLX
class PyVLX: """Class for PyVLX.""" def __init__( self, path: Optional[str] = None, host: Optional[str] = None, password: Optional[str] = None, loop: Optional[asyncio.AbstractEventLoop] = None, heartbeat_interval: int = 30, heartbeat_load_all_states: bool = True, ): """Initialize PyVLX class.""" self.loop = loop or asyncio.get_event_loop() self.config = Config(self, path, host, password) self.connection = Connection(loop=self.loop, config=self.config) self.heartbeat = Heartbeat( pyvlx=self, interval=heartbeat_interval, load_all_states=heartbeat_load_all_states, ) self.node_updater = NodeUpdater(pyvlx=self) self.nodes = Nodes(self) self.connection.register_frame_received_cb(self.node_updater.process_frame) self.scenes = Scenes(self) self.version = None self.protocol_version = None self.klf200 = Klf200Gateway(pyvlx=self) self.api_call_semaphore = asyncio.Semaphore(1) # Limit parallel commands async def connect(self) -> None: """Connect to KLF 200.""" PYVLXLOG.debug("Connecting to KLF 200") await self.connection.connect() assert self.config.password is not None await self.klf200.password_enter(password=self.config.password) await self.klf200.get_version() await self.klf200.get_protocol_version() PYVLXLOG.debug( "Connected to: %s, %s", str(self.klf200.version), str(self.klf200.protocol_version), ) await self.klf200.house_status_monitor_disable(pyvlx=self) await self.klf200.get_state() await self.klf200.set_utc() await self.klf200.get_network_setup() await self.klf200.house_status_monitor_enable(pyvlx=self) self.heartbeat.start() async def reboot_gateway(self) -> None: """For Compatibility: Reboot the KLF 200.""" if not self.get_connected(): PYVLXLOG.warning("KLF 200 reboot initiated, but gateway is not connected") else: PYVLXLOG.warning("KLF 200 reboot initiated") await self.klf200.reboot() def get_connected(self) -> bool: """Return whether the gateway is currently connected.""" return self.connection.connected async def check_connected(self) -> None: """Check we're connected, and if not, connect.""" if not self.connection.connected: await self.connect() async def send_frame(self, frame: FrameBase) -> None: """Send frame to API via connection.""" await self.check_connected() self.connection.write(frame) async def disconnect(self) -> None: """Disconnect from KLF 200.""" await self.heartbeat.stop() if self.connection.connected: try: # If the connection will be closed while house status monitor is enabled, a reconnection will fail on SSL handshake. if self.klf200.house_status_monitor_enabled: await self.klf200.house_status_monitor_disable(pyvlx=self, timeout=1) # Reboot KLF200 when disconnecting to avoid unresponsive KLF200. await self.klf200.reboot() except (OSError, PyVLXException): pass self.connection.disconnect() if self.connection.tasks: await asyncio.gather(*self.connection.tasks) # Wait for all tasks to finish async def load_nodes(self, node_id: Optional[int] = None) -> None: """Load devices from KLF 200, if no node_id is specified all nodes are loaded.""" await self.nodes.load(node_id) async def load_scenes(self) -> None: """Load scenes from KLF 200.""" await self.scenes.load() async def get_limitation(self, node_id: int) -> None: """Return limitation.""" limit = get_limitation.GetLimitation(self, node_id) await limit.do_api_call()
class PyVLX: '''Class for PyVLX.''' def __init__( self, path: Optional[str] = None, host: Optional[str] = None, password: Optional[str] = None, loop: Optional[asyncio.AbstractEventLoop] = None, heartbeat_interval: int = 30, heartbeat_load_all_states: bool = True, ): '''Initialize PyVLX class.''' pass async def connect(self) -> None: '''Connect to KLF 200.''' pass async def reboot_gateway(self) -> None: '''For Compatibility: Reboot the KLF 200.''' pass def get_connected(self) -> bool: '''Return whether the gateway is currently connected.''' pass async def check_connected(self) -> None: '''Check we're connected, and if not, connect.''' pass async def send_frame(self, frame: FrameBase) -> None: '''Send frame to API via connection.''' pass async def disconnect(self) -> None: '''Disconnect from KLF 200.''' pass async def load_nodes(self, node_id: Optional[int] = None) -> None: '''Load devices from KLF 200, if no node_id is specified all nodes are loaded.''' pass async def load_scenes(self) -> None: '''Load scenes from KLF 200.''' pass async def get_limitation(self, node_id: int) -> None: '''Return limitation.''' pass
11
11
9
0
8
1
2
0.19
0
12
8
0
10
11
10
10
101
11
77
31
58
15
60
23
49
5
0
3
16
140,453
Julius2342/pyvlx
Julius2342_pyvlx/pyvlx/opening_device.py
pyvlx.opening_device.OpeningDevice
class OpeningDevice(Node): """Meta class for opening device with one main parameter for position.""" def __init__( self, pyvlx: "PyVLX", node_id: int, name: str, serial_number: Optional[str] = None, position_parameter: Parameter = Parameter(), ): """Initialize opening device. Parameters: * pyvlx: PyVLX object * node_id: internal id for addressing nodes. Provided by KLF 200 device * name: node name * serial_number: serial number of the node. * position_parameter: initial position of the opening device. """ super().__init__( pyvlx=pyvlx, node_id=node_id, name=name, serial_number=serial_number ) self.position: Position = Position(parameter=position_parameter) self.target: Position = Position(parameter=position_parameter) self.is_opening: bool = False self.is_closing: bool = False self.state_received_at: Optional[datetime.datetime] = None self.estimated_completion: Optional[datetime.datetime] = None self.use_default_velocity: bool = False self.default_velocity: Velocity = Velocity.DEFAULT self.open_position_target: int = 0 self.close_position_target: int = 100 self._update_task: Task | None = None async def _update_calls(self) -> None: """While cover are moving, perform periodically update calls.""" while self.is_moving(): await asyncio.sleep(1) await self.after_update() if self._update_task: self._update_task.cancel() self._update_task = None async def set_position( self, position: Position, velocity: Velocity | int | None = Velocity.DEFAULT, wait_for_completion: bool = True, ) -> None: """Set opening device to desired position. Parameters: * position: Position object containing the target position. * velocity: Velocity to be used during transition. * wait_for_completion: If set, function will return after device has reached target position. """ kwargs: Any = {} if ( velocity is None or velocity is Velocity.DEFAULT ) and self.use_default_velocity: velocity = self.default_velocity if isinstance(velocity, Velocity): if velocity is not Velocity.DEFAULT: if velocity is Velocity.SILENT: kwargs["fp1"] = Parameter(raw=b"\x00\x00") else: kwargs["fp1"] = Parameter(raw=b"\xC8\x00") elif isinstance(velocity, int): kwargs["fp1"] = Position.from_percent(velocity) command = CommandSend( pyvlx=self.pyvlx, wait_for_completion=wait_for_completion, node_id=self.node_id, parameter=position, functional_parameter=kwargs, ) await command.send() await self.after_update() async def open( self, velocity: Velocity | int | None = Velocity.DEFAULT, wait_for_completion: bool = True, ) -> None: """Open opening device. Parameters: * velocity: Velocity to be used during transition. * wait_for_completion: If set, function will return after device has reached target position. """ await self.set_position( position=Position(position_percent=self.open_position_target), velocity=velocity, wait_for_completion=wait_for_completion, ) async def close( self, velocity: Velocity | int | None = Velocity.DEFAULT, wait_for_completion: bool = True, ) -> None: """Close opening device. Parameters: * velocity: Velocity to be used during transition. * wait_for_completion: If set, function will return after device has reached target position. """ await self.set_position( position=Position(position_percent=self.close_position_target), velocity=velocity, wait_for_completion=wait_for_completion, ) async def stop(self, wait_for_completion: bool = True) -> None: """Stop opening device. Parameters: * wait_for_completion: If set, function will return after device has reached target position. """ await self.set_position( position=CurrentPosition(), wait_for_completion=wait_for_completion ) def is_moving(self) -> bool: """Return moving state of the cover.""" return self.is_opening or self.is_closing def movement_percent(self) -> int: """Return movement percentage of the cover.""" if ( self.estimated_completion is None or self.state_received_at is None or self.estimated_completion < datetime.datetime.now() ): return 100 movement_duration_s: float = ( self.estimated_completion - self.state_received_at ).total_seconds() time_passed_s: float = ( datetime.datetime.now() - self.state_received_at ).total_seconds() percent: int = int(time_passed_s / movement_duration_s * 100) percent = max(percent, 0) percent = min(percent, 100) return percent def get_position(self) -> Position: """Return position of the cover.""" if self.is_moving(): percent = self.movement_percent() movement_origin = self.position.position_percent movement_target = self.target.position_percent current_position = ( movement_origin + (movement_target - movement_origin) / 100 * percent ) if not self._update_task: self._update_task = self.pyvlx.loop.create_task(self._update_calls()) return Position(position_percent=int(current_position)) return self.position def __str__(self) -> str: """Return object as readable string.""" return '<{} name="{}" node_id="{}" serial_number="{}" position="{}"/>'.format( type(self).__name__, self.name, self.node_id, self.serial_number, self.position, )
class OpeningDevice(Node): '''Meta class for opening device with one main parameter for position.''' def __init__( self, pyvlx: "PyVLX", node_id: int, name: str, serial_number: Optional[str] = None, position_parameter: Parameter = Parameter(), ): '''Initialize opening device. Parameters: * pyvlx: PyVLX object * node_id: internal id for addressing nodes. Provided by KLF 200 device * name: node name * serial_number: serial number of the node. * position_parameter: initial position of the opening device. ''' pass async def _update_calls(self) -> None: '''While cover are moving, perform periodically update calls.''' pass async def set_position( self, position: Position, velocity: Velocity | int | None = Velocity.DEFAULT, wait_for_completion: bool = True, ) -> None: '''Set opening device to desired position. Parameters: * position: Position object containing the target position. * velocity: Velocity to be used during transition. * wait_for_completion: If set, function will return after device has reached target position. ''' pass async def open( self, velocity: Velocity | int | None = Velocity.DEFAULT, wait_for_completion: bool = True, ) -> None: '''Open opening device. Parameters: * velocity: Velocity to be used during transition. * wait_for_completion: If set, function will return after device has reached target position. ''' pass async def close( self, velocity: Velocity | int | None = Velocity.DEFAULT, wait_for_completion: bool = True, ) -> None: '''Close opening device. Parameters: * velocity: Velocity to be used during transition. * wait_for_completion: If set, function will return after device has reached target position. ''' pass async def stop(self, wait_for_completion: bool = True) -> None: '''Stop opening device. Parameters: * wait_for_completion: If set, function will return after device has reached target position. ''' pass def is_moving(self) -> bool: '''Return moving state of the cover.''' pass def movement_percent(self) -> int: '''Return movement percentage of the cover.''' pass def get_position(self) -> Position: '''Return position of the cover.''' pass def __str__(self) -> str: '''Return object as readable string.''' pass
11
11
17
2
12
4
2
0.32
1
14
5
8
10
13
10
18
185
25
121
53
90
39
63
31
52
6
1
3
20
140,454
Julius2342/pyvlx
Julius2342_pyvlx/pyvlx/api/status_request.py
pyvlx.api.status_request.StatusRequest
class StatusRequest(ApiEvent): """Class for retrieving node informationfrom API.""" def __init__(self, pyvlx: "PyVLX", node_id: int): """Initialize SceneList class.""" super().__init__(pyvlx=pyvlx) self.node_id = node_id self.success = False self.notification_frame: Optional[FrameStatusRequestNotification] = None self.session_id: Optional[int] = None async def handle_frame(self, frame: FrameBase) -> bool: """Handle incoming API frame, return True if this was the expected frame.""" if ( isinstance(frame, FrameStatusRequestConfirmation) and frame.session_id == self.session_id ): # We are still waiting for StatusRequestNotification return False if ( isinstance(frame, FrameStatusRequestNotification) and frame.session_id == self.session_id ): self.notification_frame = frame self.success = True return True return False def request_frame(self) -> FrameStatusRequestRequest: """Construct initiating frame.""" self.session_id = get_new_session_id() return FrameStatusRequestRequest( session_id=self.session_id, node_ids=[self.node_id] )
class StatusRequest(ApiEvent): '''Class for retrieving node informationfrom API.''' def __init__(self, pyvlx: "PyVLX", node_id: int): '''Initialize SceneList class.''' pass async def handle_frame(self, frame: FrameBase) -> bool: '''Handle incoming API frame, return True if this was the expected frame.''' pass def request_frame(self) -> FrameStatusRequestRequest: '''Construct initiating frame.''' pass
4
4
10
0
9
1
2
0.19
1
7
4
0
3
4
3
12
35
3
27
8
23
5
18
8
14
3
1
1
5
140,455
Julius2342/pyvlx
Julius2342_pyvlx/pyvlx/opening_device.py
pyvlx.opening_device.Gate
class Gate(OpeningDevice): """Gate object."""
class Gate(OpeningDevice): '''Gate object.''' pass
1
1
0
0
0
0
0
1
1
0
0
0
0
0
0
18
2
0
1
1
0
1
1
1
0
0
2
0
0
140,456
Julius2342/pyvlx
Julius2342_pyvlx/pyvlx/opening_device.py
pyvlx.opening_device.DualRollerShutter
class DualRollerShutter(OpeningDevice): """DualRollerShutter object.""" def __init__( self, pyvlx: "PyVLX", node_id: int, name: str, serial_number: Optional[str], position_parameter: Parameter = Parameter(), ): """Initialize Blind class. Parameters: * pyvlx: PyVLX object * node_id: internal id for addressing nodes. Provided by KLF 200 device * name: node name """ super().__init__( pyvlx=pyvlx, node_id=node_id, name=name, serial_number=serial_number, position_parameter=position_parameter, ) self.position_upper_curtain: Position = Position(position_percent=0) self.position_lower_curtain: Position = Position(position_percent=0) self.target_position: Any = Position() self.active_parameter: int = 0 async def set_position( self, position: Position, velocity: Velocity | int | None = Velocity.DEFAULT, wait_for_completion: bool = True, curtain: str = "dual", ) -> None: """Set DualRollerShutter to desired position. Parameters: * position: Position object containing the current position. * target_position: Position object holding the target position which allows to adjust the position while the blind is in movement * wait_for_completion: If set, function will return after device has reached target position. """ kwargs: Any = {} if curtain == "upper": self.target_position = DualRollerShutterPosition() self.active_parameter = 1 kwargs["fp1"] = position kwargs["fp2"] = TargetPosition() elif curtain == "lower": self.target_position = DualRollerShutterPosition() self.active_parameter = 2 kwargs["fp1"] = TargetPosition() kwargs["fp2"] = position else: self.target_position = position self.active_parameter = 0 if ( velocity is None or velocity is Velocity.DEFAULT ) and self.use_default_velocity: velocity = self.default_velocity if isinstance(velocity, Velocity): if velocity is not Velocity.DEFAULT: if velocity is Velocity.SILENT: kwargs["fp3"] = Parameter(raw=b"\x00\x00") else: kwargs["fp3"] = Parameter(raw=b"\xC8\x00") elif isinstance(velocity, int): kwargs["fp3"] = Position.from_percent(velocity) command = CommandSend( pyvlx=self.pyvlx, wait_for_completion=wait_for_completion, node_id=self.node_id, parameter=self.target_position, active_parameter=self.active_parameter, **kwargs ) await command.send() if position.position <= Position.MAX: if curtain == "upper": self.position_upper_curtain = position elif curtain == "lower": self.position_lower_curtain = position else: self.position = position await self.after_update() async def open( self, velocity: Velocity | int | None = Velocity.DEFAULT, wait_for_completion: bool = True, curtain: str = "dual", ) -> None: """Open DualRollerShutter. Parameters: * wait_for_completion: If set, function will return after device has reached target position. """ await self.set_position( position=Position(position_percent=self.open_position_target), velocity=velocity, wait_for_completion=wait_for_completion, curtain=curtain, ) async def close( self, velocity: Velocity | int | None = Velocity.DEFAULT, wait_for_completion: bool = True, curtain: str = "dual", ) -> None: """Close DualRollerShutter. Parameters: * wait_for_completion: If set, function will return after device has reached target position. """ await self.set_position( position=Position(position_percent=self.close_position_target), velocity=velocity, wait_for_completion=wait_for_completion, curtain=curtain, ) async def stop( self, wait_for_completion: bool = True, velocity: Velocity | int | None = Velocity.DEFAULT, curtain: str = "dual", ) -> None: """Stop Blind position.""" await self.set_position( position=CurrentPosition(), velocity=velocity, wait_for_completion=wait_for_completion, curtain=curtain, )
class DualRollerShutter(OpeningDevice): '''DualRollerShutter object.''' def __init__( self, pyvlx: "PyVLX", node_id: int, name: str, serial_number: Optional[str], position_parameter: Parameter = Parameter(), ): '''Initialize Blind class. Parameters: * pyvlx: PyVLX object * node_id: internal id for addressing nodes. Provided by KLF 200 device * name: node name ''' pass async def set_position( self, position: Position, velocity: Velocity | int | None = Velocity.DEFAULT, wait_for_completion: bool = True, curtain: str = "dual", ) -> None: '''Set DualRollerShutter to desired position. Parameters: * position: Position object containing the current position. * target_position: Position object holding the target position which allows to adjust the position while the blind is in movement * wait_for_completion: If set, function will return after device has reached target position. ''' pass async def open( self, velocity: Velocity | int | None = Velocity.DEFAULT, wait_for_completion: bool = True, curtain: str = "dual", ) -> None: '''Open DualRollerShutter. Parameters: * wait_for_completion: If set, function will return after device has reached target position. ''' pass async def close( self, velocity: Velocity | int | None = Velocity.DEFAULT, wait_for_completion: bool = True, curtain: str = "dual", ) -> None: '''Close DualRollerShutter. Parameters: * wait_for_completion: If set, function will return after device has reached target position. ''' pass async def stop( self, wait_for_completion: bool = True, velocity: Velocity | int | None = Velocity.DEFAULT, curtain: str = "dual", ) -> None: '''Stop Blind position.''' pass
6
6
28
2
21
5
3
0.25
1
12
7
0
5
9
5
23
148
15
106
45
72
27
42
13
36
11
2
3
15
140,457
Julius2342/pyvlx
Julius2342_pyvlx/pyvlx/dataobjects.py
pyvlx.dataobjects.DtoProtocolVersion
class DtoProtocolVersion: """KLF 200 Dataobject for Protocol version.""" def __init__(self, majorversion: Optional[int] = None, minorversion: Optional[int] = None): """Initialize DtoProtocolVersion class.""" self.majorversion = majorversion self.minorversion = minorversion def __str__(self) -> str: """Return human readable string.""" return ( '<{} majorversion="{}" minorversion="{}"/>'.format( type(self).__name__, self.majorversion, self.minorversion ) )
class DtoProtocolVersion: '''KLF 200 Dataobject for Protocol version.''' def __init__(self, majorversion: Optional[int] = None, minorversion: Optional[int] = None): '''Initialize DtoProtocolVersion class.''' pass def __str__(self) -> str: '''Return human readable string.''' pass
3
3
6
0
5
1
1
0.3
0
3
0
0
2
2
2
2
15
2
10
5
7
3
6
5
3
1
0
0
2
140,458
Julius2342/pyvlx
Julius2342_pyvlx/pyvlx/dataobjects.py
pyvlx.dataobjects.DtoNetworkSetup
class DtoNetworkSetup: """Dataobject to hold KLF200 Network Setup.""" def __init__(self, ipaddress: Optional[str] = None, gateway: Optional[str] = None, netmask: Optional[str] = None, dhcp: Optional[DHCPParameter] = None): """Initialize DtoNetworkSetup class.""" self.ipaddress = ipaddress self.gateway = gateway self.netmask = netmask self.dhcp = dhcp def __str__(self) -> str: """Return human readable string.""" return '<{} ipaddress="{}" gateway="{}" gateway="{}" dhcp="{}"/>'.format( type(self).__name__, self.ipaddress, self.gateway, self.gateway, self.dhcp )
class DtoNetworkSetup: '''Dataobject to hold KLF200 Network Setup.''' def __init__(self, ipaddress: Optional[str] = None, gateway: Optional[str] = None, netmask: Optional[str] = None, dhcp: Optional[DHCPParameter] = None): '''Initialize DtoNetworkSetup class.''' pass def __str__(self) -> str: '''Return human readable string.''' pass
3
3
8
0
7
1
1
0.2
0
3
1
0
2
4
2
2
20
2
15
11
8
3
8
7
5
1
0
0
2
140,459
Julius2342/pyvlx
Julius2342_pyvlx/pyvlx/dataobjects.py
pyvlx.dataobjects.DtoLocalTime
class DtoLocalTime: """Dataobject to hold KLF200 Time Data.""" def __init__(self, utctime: Optional[datetime] = None, localtime: Optional[datetime] = None): """Initialize DtoLocalTime class.""" if utctime is None: utctime = datetime.fromtimestamp(0) if localtime is None: localtime = datetime.fromtimestamp(0) self.utctime = utctime self.localtime = localtime def __str__(self) -> str: """Return human readable string.""" return ( '<{} utctime="{}" localtime="{}"/>'.format( type(self).__name__, self.utctime, self.localtime) ) def from_payload(self, payload: bytes) -> None: """Build the Dto From Data.""" self.utctime = datetime.fromtimestamp(int.from_bytes(payload[0:4], "big")) weekday = payload[11] - 1 if weekday == -1: weekday = 6 self.localtime = datetime.fromtimestamp(time.mktime( (int.from_bytes(payload[9:11], byteorder='big') + 1900, # Year payload[8], # month payload[7], # day payload[6], # hour payload[5], # minute payload[4], # second weekday, int.from_bytes(payload[12:14], byteorder='big'), # day of year int.from_bytes(payload[14:15], byteorder='big', signed=True)))) def to_payload(self) -> bytes: """Build the Dto From Data.""" payload = b'' payload = int(self.utctime.timestamp()).to_bytes(4, byteorder='big') payload += self.localtime.second.to_bytes(1, "big") payload += self.localtime.minute.to_bytes(1, "big") payload += self.localtime.hour.to_bytes(1, "big") payload += self.localtime.day.to_bytes(1, "big") payload += self.localtime.month.to_bytes(1, "big") payload += (self.localtime.year - 1900).to_bytes(2, "big") if self.localtime.weekday == 6: payload += (0).to_bytes(1, "big") else: payload += (self.localtime.weekday() + 1).to_bytes(1, "big") payload += self.localtime.timetuple().tm_yday.to_bytes(2, "big") payload += (self.localtime.timetuple().tm_isdst).to_bytes(1, "big", signed=True) return payload
class DtoLocalTime: '''Dataobject to hold KLF200 Time Data.''' def __init__(self, utctime: Optional[datetime] = None, localtime: Optional[datetime] = None): '''Initialize DtoLocalTime class.''' pass def __str__(self) -> str: '''Return human readable string.''' pass def from_payload(self, payload: bytes) -> None: '''Build the Dto From Data.''' pass def to_payload(self) -> bytes: '''Build the Dto From Data.''' pass
5
5
12
0
11
3
2
0.27
0
5
0
0
4
2
4
4
54
5
44
9
39
12
31
9
26
3
0
1
8
140,460
Julius2342/pyvlx
Julius2342_pyvlx/pyvlx/dataobjects.py
pyvlx.dataobjects.DtoLeaveLearnState
class DtoLeaveLearnState: """Dataobject to hold KLF200 Data.""" def __init__(self, status: Optional[LeaveLearnStateConfirmationStatus] = None): """Initialize DtoLeaveLearnState class.""" self.status = status def __str__(self) -> str: """Return human readable string.""" return ( '<{} status="{}"/>'.format( type(self).__name__, self.status ) )
class DtoLeaveLearnState: '''Dataobject to hold KLF200 Data.''' def __init__(self, status: Optional[LeaveLearnStateConfirmationStatus] = None): '''Initialize DtoLeaveLearnState class.''' pass def __str__(self) -> str: '''Return human readable string.''' pass
3
3
5
0
4
1
1
0.33
0
3
1
0
2
1
2
2
14
2
9
4
6
3
5
4
2
1
0
0
2
140,461
Julius2342/pyvlx
Julius2342_pyvlx/pyvlx/const.py
pyvlx.const.StatusType
class StatusType(Enum): """Enum class for Status Type for GW_STATUS_REQUEST_NTF frame.""" REQUEST_TARGET_POSITION = 0 # Request Target Position REQUEST_CURRENT_POSITION = 1 # Request Current Position REQUEST_REMAINING_TIME = 2 # Request Remaining Time REQUEST_MAIN_INFO = 3 # Request Main Info REQUEST_UNKNOWN = 255 # Request Unknown @classmethod def _missing_(cls, value: object) -> Any: return cls.REQUEST_UNKNOWN
class StatusType(Enum): '''Enum class for Status Type for GW_STATUS_REQUEST_NTF frame.''' @classmethod def _missing_(cls, value: object) -> Any: pass
3
1
2
0
2
0
1
0.67
1
2
0
0
0
0
1
50
12
2
9
8
6
6
8
7
6
1
4
0
1
140,462
Julius2342/pyvlx
Julius2342_pyvlx/pyvlx/const.py
pyvlx.const.StatusReply
class StatusReply(Enum): """Enum Class for Node Status Reply.""" # pylint: disable=line-too-long UNKNOWN_STATUS_REPLY = 0x00 # Used to indicate unknown reply. COMMAND_COMPLETED_OK = 0x01 # Indicates no errors detected. NO_CONTACT = 0x02 # Indicates no communication to node. MANUALLY_OPERATED = 0x03 # Indicates manually operated by a user. BLOCKED = 0x04 # Indicates node has been blocked by an object. WRONG_SYSTEMKEY = 0x05 # Indicates the node contains a wrong system key. PRIORITY_LEVEL_LOCKED = 0x06 # Indicates the node is locked on this priority level. REACHED_WRONG_POSITION = 0x07 # Indicates node has stopped in another position than expected. ERROR_DURING_EXECUTION = 0x08 # Indicates an error has occurred during execution of command. NO_EXECUTION = 0x09 # Indicates no movement of the node parameter. CALIBRATING = 0x0A # Indicates the node is calibrating the parameters. POWER_CONSUMPTION_TOO_HIGH = 0x0B # Indicates the node power consumption is too high. POWER_CONSUMPTION_TOO_LOW = 0x0C # Indicates the node power consumption is too low. LOCK_POSITION_OPEN = 0x0D # Indicates door lock errors. (Door open during lock command) MOTION_TIME_TOO_LONG__COMMUNICATION_ENDED = 0x0E # Indicates the target was not reached in time. THERMAL_PROTECTION = 0x0F # Indicates the node has gone into thermal protection mode. PRODUCT_NOT_OPERATIONAL = 0x10 # Indicates the node is not currently operational. FILTER_MAINTENANCE_NEEDED = 0x11 # Indicates the filter needs maintenance. BATTERY_LEVEL = 0x12 # Indicates the battery level is low. TARGET_MODIFIED = 0x13 # Indicates the node has modified the target value of the command. MODE_NOT_IMPLEMENTED = 0x14 # Indicates this node does not support the mode received. COMMAND_INCOMPATIBLE_TO_MOVEMENT = 0x15 # Indicates the node is unable to move in the right direction. USER_ACTION = 0x16 # Indicates dead bolt is manually locked during unlock command. DEAD_BOLT_ERROR = 0x17 # Indicates dead bolt error. AUTOMATIC_CYCLE_ENGAGED = 0x18 # Indicates the node has gone into automatic cycle mode. WRONG_LOAD_CONNECTED = 0x19 # Indicates wrong load on node. COLOUR_NOT_REACHABLE = 0x1A # Indicates that node is unable to reach received colour code. TARGET_NOT_REACHABLE = 0x1B # Indicates the node is unable to reach received target position. BAD_INDEX_RECEIVED = 0x1C # Indicates io-protocol has received an invalid index. COMMAND_OVERRULED = 0x1D # Indicates that the command was overruled by a new command. NODE_WAITING_FOR_POWER = 0x1E # Indicates that the node reported waiting for power. INFORMATION_CODE = 0xDF # Indicates an unknown error code received. (Hex code is shown on display) PARAMETER_LIMITED = 0xE0 # Indicates the parameter was limited by an unknown device. (Same as LIMITATION_BY_UNKNOWN_DEVICE) LIMITATION_BY_LOCAL_USER = 0xE1 # Indicates the parameter was limited by local button. LIMITATION_BY_USER = 0xE2 # Indicates the parameter was limited by a remote control. LIMITATION_BY_RAIN = 0xE3 # Indicates the parameter was limited by a rain sensor. LIMITATION_BY_TIMER = 0xE4 # Indicates the parameter was limited by a timer. LIMITATION_BY_UPS = 0xE6 # Indicates the parameter was limited by a power supply. LIMITATION_BY_UNKNOWN_DEVICE = 0xE7 # Indicates the parameter was limited by an unknown device. (Same as PARAMETER_LIMITED) LIMITATION_BY_SAAC = 0xEA # Indicates the parameter was limited by a standalone automatic controller. LIMITATION_BY_WIND = 0xEB # Indicates the parameter was limited by a wind sensor. LIMITATION_BY_MYSELF = 0xEC # Indicates the parameter was limited by the node itself. LIMITATION_BY_AUTOMATIC_CYCLE = 0xED # Indicates the parameter was limited by an automatic cycle. LIMITATION_BY_EMERGENCY = 0xEE # Indicates the parameter was limited by an emergency. @classmethod def _missing_(cls, value: object) -> Any: return cls.UNKNOWN_STATUS_REPLY
class StatusReply(Enum): '''Enum Class for Node Status Reply.''' @classmethod def _missing_(cls, value: object) -> Any: pass
3
1
2
0
2
0
1
0.96
1
2
0
0
0
0
1
50
53
3
48
47
45
46
47
46
45
1
4
0
1
140,463
Julius2342/pyvlx
Julius2342_pyvlx/pyvlx/const.py
pyvlx.const.StatusId
class StatusId(Enum): """Enum Class for Status ID Reply.""" # pylint: disable=line-too-long STATUS_USER = 0x01 # The status is from a user activation. STATUS_RAIN = 0x02 # The status is from a rain sensor activation. STATUS_TIMER = 0x03 # The status is from a timer generated action. STATUS_UPS = 0x05 # The status is from a UPS generated action. STATUS_PROGRAM = 0x08 # The status is from an automatic program generated action. (SAAC) STATUS_WIND = 0x09 # The status is from a Wind sensor generated action. STATUS_MYSELF = 0x0A # The status is from an actuator generated action. STATUS_AUTOMATIC_CYCLE = 0x0B # The status is from a automatic cycle generated action. STATUS_EMERGENCY = 0x0C # The status is from an emergency or a security generated action. STATUS_UNKNOWN = 0xFF # The status is from from an unknown command originator action. @classmethod def _missing_(cls, value: object) -> Any: return cls.STATUS_UNKNOWN
class StatusId(Enum): '''Enum Class for Status ID Reply.''' @classmethod def _missing_(cls, value: object) -> Any: pass
3
1
2
0
2
0
1
0.86
1
2
0
0
0
0
1
50
19
3
14
13
11
12
13
12
11
1
4
0
1
140,464
Julius2342/pyvlx
Julius2342_pyvlx/pyvlx/dataobjects.py
pyvlx.dataobjects.DtoState
class DtoState: """Data Object for Gateway State.""" def __init__(self, gateway_state: Optional[GatewayState] = None, gateway_sub_state: Optional[GatewaySubState] = None): """Initialize DtoState class.""" self.gateway_state = gateway_state self.gateway_sub_state = gateway_sub_state def __str__(self) -> str: """Return human readable string.""" return ( '<{} gateway_state="{}" gateway_sub_state="{}"/>'.format( type(self).__name__, self.gateway_state, self.gateway_sub_state ) )
class DtoState: '''Data Object for Gateway State.''' def __init__(self, gateway_state: Optional[GatewayState] = None, gateway_sub_state: Optional[GatewaySubState] = None): '''Initialize DtoState class.''' pass def __str__(self) -> str: '''Return human readable string.''' pass
3
3
6
0
5
1
1
0.3
0
4
2
0
2
2
2
2
15
2
10
5
7
3
6
5
3
1
0
0
2
140,465
Julius2342/pyvlx
Julius2342_pyvlx/pyvlx/const.py
pyvlx.const.RunStatus
class RunStatus(Enum): """Enum Class for Node RunStatus.""" EXECUTION_COMPLETED = 0 # Execution is completed with no errors. EXECUTION_FAILED = 1 # Execution has failed. (Get specifics in the following error code) EXECUTION_ACTIVE = 2
class RunStatus(Enum): '''Enum Class for Node RunStatus.''' pass
1
1
0
0
0
0
0
1
1
0
0
0
0
0
0
49
6
1
4
4
3
4
4
4
3
0
4
0
0
140,466
Julius2342/pyvlx
Julius2342_pyvlx/pyvlx/const.py
pyvlx.const.NodeParameter
class NodeParameter(Enum): """Enum Class for Node Parameter.""" MP = 0x00 # Main Parameter. FP1 = 0x01 # Functional Parameter number 1. FP2 = 0x02 # Functional Parameter number 2. FP3 = 0x03 # Functional Parameter number 3. FP4 = 0x04 # Functional Parameter number 4. FP5 = 0x05 # Functional Parameter number 5. FP6 = 0x06 # Functional Parameter number 6. FP7 = 0x07 # Functional Parameter number 7. FP8 = 0x08 # Functional Parameter number 8. FP9 = 0x09 # Functional Parameter number 9. FP10 = 0x0A # Functional Parameter number 10. FP11 = 0x0B # Functional Parameter number 11. FP12 = 0x0C # Functional Parameter number 12. FP13 = 0x0D # Functional Parameter number 13. FP14 = 0x0E # Functional Parameter number 14. FP15 = 0x0F # Functional Parameter number 15. FP16 = 0x10 # Functional Parameter number 16. NOT_USED = 0xFF
class NodeParameter(Enum): '''Enum Class for Node Parameter.''' pass
1
1
0
0
0
0
0
1
1
0
0
0
0
0
0
49
21
1
19
19
18
19
19
19
18
0
4
0
0
140,467
Julius2342/pyvlx
Julius2342_pyvlx/pyvlx/const.py
pyvlx.const.LockPriorityLevel
class LockPriorityLevel(Enum): """Enum Class for Lock Priority Level.""" NO = 0 # Do not lock any priority level. MIN30 = 1 # Lock one or more priority level in 30 minutes. FOREVER = 2
class LockPriorityLevel(Enum): '''Enum Class for Lock Priority Level.''' pass
1
1
0
0
0
0
0
1
1
0
0
0
0
0
0
49
6
1
4
4
3
4
4
4
3
0
4
0
0
140,468
Julius2342/pyvlx
Julius2342_pyvlx/pyvlx/connection.py
pyvlx.connection.TCPTransport
class TCPTransport(asyncio.Protocol): """Class for handling asyncio connection transport.""" def __init__( self, frame_received_cb: Callable[[FrameBase], None], connection_lost_cb: Callable[[], None], ): """Init TCPTransport.""" self.frame_received_cb = frame_received_cb self.connection_lost_cb = connection_lost_cb self.tokenizer = SlipTokenizer() def connection_made(self, transport: object) -> None: """Handle sucessful connection.""" PYVLXLOG.debug("Socket connection to KLF 200 opened") def data_received(self, data: bytes) -> None: """Handle data received.""" self.tokenizer.feed(data) while self.tokenizer.has_tokens(): raw = self.tokenizer.get_next_token() assert raw is not None try: frame = frame_from_raw(raw) if frame is not None: self.frame_received_cb(frame) except PyVLXException: PYVLXLOG.error("Error in data_received", exc_info=sys.exc_info()) def connection_lost(self, exc: object) -> None: """Handle lost connection.""" PYVLXLOG.debug("Socket connection to KLF 200 has been lost") self.connection_lost_cb()
class TCPTransport(asyncio.Protocol): '''Class for handling asyncio connection transport.''' def __init__( self, frame_received_cb: Callable[[FrameBase], None], connection_lost_cb: Callable[[], None], ): '''Init TCPTransport.''' pass def connection_made(self, transport: object) -> None: '''Handle sucessful connection.''' pass def data_received(self, data: bytes) -> None: '''Handle data received.''' pass def connection_lost(self, exc: object) -> None: '''Handle lost connection.''' pass
5
5
7
0
6
1
2
0.2
1
5
3
0
4
3
4
4
35
5
25
14
16
5
21
10
16
4
1
3
7
140,469
Julius2342/pyvlx
Julius2342_pyvlx/pyvlx/connection.py
pyvlx.connection.SlipTokenizer
class SlipTokenizer: """Helper class for splitting up binary stream to slip packets.""" def __init__(self) -> None: """Init Tokenizer.""" self.data = bytes() def feed(self, chunk: bytes) -> None: """Feed chunk to tokenizer.""" if not chunk: return self.data += chunk def has_tokens(self) -> bool: """Return True if Tokenizer has tokens.""" return is_slip(self.data) def get_next_token(self) -> Optional[bytes]: """Get next token from Tokenizer.""" slip, self.data = get_next_slip(self.data) return slip
class SlipTokenizer: '''Helper class for splitting up binary stream to slip packets.''' def __init__(self) -> None: '''Init Tokenizer.''' pass def feed(self, chunk: bytes) -> None: '''Feed chunk to tokenizer.''' pass def has_tokens(self) -> bool: '''Return True if Tokenizer has tokens.''' pass def get_next_token(self) -> Optional[bytes]: '''Get next token from Tokenizer.''' pass
5
5
4
0
3
1
1
0.42
0
2
0
0
4
1
4
4
21
4
12
7
7
5
12
7
7
2
0
1
5
140,470
Julius2342/pyvlx
Julius2342_pyvlx/pyvlx/connection.py
pyvlx.connection.Connection
class Connection: """Class for handling TCP connection.""" def __init__(self, loop: asyncio.AbstractEventLoop, config: Config): """Init TCP connection.""" self.loop = loop self.config = config self.transport: Optional[asyncio.Transport] = None self.frame_received_cbs: List[CallbackType] = [] self.connection_closed_cbs: List[Callable[[], Coroutine]] = [] self.connection_opened_cbs: List[Callable[[], Coroutine]] = [] self.connected = False self.connection_counter = 0 self.tasks: Set[asyncio.Task] = set() def __del__(self) -> None: """Destruct connection.""" self.disconnect() def disconnect(self) -> None: """Disconnect connection.""" if self.transport is not None: self.transport.close() self.transport = None self.connected = False PYVLXLOG.debug("TCP transport closed.") for connection_closed_cb in self.connection_closed_cbs: if asyncio.iscoroutine(connection_closed_cb()): task = self.loop.create_task(connection_closed_cb()) self.tasks.add(task) task.add_done_callback(self.tasks.remove) async def connect(self) -> None: """Connect to gateway via SSL.""" tcp_client = TCPTransport(self.frame_received_cb, connection_lost_cb=self.on_connection_lost) assert self.config.host is not None self.transport, _ = await self.loop.create_connection( lambda: tcp_client, host=self.config.host, port=self.config.port, ssl=self.create_ssl_context(), ) self.connected = True self.connection_counter += 1 PYVLXLOG.debug( "Amount of connections since last HA start: %s", self.connection_counter ) for connection_opened_cb in self.connection_opened_cbs: if asyncio.iscoroutine(connection_opened_cb()): task = self.loop.create_task(connection_opened_cb()) self.tasks.add(task) task.add_done_callback(self.tasks.remove) def register_frame_received_cb(self, callback: CallbackType) -> None: """Register frame received callback.""" self.frame_received_cbs.append(callback) def unregister_frame_received_cb(self, callback: CallbackType) -> None: """Unregister frame received callback.""" self.frame_received_cbs.remove(callback) def register_connection_closed_cb(self, callback: Callable[[], Coroutine]) -> None: """Register connection closed callback.""" self.connection_closed_cbs.append(callback) def unregister_connection_closed_cb(self, callback: Callable[[], Coroutine]) -> None: """Unregister connection closed callback.""" self.connection_closed_cbs.remove(callback) def register_connection_opened_cb(self, callback: Callable[[], Coroutine]) -> None: """Register connection opened callback.""" self.connection_opened_cbs.append(callback) def unregister_connection_opened_cb(self, callback: Callable[[], Coroutine]) -> None: """Unregister connection opened callback.""" self.connection_opened_cbs.remove(callback) def write(self, frame: FrameBase) -> None: """Write frame to Bus.""" if not isinstance(frame, FrameBase): raise PyVLXException("Frame not of type FrameBase", *type(frame)) PYVLXLOG.debug("SEND: %s", frame) assert self.transport is not None self.transport.write(slip_pack(bytes(frame))) @staticmethod def create_ssl_context() -> ssl.SSLContext: """Create and return SSL Context.""" ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) ssl_context.check_hostname = False ssl_context.verify_mode = ssl.CERT_NONE return ssl_context def frame_received_cb(self, frame: FrameBase) -> None: """Received message.""" PYVLXLOG.debug("REC: %s", frame) for frame_received_cb in self.frame_received_cbs: # pylint: disable=not-callable task = self.loop.create_task(frame_received_cb(frame)) self.tasks.add(task) task.add_done_callback(self.tasks.remove) def on_connection_lost(self) -> None: """Server closed connection.""" self.disconnect()
class Connection: '''Class for handling TCP connection.''' def __init__(self, loop: asyncio.AbstractEventLoop, config: Config): '''Init TCP connection.''' pass def __del__(self) -> None: '''Destruct connection.''' pass def disconnect(self) -> None: '''Disconnect connection.''' pass async def connect(self) -> None: '''Connect to gateway via SSL.''' pass def register_frame_received_cb(self, callback: CallbackType) -> None: '''Register frame received callback.''' pass def unregister_frame_received_cb(self, callback: CallbackType) -> None: '''Unregister frame received callback.''' pass def register_connection_closed_cb(self, callback: Callable[[], Coroutine]) -> None: '''Register connection closed callback.''' pass def unregister_connection_closed_cb(self, callback: Callable[[], Coroutine]) -> None: '''Unregister connection closed callback.''' pass def register_connection_opened_cb(self, callback: Callable[[], Coroutine]) -> None: '''Register connection opened callback.''' pass def unregister_connection_opened_cb(self, callback: Callable[[], Coroutine]) -> None: '''Unregister connection opened callback.''' pass def write(self, frame: FrameBase) -> None: '''Write frame to Bus.''' pass @staticmethod def create_ssl_context() -> ssl.SSLContext: '''Create and return SSL Context.''' pass def frame_received_cb(self, frame: FrameBase) -> None: '''Received message.''' pass def on_connection_lost(self) -> None: '''Server closed connection.''' pass
16
15
6
0
5
1
2
0.21
0
8
4
0
13
9
14
14
105
14
75
34
59
16
67
33
52
4
0
2
21
140,471
Julius2342/pyvlx
Julius2342_pyvlx/pyvlx/config.py
pyvlx.config.Config
class Config: """Object for configuration.""" DEFAULT_PORT = 51200 def __init__(self, pyvlx: "PyVLX", path: Optional[str] = None, host: Optional[str] = None, password: Optional[str] = None, port: Optional[int] = None): """Initialize Config class.""" self.pyvlx = pyvlx self.host = host self.password = password self.port = port or self.DEFAULT_PORT if path is not None: self.read_config(path) def read_config(self, path: str) -> None: """Read configuration file.""" PYVLXLOG.info("Reading config file: %s", path) try: with open(path, "r", encoding="utf-8") as filehandle: doc = yaml.safe_load(filehandle) self.test_configuration(doc, path) self.host = cast(str, doc["config"]["host"]) self.password = cast(str, doc["config"]["password"]) if "port" in doc["config"]: self.port = doc["config"]["port"] except FileNotFoundError as not_found: raise PyVLXException("file does not exist: {0}".format(not_found)) from not_found @staticmethod def test_configuration(doc: Any, path: str) -> None: """Test if configuration file is sane.""" if "config" not in doc: raise PyVLXException("no element config found in: {0}".format(path)) if "host" not in doc["config"]: raise PyVLXException("no element host found in: {0}".format(path)) if "password" not in doc["config"]: raise PyVLXException("no element password found in: {0}".format(path))
class Config: '''Object for configuration.''' def __init__(self, pyvlx: "PyVLX", path: Optional[str] = None, host: Optional[str] = None, password: Optional[str] = None, port: Optional[int] = None): '''Initialize Config class.''' pass def read_config(self, path: str) -> None: '''Read configuration file.''' pass @staticmethod def test_configuration(doc: Any, path: str) -> None: '''Test if configuration file is sane.''' pass
5
4
11
0
10
1
3
0.12
0
5
1
0
2
4
3
3
42
4
34
18
24
4
28
10
24
4
0
3
9
140,472
Julius2342/pyvlx
Julius2342_pyvlx/old_api/pyvlx/config.py
pyvlx.config.Config
class Config: """Object for configuration.""" def __init__(self, pyvlx, path=None, host=None, password=None): """Initialize Config class.""" self.pyvlx = pyvlx if path is not None: self.read_config(path) if host is not None: self.host = host if password is not None: self.password = password def read_config(self, path): """Read configuration file.""" self.pyvlx.logger.info('Reading config file: ', path) try: with open(path, 'r') as filehandle: doc = yaml.load(filehandle) if 'config' not in doc: raise PyVLXException('no element config found in: {0}'.format(path)) if 'host' not in doc['config']: raise PyVLXException('no element host found in: {0}'.format(path)) if 'password' not in doc['config']: raise PyVLXException('no element password found in: {0}'.format(path)) self.host = doc['config']['host'] self.password = doc['config']['password'] except FileNotFoundError as ex: raise PyVLXException('file does not exist: {0}'.format(ex))
class Config: '''Object for configuration.''' def __init__(self, pyvlx, path=None, host=None, password=None): '''Initialize Config class.''' pass def read_config(self, path): '''Read configuration file.''' pass
3
3
13
0
12
1
5
0.13
0
2
1
0
2
3
2
2
29
2
24
9
21
3
24
7
21
5
0
3
9
140,473
Julius2342/pyvlx
Julius2342_pyvlx/pyvlx/const.py
pyvlx.const.OperatingState
class OperatingState(Enum): """Enum Class for operating state of the node.""" NON_EXECUTING = 0 ERROR_EXECUTING = 1 NOT_USED = 2 WAIT_FOR_POWER = 3 EXECUTING = 4 DONE = 5 UNKNOWN = 255 @classmethod def _missing_(cls, value: object) -> Any: return cls.UNKNOWN
class OperatingState(Enum): '''Enum Class for operating state of the node.''' @classmethod def _missing_(cls, value: object) -> Any: pass
3
1
2
0
2
0
1
0.09
1
2
0
0
0
0
1
50
14
2
11
10
8
1
10
9
8
1
4
0
1
140,474
Julius2342/pyvlx
Julius2342_pyvlx/pyvlx/dataobjects.py
pyvlx.dataobjects.DtoVersion
class DtoVersion: """Object for KLF200 Version Information.""" def __init__(self, softwareversion: Optional[str] = None, hardwareversion: Optional[int] = None, productgroup: Optional[int] = None, producttype: Optional[int] = None): """Initialize DtoVersion class.""" self.softwareversion = softwareversion self.hardwareversion = hardwareversion self.productgroup = productgroup self.producttype = producttype def __str__(self) -> str: """Return human readable string.""" return ( '<{} softwareversion="{}" hardwareversion="{}" ' 'productgroup="{}" producttype="{}"/>'.format( type(self).__name__, self.softwareversion, self.hardwareversion, self.productgroup, self.producttype ) )
class DtoVersion: '''Object for KLF200 Version Information.''' def __init__(self, softwareversion: Optional[str] = None, hardwareversion: Optional[int] = None, productgroup: Optional[int] = None, producttype: Optional[int] = None): '''Initialize DtoVersion class.''' pass def __str__(self) -> str: '''Return human readable string.''' pass
3
3
10
0
9
1
1
0.17
0
3
0
0
2
4
2
2
23
2
18
11
11
3
8
7
5
1
0
0
2
140,475
Julius2342/pyvlx
Julius2342_pyvlx/old_api/pyvlx/device.py
pyvlx.device.Device
class Device: """Class for device abstraction.""" def __init__(self, pyvlx, ident, name): """Initialize Switch class.""" self.pyvlx = pyvlx self.ident = ident self.name = name def get_name(self): """Return name of object.""" return self.name
class Device: '''Class for device abstraction.''' def __init__(self, pyvlx, ident, name): '''Initialize Switch class.''' pass def get_name(self): '''Return name of object.''' pass
3
3
4
0
3
1
1
0.43
0
0
0
3
2
3
2
2
12
2
7
6
4
3
7
6
4
1
0
0
2
140,476
Julius2342/pyvlx
Julius2342_pyvlx/old_api/pyvlx/devices.py
pyvlx.devices.Devices
class Devices: """Object for storing devices.""" def __init__(self, pyvlx): """Initialize Devices class.""" self.pyvlx = pyvlx self.__devices = [] def __iter__(self): """Iterator.""" yield from self.__devices def __getitem__(self, key): """Return device by name or by index.""" for device in self.__devices: if device.name == key: return device if isinstance(key, int): return self.__devices[key] raise KeyError def __len__(self): """Return number of devices.""" return len(self.__devices) def add(self, device): """Add device.""" if not isinstance(device, Device): raise TypeError() self.__devices.append(device) async def load(self): """Load devices from KLF 200.""" json_response = await self.pyvlx.interface.api_call('products', 'get') self.data_import(json_response) def data_import(self, json_response): """Import data from json response.""" if 'data' not in json_response: raise PyVLXException('no element data found: {0}'.format( json.dumps(json_response))) data = json_response['data'] for item in data: if 'category' not in item: raise PyVLXException('no element category: {0}'.format( json.dumps(item))) category = item['category'] if category == 'Window opener': self.load_window_opener(item) elif category in ['Roller shutter', 'Dual Shutter']: self.load_roller_shutter(item) elif category in ['Blind']: self.load_blind(item) else: self.pyvlx.logger.warning( 'WARNING: Could not parse product: %s', category) def load_window_opener(self, item): """Load window opener from JSON.""" window = Window.from_config(self.pyvlx, item) self.add(window) def load_roller_shutter(self, item): """Load roller shutter from JSON.""" rollershutter = RollerShutter.from_config(self.pyvlx, item) self.add(rollershutter) def load_blind(self, item): """Load blind from JSON.""" blind = Blind.from_config(self.pyvlx, item) self.add(blind)
class Devices: '''Object for storing devices.''' def __init__(self, pyvlx): '''Initialize Devices class.''' pass def __iter__(self): '''Iterator.''' pass def __getitem__(self, key): '''Return device by name or by index.''' pass def __len__(self): '''Return number of devices.''' pass def add(self, device): '''Add device.''' pass async def load(self): '''Load devices from KLF 200.''' pass def data_import(self, json_response): '''Import data from json response.''' pass def load_window_opener(self, item): '''Load window opener from JSON.''' pass def load_roller_shutter(self, item): '''Load roller shutter from JSON.''' pass def load_blind(self, item): '''Load blind from JSON.''' pass
11
11
6
0
5
1
2
0.22
0
8
5
0
10
2
10
10
72
11
50
21
39
11
44
21
33
7
0
2
20
140,477
Julius2342/pyvlx
Julius2342_pyvlx/pyvlx/opening_device.py
pyvlx.opening_device.Blind
class Blind(OpeningDevice): """Blind objects.""" def __init__( self, pyvlx: "PyVLX", node_id: int, name: str, serial_number: Optional[str], position_parameter: Parameter = Parameter(), ): """Initialize Blind class. Parameters: * pyvlx: PyVLX object * node_id: internal id for addressing nodes. Provided by KLF 200 device * name: node name """ super().__init__( pyvlx=pyvlx, node_id=node_id, name=name, serial_number=serial_number, position_parameter=position_parameter, ) self.orientation: Position = Position(position_percent=0) self.target_orientation: Position = TargetPosition() self.target_position: Position = TargetPosition() self.open_orientation_target: int = 50 self.close_orientation_target: int = 100 async def set_position_and_orientation( self, position: Position, wait_for_completion: bool = True, velocity: Velocity | int | None = None, orientation: Optional[Position] = None, ) -> None: """Set window to desired position. Parameters: * position: Position object containing the current position. * velocity: Velocity to be used during transition. * target_position: Position object holding the target position which allows to adjust the position while the blind is in movement without stopping the blind (if orientation position has been changed.) * wait_for_completion: If set, function will return after device has reached target position. * orientation: If set, the orientation of the device will be set in the same request. Note, that, if the position is set to 0, the orientation will be set to 0 too. """ self.target_position = position self.position = position kwargs: Any = {} if orientation is not None: kwargs["fp3"] = orientation elif self.target_position == Position(position_percent=0): kwargs["fp3"] = Position(position_percent=0) else: kwargs["fp3"] = IgnorePosition() if ( velocity is None or velocity is Velocity.DEFAULT ) and self.use_default_velocity: velocity = self.default_velocity if isinstance(velocity, Velocity): if velocity is not Velocity.DEFAULT: if velocity is Velocity.SILENT: # The above code is declaring a variable called `kwargs`. kwargs["fp1"] = Parameter(raw=b"\x00\x00") else: kwargs["fp1"] = Parameter(raw=b"\xC8\x00") elif isinstance(velocity, int): kwargs["fp1"] = Position.from_percent(velocity) command = CommandSend( pyvlx=self.pyvlx, node_id=self.node_id, parameter=position, wait_for_completion=wait_for_completion, **kwargs ) await command.send() await self.after_update() async def set_position( self, position: Position, velocity: Velocity | int | None = Velocity.DEFAULT, wait_for_completion: bool = True, ) -> None: """Set window to desired position. Parameters: * position: Position object containing the current position. * velocity: Velocity to be used during transition. * target_position: Position object holding the target position which allows to adjust the position while the blind is in movement without stopping the blind (if orientation position has been changed.) * wait_for_completion: If set, function will return after device has reached target position. """ await self.set_position_and_orientation( position=position, wait_for_completion=wait_for_completion, velocity=velocity, ) async def open( self, velocity: Velocity | int | None = Velocity.DEFAULT, wait_for_completion: bool = True, ) -> None: """Open window. Parameters: * velocity: Velocity to be used during transition. * wait_for_completion: If set, function will return after device has reached target position. """ await self.set_position( position=Position(position_percent=self.open_position_target), velocity=velocity, wait_for_completion=wait_for_completion, ) async def close( self, velocity: Velocity | int | None = Velocity.DEFAULT, wait_for_completion: bool = True, ) -> None: """Close window. Parameters: * velocity: Velocity to be used during transition. * wait_for_completion: If set, function will return after device has reached target position. """ await self.set_position( position=Position(position_percent=self.close_position_target), velocity=velocity, wait_for_completion=wait_for_completion, ) async def stop(self, wait_for_completion: bool = True) -> None: """Stop Blind position.""" await self.set_position_and_orientation( position=CurrentPosition(), wait_for_completion=wait_for_completion, orientation=self.target_orientation, ) async def set_orientation( self, orientation: Position, wait_for_completion: bool = True ) -> None: """Set Blind shades to desired orientation. Parameters: * orientation: Position object containing the target orientation. + target_orientation: Position object holding the target orientation which allows to adjust the orientation while the blind is in movement without stopping the blind (if the position has been changed.) * wait_for_completion: If set, function will return after device has reached target position. """ self.target_orientation = orientation self.orientation = orientation fp3 = ( Position(position_percent=0) if self.target_position == Position(position_percent=0) else self.target_orientation ) print("Orientation in device: %s " % (orientation)) command = CommandSend( pyvlx=self.pyvlx, wait_for_completion=wait_for_completion, node_id=self.node_id, parameter=self.target_position, fp3=fp3, ) await command.send() await self.after_update() # KLF200 always send UNKNOWN position for functional parameter, # so orientation is set directly and not via GW_NODE_STATE_POSITION_CHANGED_NTF async def open_orientation(self, wait_for_completion: bool = True) -> None: """Open Blind slats orientation. Blind slats with ±90° orientation are open at 50% """ await self.set_orientation( orientation=Position(position_percent=self.open_orientation_target), wait_for_completion=wait_for_completion, ) async def close_orientation(self, wait_for_completion: bool = True) -> None: """Close Blind slats.""" await self.set_orientation( orientation=Position(position_percent=self.close_orientation_target), wait_for_completion=wait_for_completion, ) async def stop_orientation(self, wait_for_completion: bool = True) -> None: """Stop Blind slats.""" await self.set_orientation( orientation=CurrentPosition(), wait_for_completion=wait_for_completion )
class Blind(OpeningDevice): '''Blind objects.''' def __init__( self, pyvlx: "PyVLX", node_id: int, name: str, serial_number: Optional[str], position_parameter: Parameter = Parameter(), ): '''Initialize Blind class. Parameters: * pyvlx: PyVLX object * node_id: internal id for addressing nodes. Provided by KLF 200 device * name: node name ''' pass async def set_position_and_orientation( self, position: Position, wait_for_completion: bool = True, velocity: Velocity | int | None = None, orientation: Optional[Position] = None, ) -> None: '''Set window to desired position. Parameters: * position: Position object containing the current position. * velocity: Velocity to be used during transition. * target_position: Position object holding the target position which allows to adjust the position while the blind is in movement without stopping the blind (if orientation position has been changed.) * wait_for_completion: If set, function will return after device has reached target position. * orientation: If set, the orientation of the device will be set in the same request. Note, that, if the position is set to 0, the orientation will be set to 0 too. ''' pass async def set_position_and_orientation( self, position: Position, wait_for_completion: bool = True, velocity: Velocity | int | None = None, orientation: Optional[Position] = None, ) -> None: '''Set window to desired position. Parameters: * position: Position object containing the current position. * velocity: Velocity to be used during transition. * target_position: Position object holding the target position which allows to adjust the position while the blind is in movement without stopping the blind (if orientation position has been changed.) * wait_for_completion: If set, function will return after device has reached target position. ''' pass async def open( self, velocity: Velocity | int | None = Velocity.DEFAULT, wait_for_completion: bool = True, ) -> None: '''Open window. Parameters: * velocity: Velocity to be used during transition. * wait_for_completion: If set, function will return after device has reached target position. ''' pass async def close( self, velocity: Velocity | int | None = Velocity.DEFAULT, wait_for_completion: bool = True, ) -> None: '''Close window. Parameters: * velocity: Velocity to be used during transition. * wait_for_completion: If set, function will return after device has reached target position. ''' pass async def stop(self, wait_for_completion: bool = True) -> None: '''Stop Blind position.''' pass async def set_orientation( self, orientation: Position, wait_for_completion: bool = True ) -> None: '''Set Blind shades to desired orientation. Parameters: * orientation: Position object containing the target orientation. + target_orientation: Position object holding the target orientation which allows to adjust the orientation while the blind is in movement without stopping the blind (if the position has been changed.) * wait_for_completion: If set, function will return after device has reached target position. ''' pass async def open_orientation(self, wait_for_completion: bool = True) -> None: '''Open Blind slats orientation. Blind slats with ±90° orientation are open at 50% ''' pass async def close_orientation(self, wait_for_completion: bool = True) -> None: '''Close Blind slats.''' pass async def stop_orientation(self, wait_for_completion: bool = True) -> None: '''Stop Blind slats.''' pass
11
11
20
2
13
6
2
0.47
1
12
7
0
10
10
10
28
215
26
129
53
90
60
49
21
38
8
2
3
18
140,478
Julius2342/pyvlx
Julius2342_pyvlx/pyvlx/opening_device.py
pyvlx.opening_device.Blade
class Blade(OpeningDevice): """Blade object."""
class Blade(OpeningDevice): '''Blade object.''' pass
1
1
0
0
0
0
0
1
1
0
0
0
0
0
0
18
2
0
1
1
0
1
1
1
0
0
2
0
0
140,479
Julius2342/pyvlx
Julius2342_pyvlx/pyvlx/opening_device.py
pyvlx.opening_device.Awning
class Awning(OpeningDevice): """Awning objects."""
class Awning(OpeningDevice): '''Awning objects.''' pass
1
1
0
0
0
0
0
1
1
0
0
0
0
0
0
18
2
0
1
1
0
1
1
1
0
0
2
0
0
140,480
Julius2342/pyvlx
Julius2342_pyvlx/pyvlx/on_off_switch.py
pyvlx.on_off_switch.OnOffSwitch
class OnOffSwitch(Node): """Class for controlling on-off switches.""" def __init__(self, pyvlx: "PyVLX", node_id: int, name: str, serial_number: Optional[str]): """Initialize opening device.""" super().__init__( pyvlx=pyvlx, node_id=node_id, name=name, serial_number=serial_number ) self.parameter = SwitchParameter() async def set_state(self, parameter: SwitchParameter) -> None: """Set switch to desired state.""" command = CommandSend( pyvlx=self.pyvlx, node_id=self.node_id, parameter=parameter ) await command.send() await self.after_update() async def set_on(self) -> None: """Set switch on.""" await self.set_state(SwitchParameterOn()) async def set_off(self) -> None: """Set switch off.""" await self.set_state(SwitchParameterOff()) def is_on(self) -> bool: """Return if switch is set to on.""" return self.parameter.is_on() def is_off(self) -> bool: """Return if switch is set to off.""" return self.parameter.is_off()
class OnOffSwitch(Node): '''Class for controlling on-off switches.''' def __init__(self, pyvlx: "PyVLX", node_id: int, name: str, serial_number: Optional[str]): '''Initialize opening device.''' pass async def set_state(self, parameter: SwitchParameter) -> None: '''Set switch to desired state.''' pass async def set_on(self) -> None: '''Set switch on.''' pass async def set_off(self) -> None: '''Set switch off.''' pass def is_on(self) -> bool: '''Return if switch is set to on.''' pass def is_off(self) -> bool: '''Return if switch is set to off.''' pass
7
7
4
0
3
1
1
0.35
1
8
4
0
6
3
6
14
33
6
20
10
13
7
16
9
9
1
1
0
6
140,481
Julius2342/pyvlx
Julius2342_pyvlx/pyvlx/nodes.py
pyvlx.nodes.Nodes
class Nodes: """Object for storing node objects.""" def __init__(self, pyvlx: "PyVLX"): """Initialize Nodes object.""" self.pyvlx = pyvlx self.__nodes: List[Node] = [] def __iter__(self) -> Iterator[Node]: """Iterate.""" yield from self.__nodes def __getitem__(self, key: Union[str, int]) -> Node: """Return node by name or by index.""" if isinstance(key, int): for node in self.__nodes: if node.node_id == key: return node for node in self.__nodes: if node.name == key: return node raise KeyError def __contains__(self, key: Union[str, int, Node]) -> bool: """Check if key is in index.""" if isinstance(key, int): for node in self.__nodes: if node.node_id == key: return True if isinstance(key, Node): for node in self.__nodes: if node == key: return True for node in self.__nodes: if node.name == key: return True return False def __len__(self) -> int: """Return number of nodes.""" return len(self.__nodes) def add(self, node: Node) -> None: """Add Node, replace existing node if node with node_id is present.""" if not isinstance(node, Node): raise TypeError() for i, j in enumerate(self.__nodes): if j.node_id == node.node_id: self.__nodes[i] = node return self.__nodes.append(node) def clear(self) -> None: """Clear internal node array.""" self.__nodes = [] async def load(self, node_id: Optional[int] = None) -> None: """Load nodes from KLF 200, if no node_id is specified all nodes are loaded.""" if node_id is not None: await self._load_node(node_id=node_id) else: await self._load_all_nodes() async def _load_node(self, node_id: int) -> None: """Load single node via API.""" get_node_information = GetNodeInformation(pyvlx=self.pyvlx, node_id=node_id) await get_node_information.do_api_call() if not get_node_information.success: raise PyVLXException("Unable to retrieve node information") notification_frame = get_node_information.notification_frame if notification_frame is None: return node = convert_frame_to_node(self.pyvlx, notification_frame) if node is not None: self.add(node) async def _load_all_nodes(self) -> None: """Load all nodes via API.""" get_all_nodes_information = GetAllNodesInformation(pyvlx=self.pyvlx) await get_all_nodes_information.do_api_call() if not get_all_nodes_information.success: raise PyVLXException("Unable to retrieve node information") self.clear() for notification_frame in get_all_nodes_information.notification_frames: node = convert_frame_to_node(self.pyvlx, notification_frame) if node is not None: self.add(node)
class Nodes: '''Object for storing node objects.''' def __init__(self, pyvlx: "PyVLX"): '''Initialize Nodes object.''' pass def __iter__(self) -> Iterator[Node]: '''Iterate.''' pass def __getitem__(self, key: Union[str, int]) -> Node: '''Return node by name or by index.''' pass def __contains__(self, key: Union[str, int, Node]) -> bool: '''Check if key is in index.''' pass def __len__(self) -> int: '''Return number of nodes.''' pass def add(self, node: Node) -> None: '''Add Node, replace existing node if node with node_id is present.''' pass def clear(self) -> None: '''Clear internal node array.''' pass async def load(self, node_id: Optional[int] = None) -> None: '''Load nodes from KLF 200, if no node_id is specified all nodes are loaded.''' pass async def _load_node(self, node_id: int) -> None: '''Load single node via API.''' pass async def _load_all_nodes(self) -> None: '''Load all nodes via API.''' pass
11
11
8
0
7
1
3
0.17
0
10
4
0
10
2
10
10
87
10
66
22
55
11
65
22
54
9
0
3
33
140,482
Julius2342/pyvlx
Julius2342_pyvlx/pyvlx/node_updater.py
pyvlx.node_updater.NodeUpdater
class NodeUpdater: """Class for updating nodes via incoming frames, usually received by house monitor.""" def __init__(self, pyvlx: "PyVLX"): """Initialize NodeUpdater object.""" self.pyvlx = pyvlx async def process_frame_status_request_notification( self, frame: FrameStatusRequestNotification ) -> None: """Process FrameStatusRequestNotification.""" PYVLXLOG.debug("NodeUpdater process frame: %s", frame) if frame.node_id not in self.pyvlx.nodes: return node = self.pyvlx.nodes[frame.node_id] if isinstance(node, Blind): if NodeParameter(0) not in frame.parameter_data: # MP missing in frame return if NodeParameter(3) not in frame.parameter_data: # FP3 missing in frame return position = Position(frame.parameter_data[NodeParameter(0)]) orientation = Position(frame.parameter_data[NodeParameter(3)]) if position.position <= Parameter.MAX: node.position = position PYVLXLOG.debug("%s position changed to: %s", node.name, position) if orientation.position <= Parameter.MAX: node.orientation = orientation PYVLXLOG.debug("%s orientation changed to: %s", node.name, orientation) await node.after_update() if isinstance(node, DualRollerShutter): if NodeParameter(0) not in frame.parameter_data: # MP missing in frame return if NodeParameter(1) not in frame.parameter_data: # FP1 missing in frame return if NodeParameter(2) not in frame.parameter_data: # FP2 missing in frame return position = Position(frame.parameter_data[NodeParameter(0)]) position_upper_curtain = Position(frame.parameter_data[NodeParameter(1)]) position_lower_curtain = Position(frame.parameter_data[NodeParameter(2)]) if position.position <= Parameter.MAX: node.position = position PYVLXLOG.debug("%s position changed to: %s", node.name, position) if position_upper_curtain.position <= Parameter.MAX: node.position_upper_curtain = position_upper_curtain PYVLXLOG.debug( "%s position upper curtain changed to: %s", node.name, position_upper_curtain, ) if position_lower_curtain.position <= Parameter.MAX: node.position_lower_curtain = position_lower_curtain PYVLXLOG.debug( "%s position lower curtain changed to: %s", node.name, position_lower_curtain, ) await node.after_update() async def process_frame(self, frame: FrameBase) -> None: """Update nodes via frame, usually received by house monitor.""" if isinstance( frame, ( FrameGetAllNodesInformationNotification, FrameNodeStatePositionChangedNotification, ), ): PYVLXLOG.debug("NodeUpdater process frame: %s", frame) if frame.node_id not in self.pyvlx.nodes: return node = self.pyvlx.nodes[frame.node_id] position = Position(frame.current_position) target: Any = Position(frame.target) # KLF transmits for functional parameters basically always 'No feed-back value known’ (0xF7FF). # In home assistant this cause unreasonable values like -23%. Therefore a check is implemented # whether the frame parameter is inside the maximum range. # Set opening device status if isinstance(node, OpeningDevice): if (position.position > target.position <= Parameter.MAX) and ( (frame.state == OperatingState.EXECUTING) or frame.remaining_time > 0 ): node.is_opening = True PYVLXLOG.debug("%s is opening", node.name) node.state_received_at = datetime.datetime.now() node.estimated_completion = ( node.state_received_at + datetime.timedelta(0, frame.remaining_time) ) PYVLXLOG.debug( "%s will be opening until", node.estimated_completion ) elif (position.position < target.position <= Parameter.MAX) and ( (frame.state == OperatingState.EXECUTING) or frame.remaining_time > 0 ): node.is_closing = True PYVLXLOG.debug("%s is closing", node.name) node.state_received_at = datetime.datetime.now() node.estimated_completion = ( node.state_received_at + datetime.timedelta(0, frame.remaining_time) ) PYVLXLOG.debug( "%s will be closing until", node.estimated_completion ) else: if node.is_opening: node.is_opening = False node.state_received_at = None node.estimated_completion = None PYVLXLOG.debug("%s stops opening", node.name) if node.is_closing: node.is_closing = False PYVLXLOG.debug("%s stops closing", node.name) # Set main parameter if isinstance(node, OpeningDevice): if position.position <= Parameter.MAX: node.position = position node.target = target PYVLXLOG.debug("%s position changed to: %s", node.name, position) await node.after_update() elif isinstance(node, LighteningDevice): intensity = Intensity(frame.current_position) if intensity.intensity <= Parameter.MAX: node.intensity = intensity PYVLXLOG.debug("%s intensity changed to: %s", node.name, intensity) await node.after_update() elif isinstance(node, OnOffSwitch): state = SwitchParameter(frame.current_position) target = SwitchParameter(frame.target) if state.state == target.state: if state.state == Parameter.ON: node.parameter = state PYVLXLOG.debug("%s state changed to: %s", node.name, state) elif state.state == Parameter.OFF: node.parameter = state PYVLXLOG.debug("%s state changed to: %s", node.name, state) await node.after_update() elif isinstance(frame, FrameStatusRequestNotification): await self.process_frame_status_request_notification(frame)
class NodeUpdater: '''Class for updating nodes via incoming frames, usually received by house monitor.''' def __init__(self, pyvlx: "PyVLX"): '''Initialize NodeUpdater object.''' pass async def process_frame_status_request_notification( self, frame: FrameStatusRequestNotification ) -> None: '''Process FrameStatusRequestNotification.''' pass async def process_frame_status_request_notification( self, frame: FrameStatusRequestNotification ) -> None: '''Update nodes via frame, usually received by house monitor.''' pass
4
4
46
1
43
4
11
0.11
0
18
15
0
3
1
3
3
144
6
129
17
123
14
91
15
87
17
0
4
32
140,483
Julius2342/pyvlx
Julius2342_pyvlx/pyvlx/node.py
pyvlx.node.Node
class Node: """Class for node abstraction.""" def __init__(self, pyvlx: "PyVLX", node_id: int, name: str, serial_number: Optional[str]): """Initialize Node object.""" self.pyvlx = pyvlx self.node_id = node_id self.name = name self.serial_number = serial_number self.device_updated_cbs: List[CallbackType] = [] self.pyvlx.connection.register_connection_opened_cb(self.after_update) self.pyvlx.connection.register_connection_closed_cb(self.after_update) def register_device_updated_cb(self, device_updated_cb: CallbackType) -> None: """Register device updated callback.""" self.device_updated_cbs.append(device_updated_cb) def unregister_device_updated_cb(self, device_updated_cb: CallbackType) -> None: """Unregister device updated callback.""" self.device_updated_cbs.remove(device_updated_cb) async def after_update(self) -> None: """Execute callbacks after internal state has been changed.""" for device_updated_cb in self.device_updated_cbs: # pylint: disable=not-callable await self.pyvlx.loop.create_task(device_updated_cb(self)) # type: ignore async def rename(self, name: str) -> None: """Change name of node.""" set_node_name = SetNodeName(pyvlx=self.pyvlx, node_id=self.node_id, name=name) await set_node_name.do_api_call() if not set_node_name.success: raise PyVLXException("Unable to rename node") self.name = name @property def is_available(self) -> bool: """Return True if node is available.""" return self.pyvlx.get_connected() def __str__(self) -> str: """Return object as readable string.""" return ( '<{} name="{}" ' 'node_id="{}" ' 'serial_number="{}"/>'.format( type(self).__name__, self.name, self.node_id, self.serial_number ) ) def __eq__(self, other: Any) -> bool: """Equal operator.""" return ( type(self).__name__ == type(other).__name__ and self.__dict__ == other.__dict__ )
class Node: '''Class for node abstraction.''' def __init__(self, pyvlx: "PyVLX", node_id: int, name: str, serial_number: Optional[str]): '''Initialize Node object.''' pass def register_device_updated_cb(self, device_updated_cb: CallbackType) -> None: '''Register device updated callback.''' pass def unregister_device_updated_cb(self, device_updated_cb: CallbackType) -> None: '''Unregister device updated callback.''' pass async def after_update(self) -> None: '''Execute callbacks after internal state has been changed.''' pass async def rename(self, name: str) -> None: '''Change name of node.''' pass @property def is_available(self) -> bool: '''Return True if node is available.''' pass def __str__(self) -> str: '''Return object as readable string.''' pass def __eq__(self, other: Any) -> bool: '''Equal operator.''' pass
10
9
6
0
5
1
1
0.29
0
7
2
3
8
5
8
8
56
8
38
17
28
11
28
16
19
2
0
1
10
140,484
Julius2342/pyvlx
Julius2342_pyvlx/pyvlx/lightening_device.py
pyvlx.lightening_device.LighteningDevice
class LighteningDevice(Node): """Meta class for turning on device with one main parameter for intensity.""" def __init__(self, pyvlx: "PyVLX", node_id: int, name: str, serial_number: Optional[str]): """Initialize turning on device. Parameters: * pyvlx: PyVLX object * node_id: internal id for addressing nodes. Provided by KLF 200 device * name: node name * serial_number: serial number of the node. """ super().__init__( pyvlx=pyvlx, node_id=node_id, name=name, serial_number=serial_number ) self.intensity = Intensity() async def set_intensity(self, intensity: Intensity, wait_for_completion: bool = True) -> None: """Set light to desired intensity. Parameters: * intensity: Intensity object containing the target intensity. * wait_for_completion: If set, function will return after device has reached target intensity. """ command = CommandSend( pyvlx=self.pyvlx, wait_for_completion=wait_for_completion, node_id=self.node_id, parameter=intensity, ) await command.send() await self.after_update() async def turn_on(self, wait_for_completion: bool = True) -> None: """Turn on light. Parameters: * wait_for_completion: If set, function will return after device has reached target intensity. """ await self.set_intensity( intensity=Intensity(intensity_percent=0), wait_for_completion=wait_for_completion, ) async def turn_off(self, wait_for_completion: bool = True) -> None: """Turn off light. Parameters: * wait_for_completion: If set, function will return after device has reached target intensity. """ await self.set_intensity( intensity=Intensity(intensity_percent=100), wait_for_completion=wait_for_completion, )
class LighteningDevice(Node): '''Meta class for turning on device with one main parameter for intensity.''' def __init__(self, pyvlx: "PyVLX", node_id: int, name: str, serial_number: Optional[str]): '''Initialize turning on device. Parameters: * pyvlx: PyVLX object * node_id: internal id for addressing nodes. Provided by KLF 200 device * name: node name * serial_number: serial number of the node. ''' pass async def set_intensity(self, intensity: Intensity, wait_for_completion: bool = True) -> None: '''Set light to desired intensity. Parameters: * intensity: Intensity object containing the target intensity. * wait_for_completion: If set, function will return after device has reached target intensity. ''' pass async def turn_on(self, wait_for_completion: bool = True) -> None: '''Turn on light. Parameters: * wait_for_completion: If set, function will return after device has reached target intensity. ''' pass async def turn_off(self, wait_for_completion: bool = True) -> None: '''Turn off light. Parameters: * wait_for_completion: If set, function will return after device has reached target intensity. ''' pass
5
5
14
2
6
6
1
1
1
6
2
1
4
3
4
12
62
12
25
9
20
25
12
7
7
1
1
0
4
140,485
Julius2342/pyvlx
Julius2342_pyvlx/pyvlx/lightening_device.py
pyvlx.lightening_device.Light
class Light(LighteningDevice): """Light object.""" def __init__(self, pyvlx: "PyVLX", node_id: int, name: str, serial_number: Optional[str]): """Initialize Light class. Parameters: * pyvlx: PyVLX object * node_id: internal id for addressing nodes. Provided by KLF 200 device * name: node name * serial_number: serial number of the node. """ super().__init__( pyvlx=pyvlx, node_id=node_id, name=name, serial_number=serial_number ) def __str__(self) -> str: """Return object as readable string.""" return ( '<{} name="{}" ' 'node_id="{}" ' 'serial_number="{}"/>'.format( type(self).__name__, self.name, self.node_id, self.serial_number ) )
class Light(LighteningDevice): '''Light object.''' def __init__(self, pyvlx: "PyVLX", node_id: int, name: str, serial_number: Optional[str]): '''Initialize Light class. Parameters: * pyvlx: PyVLX object * node_id: internal id for addressing nodes. Provided by KLF 200 device * name: node name * serial_number: serial number of the node. ''' pass def __str__(self) -> str: '''Return object as readable string.''' pass
3
3
12
1
6
5
1
0.77
1
4
0
0
2
0
2
14
27
4
13
3
10
10
5
3
2
1
2
0
2
140,486
Julius2342/pyvlx
Julius2342_pyvlx/pyvlx/klf200gateway.py
pyvlx.klf200gateway.Klf200Gateway
class Klf200Gateway: """Class for node abstraction.""" def __init__(self, pyvlx: "PyVLX"): """Initialize Node object.""" self.pyvlx = pyvlx self.state: Optional[DtoState] = None self.network_setup: Optional[DtoNetworkSetup] = None self.password: Optional[str] = None self.time: Optional[DtoLocalTime] = None self.protocol_version: Optional[DtoProtocolVersion] = None self.version: Optional[DtoVersion] = None self.device_updated_cbs: List[CallbackType] = [] self.house_status_monitor_enabled = False def register_device_updated_cb(self, device_updated_cb: CallbackType) -> None: """Register device updated callback.""" self.device_updated_cbs.append(device_updated_cb) def unregister_device_updated_cb(self, device_updated_cb: CallbackType) -> None: """Unregister device updated callback.""" self.device_updated_cbs.remove(device_updated_cb) async def after_update(self) -> None: """Execute callbacks after internal state has been changed.""" for device_updated_cb in self.device_updated_cbs: # pylint: disable=not-callable await device_updated_cb(self) async def get_state(self) -> bool: """Retrieve state from API.""" get_state = GetState(pyvlx=self.pyvlx) await get_state.do_api_call() if not get_state.success: raise PyVLXException("Unable to retrieve state") self.state = get_state.state return get_state.success async def get_network_setup(self) -> bool: """Retrieve network setup from API.""" get_network_setup = GetNetworkSetup(pyvlx=self.pyvlx) await get_network_setup.do_api_call() if not get_network_setup.success: raise PyVLXException("Unable to retrieve network setup") self.network_setup = get_network_setup.networksetup return get_network_setup.success async def get_version(self) -> bool: """Retrieve version from API.""" get_version = GetVersion(pyvlx=self.pyvlx) await get_version.do_api_call() if not get_version.success: raise PyVLXException("Unable to retrieve version") self.version = get_version.version return get_version.success async def get_protocol_version(self) -> bool: """Retrieve protocol version from API.""" get_protocol_version = GetProtocolVersion(pyvlx=self.pyvlx) await get_protocol_version.do_api_call() if not get_protocol_version.success: raise PyVLXException("Unable to retrieve protocol version") self.protocol_version = get_protocol_version.protocolversion return get_protocol_version.success async def leave_learn_state(self) -> bool: """Leave Learn state from API.""" leave_learn_state = LeaveLearnState(pyvlx=self.pyvlx) await leave_learn_state.do_api_call() if not leave_learn_state.success: raise PyVLXException("Unable to leave learn state") return leave_learn_state.success async def set_utc(self) -> bool: """Set UTC Clock.""" setutc = SetUTC(pyvlx=self.pyvlx) await setutc.do_api_call() if not setutc.success: raise PyVLXException("Unable to set utc.") return setutc.success async def set_rtc_time_zone(self) -> None: """Set the RTC Time Zone.""" # idontwant = setrtctimezone(pyvlx=self.pyvlx) raise PyVLXException("KLF 200 RTC Timezone Set not implemented") # return setrtctimezone.success async def reboot(self) -> bool: """Reboot gateway.""" reboot = Reboot(pyvlx=self.pyvlx) await reboot.do_api_call() if not reboot.success: raise PyVLXException("Unable to reboot gateway.") await self.pyvlx.disconnect() return reboot.success async def set_factory_default(self) -> bool: """Set Gateway to Factory Default.""" factorydefault = FactoryDefault(pyvlx=self.pyvlx) await factorydefault.do_api_call() if not factorydefault.success: raise PyVLXException("Unable to factory Default Reset gateway.") return factorydefault.success async def get_local_time(self) -> bool: """Get local time from gateway.""" getlocaltime = GetLocalTime(pyvlx=self.pyvlx) await getlocaltime.do_api_call() if not getlocaltime.success: raise PyVLXException("Unable to get local time.") self.time = getlocaltime.localtime return getlocaltime.success async def password_enter(self, password: str) -> bool: """Get enter Password for gateway.""" self.password = password passwordenter = PasswordEnter(pyvlx=self.pyvlx, password=self.password) await passwordenter.do_api_call() if not passwordenter.success: raise PyVLXException("Login to KLF 200 failed, check credentials") return passwordenter.success async def house_status_monitor_enable(self, pyvlx: "PyVLX") -> None: """Enable house status monitor.""" status_monitor_enable = HouseStatusMonitorEnable(pyvlx=pyvlx) await status_monitor_enable.do_api_call() if not status_monitor_enable.success: raise PyVLXException("Unable enable house status monitor.") self.house_status_monitor_enabled = True async def house_status_monitor_disable(self, pyvlx: "PyVLX", timeout: Optional[int] = None) -> None: """Disable house status monitor.""" status_monitor_disable = HouseStatusMonitorDisable(pyvlx=pyvlx) if timeout is not None: status_monitor_disable.timeout_in_seconds = timeout await status_monitor_disable.do_api_call() if not status_monitor_disable.success: raise PyVLXException("Unable disable house status monitor.") self.house_status_monitor_enabled = False def __str__(self) -> str: """Return object as readable string.""" return '<{} state="{}" network_setup="{}" version="{}" protocol_version="{}"/>'.format( type(self).__name__, str(self.state), str(self.network_setup), str(self.version), str(self.protocol_version), )
class Klf200Gateway: '''Class for node abstraction.''' def __init__(self, pyvlx: "PyVLX"): '''Initialize Node object.''' pass def register_device_updated_cb(self, device_updated_cb: CallbackType) -> None: '''Register device updated callback.''' pass def unregister_device_updated_cb(self, device_updated_cb: CallbackType) -> None: '''Unregister device updated callback.''' pass async def after_update(self) -> None: '''Execute callbacks after internal state has been changed.''' pass async def get_state(self) -> bool: '''Retrieve state from API.''' pass async def get_network_setup(self) -> bool: '''Retrieve network setup from API.''' pass async def get_version(self) -> bool: '''Retrieve version from API.''' pass async def get_protocol_version(self) -> bool: '''Retrieve protocol version from API.''' pass async def leave_learn_state(self) -> bool: '''Leave Learn state from API.''' pass async def set_utc(self) -> bool: '''Set UTC Clock.''' pass async def set_rtc_time_zone(self) -> None: '''Set the RTC Time Zone.''' pass async def reboot(self) -> bool: '''Reboot gateway.''' pass async def set_factory_default(self) -> bool: '''Set Gateway to Factory Default.''' pass async def get_local_time(self) -> bool: '''Get local time from gateway.''' pass async def password_enter(self, password: str) -> bool: '''Get enter Password for gateway.''' pass async def house_status_monitor_enable(self, pyvlx: "PyVLX") -> None: '''Enable house status monitor.''' pass async def house_status_monitor_disable(self, pyvlx: "PyVLX", timeout: Optional[int] = None) -> None: '''Disable house status monitor.''' pass def __str__(self) -> str: '''Return object as readable string.''' pass
19
19
7
0
6
1
2
0.2
0
22
18
0
18
9
18
18
149
18
109
41
90
22
103
41
84
3
0
1
32
140,487
Julius2342/pyvlx
Julius2342_pyvlx/old_api/pyvlx/interface.py
pyvlx.interface.Interface
class Interface: """Interface to KLF 200.""" def __init__(self, config, timeout=10): """Initialize interface class.""" self.config = config self.token = None self.timeout = timeout async def api_call(self, verb, action, params=None, add_authorization_token=True, retry=False): """Send api call.""" if add_authorization_token and not self.token: await self.refresh_token() try: return await self._api_call_impl(verb, action, params, add_authorization_token) except InvalidToken: if not retry and add_authorization_token: await self.refresh_token() # Recursive call of api_call return await self.api_call(verb, action, params, add_authorization_token, True) raise async def _api_call_impl(self, verb, action, params=None, add_authorization_token=True): url = self.create_api_url(self.config.host, verb) body = self.create_body(action, params) headers = self.create_headers(add_authorization_token, self.token) return await self._do_http_request(url, body, headers) async def _do_http_request(self, url, body, headers): try: return await self._do_http_request_impl(url, body, headers) except asyncio.TimeoutError: raise PyVLXException("Request timeout when talking to VELUX API") except aiohttp.ClientError: raise PyVLXException("HTTP error when talking to VELUX API") except OSError: raise PyVLXException("OS error when talking to VELUX API") async def _do_http_request_impl(self, url, body, headers): print(url, body, headers) async with aiohttp.ClientSession() as session: with async_timeout.timeout(self.timeout): async with session.post(url, data=json.dumps(body), headers=headers) as response: response = await response.text() response = self.fix_response(response) print(response) json_response = json.loads(response) self.evaluate_response(json_response) # print(json.dumps(json_response, indent=4, sort_keys=True)) return json_response async def refresh_token(self): """Refresh API token from KLF 200.""" json_response = await self.api_call('auth', 'login', {'password': self.config.password}, add_authorization_token=False) if 'token' not in json_response: raise PyVLXException('no element token found in response: {0}'.format(json.dumps(json_response))) self.token = json_response['token'] async def disconnect(self): """Disconnect from KLF 200.""" await self.api_call('auth', 'logout', {}, add_authorization_token=True) self.token = None @staticmethod def create_api_url(host, verb): """Return full rest url.""" return 'http://{0}/api/v1/{1}'.format(host, verb) @staticmethod def create_headers(add_authorization_token, token=None): """Create http header for rest request.""" headers = {} headers['Content-Type'] = 'application/json' if add_authorization_token: headers['Authorization'] = 'Bearer ' + token return headers @staticmethod def create_body(action, params): """Create http body for rest request.""" body = {} body['action'] = action if params is not None: body['params'] = params return body @staticmethod def evaluate_response(json_response): """Evaluate rest response.""" if 'errors' in json_response and json_response['errors']: Interface.evaluate_errors(json_response) elif 'result' not in json_response: raise PyVLXException('no element result found in response: {0}'.format(json.dumps(json_response))) elif not json_response['result']: raise PyVLXException('Request failed {0}'.format(json.dumps(json_response))) @staticmethod def evaluate_errors(json_response): """Evaluate rest errors.""" if 'errors' not in json_response or \ not isinstance(json_response['errors'], list) or \ not json_response['errors'] or \ not isinstance(json_response['errors'][0], int): raise PyVLXException('Could not evaluate errors {0}'.format(json.dumps(json_response))) # unclear if response may contain more errors than one. Taking the first. first_error = json_response['errors'][0] if first_error in [402, 403, 405, 406]: raise InvalidToken(first_error) raise PyVLXException('Unknown error code {0}'.format(first_error)) @staticmethod def fix_response(response): """Fix broken rest reponses.""" # WTF: For whatever reason, the KLF 200 sometimes puts an ')]}',' in front of the response ... index = response.find('{') if index > 0: return response[index:] return response
class Interface: '''Interface to KLF 200.''' def __init__(self, config, timeout=10): '''Initialize interface class.''' pass async def api_call(self, verb, action, params=None, add_authorization_token=True, retry=False): '''Send api call.''' pass async def _api_call_impl(self, verb, action, params=None, add_authorization_token=True): pass async def _do_http_request(self, url, body, headers): pass async def _do_http_request_impl(self, url, body, headers): pass async def refresh_token(self): '''Refresh API token from KLF 200.''' pass async def disconnect(self): '''Disconnect from KLF 200.''' pass @staticmethod def create_api_url(host, verb): '''Return full rest url.''' pass @staticmethod def create_headers(add_authorization_token, token=None): '''Create http header for rest request.''' pass @staticmethod def create_body(action, params): '''Create http body for rest request.''' pass @staticmethod def evaluate_response(json_response): '''Evaluate rest response.''' pass @staticmethod def evaluate_errors(json_response): '''Evaluate rest errors.''' pass @staticmethod def fix_response(response): '''Fix broken rest reponses.''' pass
20
11
8
0
6
1
2
0.17
0
8
2
0
7
3
13
13
122
17
90
34
70
15
79
26
65
4
0
3
28
140,488
Julius2342/pyvlx
Julius2342_pyvlx/pyvlx/heartbeat.py
pyvlx.heartbeat.Heartbeat
class Heartbeat: """Class for sending heartbeats to API.""" def __init__( self, pyvlx: "PyVLX", interval: int = 30, load_all_states: bool = True ): """Initialize Heartbeat object.""" PYVLXLOG.debug("Heartbeat __init__") self.pyvlx = pyvlx self.interval = interval self.load_all_states = load_all_states self.task: Any = None async def _run(self) -> None: PYVLXLOG.debug("Heartbeat: task started") while True: PYVLXLOG.debug("Heartbeat: sleeping") await asyncio.sleep(self.interval) PYVLXLOG.debug("Heartbeat: pulsing") try: await self.pulse() except (OSError, PyVLXException) as e: PYVLXLOG.debug("Heartbeat: pulsing failed: %s", e) async def _start(self) -> None: if self.task is not None: await self.stop() PYVLXLOG.debug("Heartbeat: creating task") self.task = asyncio.create_task(self._run()) def start(self) -> None: """Start heartbeat.""" PYVLXLOG.debug("Heartbeat start") asyncio.run_coroutine_threadsafe(self._start(), self.pyvlx.loop) @property def stopped(self) -> bool: """Return Heartbeat running state.""" return self.task is None async def stop(self) -> None: """Stop heartbeat.""" if self.task is not None: self.task.cancel() self.task = None PYVLXLOG.debug("Heartbeat stopped") else: PYVLXLOG.debug("Heartbeat was not running") async def pulse(self) -> None: """Send get state request to API to keep the connection alive.""" PYVLXLOG.debug("Heartbeat pulse") get_state = GetState(pyvlx=self.pyvlx) await get_state.do_api_call() if not get_state.success: raise PyVLXException("Unable to send get state.") # If nodes contain Blind or DualRollerShutter device, refresh orientation or upper/lower curtain positions because House Monitoring # delivers wrong values for FP1, FP2 and FP3 parameter for node in self.pyvlx.nodes: if isinstance(node, (Blind, DualRollerShutter)) or self.load_all_states: status_request = StatusRequest(self.pyvlx, node.node_id) await status_request.do_api_call() # give user requests a chance await asyncio.sleep(0.5)
class Heartbeat: '''Class for sending heartbeats to API.''' def __init__( self, pyvlx: "PyVLX", interval: int = 30, load_all_states: bool = True ): '''Initialize Heartbeat object.''' pass async def _run(self) -> None: pass async def _start(self) -> None: pass def start(self) -> None: '''Start heartbeat.''' pass @property def stopped(self) -> bool: '''Return Heartbeat running state.''' pass def stopped(self) -> bool: '''Stop heartbeat.''' pass async def pulse(self) -> None: '''Send get state request to API to keep the connection alive.''' pass
9
6
8
0
7
1
2
0.19
0
9
5
0
7
4
7
7
65
8
48
19
37
9
44
15
36
4
0
2
14
140,489
Julius2342/pyvlx
Julius2342_pyvlx/pyvlx/exception.py
pyvlx.exception.PyVLXException
class PyVLXException(Exception): """Default PyVLX Exception.""" def __init__(self, description: str, **kwargs: Any): """Initialize PyVLXException class.""" super().__init__(description) self.description = description self.parameter = kwargs def _format_parameter(self) -> str: return " ".join( [ '%s="%s"' % (key, value) for (key, value) in sorted(self.parameter.items()) ] ) def __str__(self) -> str: """Return object as readable string.""" return '<{} description="{}" {}/>'.format( type(self).__name__, self.description, self._format_parameter() )
class PyVLXException(Exception): '''Default PyVLX Exception.''' def __init__(self, description: str, **kwargs: Any): '''Initialize PyVLXException class.''' pass def _format_parameter(self) -> str: pass def __str__(self) -> str: '''Return object as readable string.''' pass
4
3
6
0
5
1
1
0.19
1
4
0
0
3
2
3
13
22
3
16
6
12
3
9
6
5
1
3
0
3
140,490
Julius2342/pyvlx
Julius2342_pyvlx/old_api/pyvlx/exception.py
pyvlx.exception.PyVLXException
class PyVLXException(Exception): """Exception class for PyVLX library.""" def __init__(self, description): """Initialize exception with the given error message.""" super(PyVLXException, self).__init__() self.description = description def __str__(self) -> str: """Return object as readable string.""" return '<PyVLXException description="{0}" />' \ .format(self.description)
class PyVLXException(Exception): '''Exception class for PyVLX library.''' def __init__(self, description): '''Initialize exception with the given error message.''' pass def __str__(self) -> str: '''Return object as readable string.''' pass
3
3
4
0
3
1
1
0.43
1
2
0
1
2
1
2
12
12
2
7
4
4
3
6
4
3
1
3
0
2
140,491
Julius2342/pyvlx
Julius2342_pyvlx/old_api/pyvlx/exception.py
pyvlx.exception.InvalidToken
class InvalidToken(PyVLXException): """KLF 200 token invalid or expired.""" def __init__(self, error_code): """Initialize exception with the given error message.""" super(InvalidToken, self).__init__("Invalid Token") self.error_code = error_code
class InvalidToken(PyVLXException): '''KLF 200 token invalid or expired.''' def __init__(self, error_code): '''Initialize exception with the given error message.''' pass
2
2
4
0
3
1
1
0.5
1
1
0
0
1
1
1
13
7
1
4
3
2
2
4
3
2
1
4
0
1
140,492
Julius2342/pyvlx
Julius2342_pyvlx/pyvlx/discovery.py
pyvlx.discovery.VeluxHost
class VeluxHost(): """Class to store Velux KLF200 host information.""" hostname: str ip_address: str
class VeluxHost(): '''Class to store Velux KLF200 host information.''' pass
1
1
0
0
0
0
0
0.33
0
0
0
0
0
0
0
0
5
1
3
1
2
1
3
1
2
0
0
0
0
140,493
Julius2342/pyvlx
Julius2342_pyvlx/pyvlx/discovery.py
pyvlx.discovery.VeluxDiscovery
class VeluxDiscovery(): """Class to discover Velux KLF200 devices on the network.""" hosts: list[VeluxHost] = [] infos: list[AsyncServiceInfo | None] = [] def __init__(self, zeroconf: AsyncZeroconf,) -> None: """Initialize VeluxDiscovery object.""" self.zc: AsyncZeroconf = zeroconf async def _async_discover_hosts(self, min_wait_time: float, expected_hosts: int | None) -> None: """Listen for zeroconf ServiceInfo.""" self.hosts.clear() service_names: list[str] = [] tasks: Set[Task] = set() got_host: Event = Event() def add_info_and_host(fut: Future) -> None: info: AsyncServiceInfo = fut.result() self.infos.append(info) host = VeluxHost( hostname=info.name.replace("._http._tcp.local.", ""), ip_address=info.parsed_addresses(version=IPVersion.V4Only)[0], ) self.hosts.append(host) got_host.set() def handler(name: str, **kwargs: Any) -> None: # pylint: disable=W0613:unused-argument if name.startswith(SERVICE_STARTS_WITH): if name not in service_names: service_names.append(name) task = asyncio.create_task(self.zc.async_get_service_info(type_=SERVICE_TYPE, name=name)) tasks.add(task) task.add_done_callback(add_info_and_host) task.add_done_callback(tasks.remove) browser: AsyncServiceBrowser = AsyncServiceBrowser(self.zc.zeroconf, SERVICE_TYPE, handlers=[handler]) if expected_hosts: while len(self.hosts) < expected_hosts: await got_host.wait() got_host.clear() while not self.hosts: await asyncio.sleep(min_wait_time) await browser.async_cancel() if tasks: await asyncio.gather(*tasks) async def async_discover_hosts( self, timeout: float = 10, min_wait_time: float = 3, expected_hosts: Optional[int] = None ) -> bool: """Return true if Velux KLF200 devices found on the network. This function creates a zeroconf AsyncServiceBrowser and waits min_wait_time (seconds) for ServiceInfos from hosts. Some devices may take some time to respond (i.e. if they currently have a high CPU load). If one or more Hosts are found, the function cancels the ServiceBrowser and returns true. If expected_hosts is set, the function ignores min_wait_time and returns true once expected_hosts are found. If timeout (seconds) is exceeded, the function returns false. """ try: async with asyncio.timeout(timeout): await self._async_discover_hosts(min_wait_time, expected_hosts) except TimeoutError: return False return True
class VeluxDiscovery(): '''Class to discover Velux KLF200 devices on the network.''' def __init__(self, zeroconf: AsyncZeroconf,) -> None: '''Initialize VeluxDiscovery object.''' pass async def _async_discover_hosts(self, min_wait_time: float, expected_hosts: int | None) -> None: '''Listen for zeroconf ServiceInfo.''' pass def add_info_and_host(fut: Future) -> None: pass def handler(name: str, **kwargs: Any) -> None: pass async def async_discover_hosts( self, timeout: float = 10, min_wait_time: float = 3, expected_hosts: Optional[int] = None ) -> bool: '''Return true if Velux KLF200 devices found on the network. This function creates a zeroconf AsyncServiceBrowser and waits min_wait_time (seconds) for ServiceInfos from hosts. Some devices may take some time to respond (i.e. if they currently have a high CPU load). If one or more Hosts are found, the function cancels the ServiceBrowser and returns true. If expected_hosts is set, the function ignores min_wait_time and returns true once expected_hosts are found. If timeout (seconds) is exceeded, the function returns false. ''' pass
6
4
15
1
13
2
2
0.24
0
12
1
0
3
1
3
3
68
8
49
21
38
12
41
16
35
5
0
2
12
140,494
Julius2342/pyvlx
Julius2342_pyvlx/pyvlx/opening_device.py
pyvlx.opening_device.GarageDoor
class GarageDoor(OpeningDevice): """GarageDoor object."""
class GarageDoor(OpeningDevice): '''GarageDoor object.''' pass
1
1
0
0
0
0
0
1
1
0
0
0
0
0
0
18
2
0
1
1
0
1
1
1
0
0
2
0
0
140,495
JungDev/django-telegrambot
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/JungDev_django-telegrambot/django_telegrambot/mqbot.py
django_telegrambot.mqbot.MQBot
class MQBot(telegram.bot.Bot): '''A subclass of Bot which delegates send method handling to MQ''' def __init__(self, mqueue=None, is_queued_def=True, *args, **kwargs): super(MQBot, self).__init__(*args, **kwargs) # below 2 attributes should be provided for decorator usage self._is_messages_queued_default = is_queued_def self._msg_queue = mqueue or mq.MessageQueue() def __del__(self): try: self._msg_queue.stop() except: pass super(MQBot, self).__del__() @mq.queuedmessage def send_message(self, *args, **kwargs): '''Wrapped method would accept new `queued` and `isgroup` OPTIONAL arguments''' return super(MQBot, self).send_message(*args, **kwargs) @mq.queuedmessage def edit_message_text(self, *args, **kwargs): '''Wrapped method would accept new `queued` and `isgroup` OPTIONAL arguments''' return super(MQBot, self).edit_message_text(*args, **kwargs)
class MQBot(telegram.bot.Bot): '''A subclass of Bot which delegates send method handling to MQ''' def __init__(self, mqueue=None, is_queued_def=True, *args, **kwargs): pass def __del__(self): pass @mq.queuedmessage def send_message(self, *args, **kwargs): '''Wrapped method would accept new `queued` and `isgroup` OPTIONAL arguments''' pass @mq.queuedmessage def edit_message_text(self, *args, **kwargs): '''Wrapped method would accept new `queued` and `isgroup` OPTIONAL arguments''' pass
7
3
5
0
4
1
1
0.35
1
1
0
0
4
2
4
4
27
4
17
9
10
6
15
7
10
2
1
1
5
140,496
JungDev/django-telegrambot
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/JungDev_django-telegrambot/tests/test_apps.py
tests.test_apps.TestDjangoTelegramBot
class TestDjangoTelegramBot(TestCase): def setUp(self): self.app = DjangoTelegramBot.create('django_telegrambot') @mock.patch('django_telegrambot.apps.apps', Apps(installed_apps=('tests.test_app',))) def test_good_app_loading(self, log): """Normal initialisation - should complete without error messages.""" self.assertFalse(DjangoTelegramBot.ready_run) self.app.ready() self.assertEquals(log.error.call_count, 0) self.assertTrue(DjangoTelegramBot.ready_run) @mock.patch('django_telegrambot.apps.apps', Apps(installed_apps=('tests.test_bad_app',))) def test_bad_app_loading(self, log): """If a telegrambot.py module in some of the apps contains a mistake, an error message should be loaded.""" self.app.ready() self.assertEquals(log.error.call_count, 1) @mock.patch('django_telegrambot.apps.apps', Apps(installed_apps=('tests.test_bad_app',))) @mock.patch.dict('django_telegrambot.apps.settings.DJANGO_TELEGRAMBOT', STRICT_INIT=True) def test_bad_app_loading_strict(self, _): """With STRICT_INIT set to true in the DJANGO_TELEGRAMBOT settings, the app must not start if the telegrambot.py files are not imported successfully.""" with self.assertRaises(ImportError): self.app.ready()
class TestDjangoTelegramBot(TestCase): def setUp(self): pass @mock.patch('django_telegrambot.apps.apps', Apps(installed_apps=('tests.test_app',))) def test_good_app_loading(self, log): '''Normal initialisation - should complete without error messages.''' pass @mock.patch('django_telegrambot.apps.apps', Apps(installed_apps=('tests.test_bad_app',))) def test_bad_app_loading(self, log): '''If a telegrambot.py module in some of the apps contains a mistake, an error message should be loaded.''' pass @mock.patch('django_telegrambot.apps.apps', Apps(installed_apps=('tests.test_bad_app',))) @mock.patch.dict('django_telegrambot.apps.settings.DJANGO_TELEGRAMBOT', STRICT_INIT=True) def test_bad_app_loading_strict(self, _): '''With STRICT_INIT set to true in the DJANGO_TELEGRAMBOT settings, the app must not start if the telegrambot.py files are not imported successfully.''' pass
9
3
5
0
3
2
1
0.27
1
2
1
0
4
1
4
4
32
4
22
12
9
6
14
6
9
1
1
1
4
140,497
JungDev/django-telegrambot
JungDev_django-telegrambot/sampleproject/bot/apps.py
bot.apps.BotConfig
class BotConfig(AppConfig): name = 'bot'
class BotConfig(AppConfig): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
2
0
2
2
1
0
2
2
1
0
1
0
0
140,498
JungDev/django-telegrambot
JungDev_django-telegrambot/django_telegrambot/management/commands/botpolling.py
django_telegrambot.management.commands.botpolling.Command
class Command(BaseCommand): help = "Run telegram bot in polling mode" can_import_settings = True def add_arguments(self, parser): parser.add_argument('--username', '-i', help="Bot username", default=None) parser.add_argument('--token', '-t', help="Bot token", default=None) pass def get_updater(self, username=None, token=None): updater = None if username is not None: updater = DjangoTelegramBot.get_updater(bot_id=username) if not updater: self.stderr.write("Cannot find default bot with username {}".format(username)) elif token: updater = DjangoTelegramBot.get_updater(bot_id=token) if not updater: self.stderr.write("Cannot find bot with token {}".format(token)) return updater def handle(self, *args, **options): from django.conf import settings if settings.DJANGO_TELEGRAMBOT.get('MODE', 'WEBHOOK') == 'WEBHOOK': self.stderr.write("Webhook mode active in settings.py, change in POLLING if you want use polling update") return updater = self.get_updater(username=options.get('username'), token=options.get('token')) if not updater: self.stderr.write("Bot not found") return # Enable Logging logging.basicConfig( format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO) logger = logging.getLogger("telegrambot") logger.setLevel(logging.INFO) console = logging.StreamHandler() console.setLevel(logging.INFO) console.setFormatter(logging.Formatter('%(name)s - %(levelname)s - %(message)s')) logger.addHandler(console) bots_list = settings.DJANGO_TELEGRAMBOT.get('BOTS', []) b = None for bot_set in bots_list: if bot_set.get('TOKEN', None) == updater.bot.token: b = bot_set break if not b: self.stderr.write("Cannot find bot settings") return allowed_updates = b.get('ALLOWED_UPDATES', None) timeout = b.get('TIMEOUT', 10) poll_interval = b.get('POLL_INTERVAL', 0.0) clean = b.get('POLL_CLEAN', False) bootstrap_retries = b.get('POLL_BOOTSTRAP_RETRIES', 0) read_latency = b.get('POLL_READ_LATENCY', 2.) self.stdout.write("Run polling...") updater.start_polling(poll_interval=poll_interval, timeout=timeout, clean=clean, bootstrap_retries=bootstrap_retries, read_latency=read_latency, allowed_updates=allowed_updates) self.stdout.write("the bot is started and runs until we press Ctrl-C on the command line.") updater.idle()
class Command(BaseCommand): def add_arguments(self, parser): pass def get_updater(self, username=None, token=None): pass def handle(self, *args, **options): pass
4
0
21
2
19
0
4
0.02
1
3
1
0
3
0
3
3
69
8
60
20
55
1
52
20
47
6
1
2
12
140,499
JungDev/django-telegrambot
JungDev_django-telegrambot/tests/test_models.py
tests.test_models.TestDjango_telegrambot
class TestDjango_telegrambot(TestCase): def setUp(self): pass def test_something(self): pass def tearDown(self): pass
class TestDjango_telegrambot(TestCase): def setUp(self): pass def test_something(self): pass def tearDown(self): pass
4
0
2
0
2
0
1
0
1
0
0
0
3
0
3
3
10
3
7
4
3
0
7
4
3
1
1
0
3
140,500
JungDev/django-telegrambot
JungDev_django-telegrambot/django_telegrambot/apps.py
django_telegrambot.apps.DjangoTelegramBot
class DjangoTelegramBot(AppConfig): name = 'django_telegrambot' verbose_name = 'Django TelegramBot' ready_run = False bot_tokens = [] bot_usernames = [] dispatchers = [] bots = [] updaters = [] __used_tokens = set() @classproperty def dispatcher(cls): #print("Getting value default dispatcher") cls.__used_tokens.add(cls.bot_tokens[0]) return cls.dispatchers[0] @classproperty def updater(cls): #print("Getting value default updater") cls.__used_tokens.add(cls.bot_tokens[0]) return cls.updaters[0] @classmethod def get_dispatcher(cls, bot_id=None, safe=True): if bot_id is None: cls.__used_tokens.add(cls.bot_tokens[0]) return cls.dispatchers[0] else: try: index = cls.bot_tokens.index(bot_id) except ValueError: if not safe: return None try: index = cls.bot_usernames.index(bot_id) except ValueError: return None cls.__used_tokens.add(cls.bot_tokens[index]) return cls.dispatchers[index] @classmethod def getDispatcher(cls, bot_id=None, safe=True): return cls.get_dispatcher(bot_id, safe) @classmethod def get_bot(cls, bot_id=None, safe=True): if bot_id is None: if safe: return cls.bots[0] else: return None else: try: index = cls.bot_tokens.index(bot_id) except ValueError: if not safe: return None try: index = cls.bot_usernames.index(bot_id) except ValueError: return None return cls.bots[index] @classmethod def getBot(cls, bot_id=None, safe=True): return cls.get_bot(bot_id, safe) @classmethod def get_updater(cls, bot_id=None, safe=True): if bot_id is None: return cls.updaters[0] else: try: index = cls.bot_tokens.index(bot_id) except ValueError: if not safe: return None try: index = cls.bot_usernames.index(bot_id) except ValueError: return None return cls.updaters[index] @classmethod def getUpdater(cls, id=None, safe=True): return cls.get_updater(id, safe) def ready(self): if DjangoTelegramBot.ready_run: return DjangoTelegramBot.ready_run = True self.mode = WEBHOOK_MODE if settings.DJANGO_TELEGRAMBOT.get('MODE', 'WEBHOOK') == 'POLLING': self.mode = POLLING_MODE modes = ['WEBHOOK','POLLING'] logger.info('Django Telegram Bot <{} mode>'.format(modes[self.mode])) bots_list = settings.DJANGO_TELEGRAMBOT.get('BOTS', []) if self.mode == WEBHOOK_MODE: webhook_site = settings.DJANGO_TELEGRAMBOT.get('WEBHOOK_SITE', None) if not webhook_site: logger.warn('Required TELEGRAM_WEBHOOK_SITE missing in settings') return if webhook_site.endswith("/"): webhook_site = webhook_site[:-1] webhook_base = settings.DJANGO_TELEGRAMBOT.get('WEBHOOK_PREFIX','/') if webhook_base.startswith("/"): webhook_base = webhook_base[1:] if webhook_base.endswith("/"): webhook_base = webhook_base[:-1] cert = settings.DJANGO_TELEGRAMBOT.get('WEBHOOK_CERTIFICATE', None) certificate = None if cert and os.path.exists(cert): logger.info('WEBHOOK_CERTIFICATE found in {}'.format(cert)) certificate=open(cert, 'rb') elif cert: logger.error('WEBHOOK_CERTIFICATE not found in {} '.format(cert)) for b in bots_list: token = b.get('TOKEN', None) context = b.get('CONTEXT', False) if not token: break allowed_updates = b.get('ALLOWED_UPDATES', None) timeout = b.get('TIMEOUT', None) proxy = b.get('PROXY', None) if self.mode == WEBHOOK_MODE: try: if b.get('MESSAGEQUEUE_ENABLED',False): q = mq.MessageQueue(all_burst_limit=b.get('MESSAGEQUEUE_ALL_BURST_LIMIT',29), all_time_limit_ms=b.get('MESSAGEQUEUE_ALL_TIME_LIMIT_MS',1024)) if proxy: request = Request(proxy_url=proxy['proxy_url'], urllib3_proxy_kwargs=proxy['urllib3_proxy_kwargs'], con_pool_size=b.get('MESSAGEQUEUE_REQUEST_CON_POOL_SIZE',8)) else: request = Request(con_pool_size=b.get('MESSAGEQUEUE_REQUEST_CON_POOL_SIZE',8)) bot = MQBot(token, request=request, mqueue=q) else: request = None if proxy: request = Request(proxy_url=proxy['proxy_url'], urllib3_proxy_kwargs=proxy['urllib3_proxy_kwargs']) bot = telegram.Bot(token=token, request=request) DjangoTelegramBot.dispatchers.append(Dispatcher(bot, None, workers=0, use_context=context)) hookurl = '{}/{}/{}/'.format(webhook_site, webhook_base, token) max_connections = b.get('WEBHOOK_MAX_CONNECTIONS', 40) setted = bot.setWebhook(hookurl, certificate=certificate, timeout=timeout, max_connections=max_connections, allowed_updates=allowed_updates) webhook_info = bot.getWebhookInfo() real_allowed = webhook_info.allowed_updates if webhook_info.allowed_updates else ["ALL"] bot.more_info = webhook_info logger.info('Telegram Bot <{}> setting webhook [ {} ] max connections:{} allowed updates:{} pending updates:{} : {}'.format(bot.username, webhook_info.url, webhook_info.max_connections, real_allowed, webhook_info.pending_update_count, setted)) except InvalidToken: logger.error('Invalid Token : {}'.format(token)) return except RetryAfter as er: logger.debug('Error: "{}". Will retry in {} seconds'.format( er.message, er.retry_after ) ) sleep(er.retry_after) self.ready() except TelegramError as er: logger.error('Error: "{}"'.format(er.message)) return else: try: updater = Updater(token=token, request_kwargs=proxy, use_context=context) bot = updater.bot bot.delete_webhook() DjangoTelegramBot.updaters.append(updater) DjangoTelegramBot.dispatchers.append(updater.dispatcher) DjangoTelegramBot.__used_tokens.add(token) except InvalidToken: logger.error('Invalid Token : {}'.format(token)) return except RetryAfter as er: logger.debug('Error: "{}". Will retry in {} seconds'.format( er.message, er.retry_after ) ) sleep(er.retry_after) self.ready() except TelegramError as er: logger.error('Error: "{}"'.format(er.message)) return DjangoTelegramBot.bots.append(bot) DjangoTelegramBot.bot_tokens.append(token) DjangoTelegramBot.bot_usernames.append(bot.username) logger.debug('Telegram Bot <{}> set as default bot'.format(DjangoTelegramBot.bots[0].username)) def module_imported(module_name, method_name, execute): try: m = importlib.import_module(module_name) if execute and hasattr(m, method_name): logger.debug('Run {}.{}()'.format(module_name,method_name)) getattr(m, method_name)() else: logger.debug('Run {}'.format(module_name)) except ImportError as er: if settings.DJANGO_TELEGRAMBOT.get('STRICT_INIT'): raise er else: logger.error('{} : {}'.format(module_name, repr(er))) return False return True # import telegram bot handlers for all INSTALLED_APPS for app_config in apps.get_app_configs(): if module_has_submodule(app_config.module, TELEGRAM_BOT_MODULE_NAME): module_name = '%s.%s' % (app_config.name, TELEGRAM_BOT_MODULE_NAME) if module_imported(module_name, 'main', True): logger.info('Loaded {}'.format(module_name)) num_bots=len(DjangoTelegramBot.__used_tokens) if self.mode == POLLING_MODE and num_bots>0: logger.info('Please manually start polling update for {0} bot{1}. Run command{1}:'.format(num_bots, 's' if num_bots>1 else '')) for token in DjangoTelegramBot.__used_tokens: updater = DjangoTelegramBot.get_updater(bot_id=token) logger.info('python manage.py botpolling --username={}'.format(updater.bot.username))
class DjangoTelegramBot(AppConfig): @classproperty def dispatcher(cls): pass @classproperty def updater(cls): pass @classmethod def get_dispatcher(cls, bot_id=None, safe=True): pass @classmethod def getDispatcher(cls, bot_id=None, safe=True): pass @classmethod def get_bot(cls, bot_id=None, safe=True): pass @classmethod def getBot(cls, bot_id=None, safe=True): pass @classmethod def get_updater(cls, bot_id=None, safe=True): pass @classmethod def getUpdater(cls, id=None, safe=True): pass def ready(self): pass def module_imported(module_name, method_name, execute): pass
19
0
23
2
20
0
5
0.01
1
3
1
0
3
1
9
9
243
37
203
59
184
3
176
49
165
29
1
5
54
140,501
JungDev/django-telegrambot
JungDev_django-telegrambot/django_telegrambot/apps.py
django_telegrambot.apps.classproperty
class classproperty(property): def __get__(self, obj, objtype=None): return super(classproperty, self).__get__(objtype) def __set__(self, obj, value): super(classproperty, self).__set__(type(obj), value) def __delete__(self, obj): super(classproperty, self).__delete__(type(obj))
class classproperty(property): def __get__(self, obj, objtype=None): pass def __set__(self, obj, value): pass def __delete__(self, obj): pass
4
0
2
0
2
0
1
0
1
2
0
0
3
0
3
11
7
0
7
4
3
0
7
4
3
1
2
0
3
140,502
JustinLovinger/optimal
JustinLovinger_optimal/optimal/algorithms/pbil.py
optimal.algorithms.pbil.PBIL
class PBIL(StandardOptimizer): """Population-based incremental learning (PBIL) algorithm. Args: solution_size: Number of bits in every solution. population_size: Number of solutions in every iteration. adjust_rate: Rate at which probability vector will move towards best solution, every iteration. mutation_chance: Chance for any given probability to mutate, every iteration. Defaults to 1 / solution_size. mutation_adjust_rate: Rate at which a probability will move towards a random probability, if it mutates. """ def __init__(self, solution_size, population_size=20, adjust_rate=0.1, mutation_chance=None, mutation_adjust_rate=0.05): super(PBIL, self).__init__(solution_size, population_size) if mutation_chance is None: mutation_chance = 1.0 / solution_size # PBIL hyperparameters self._adjust_rate = adjust_rate self._mutation_chance = mutation_chance self._mutation_adjust_rate = mutation_adjust_rate self._hyperparameters['_adjust_rate'] = { 'type': 'float', 'min': 0.0, 'max': 1.0 } self._hyperparameters['_mutation_chance'] = { 'type': 'float', 'min': 0.0, 'max': 1.0 } self._hyperparameters['_mutation_adjust_rate'] = { 'type': 'float', 'min': 0.0, 'max': 1.0 } # PBIL parameters self._probability_vec = None # Initialize in initialize function def initialize(self): """Initialize algorithm parameters before each optimization run. This method is optional, but useful for some algorithms """ self._probability_vec = 0.5 * numpy.ones(self._solution_size) def initial_population(self): """Make the initial population before each optimization run. Returns: list; a list of solutions. """ return [ _sample(self._probability_vec) for _ in range(self._population_size) ] def next_population(self, population, fitnesses): """Make a new population after each optimization iteration. Args: population: The population current population of solutions. fitnesses: The fitness associated with each solution in the population Returns: list; a list of solutions. """ # Update probability vector self._probability_vec = _adjust_probability_vec_best( population, fitnesses, self._probability_vec, self._adjust_rate) # Mutate probability vector _mutate_probability_vec(self._probability_vec, self._mutation_chance, self._mutation_adjust_rate) # Return new samples return [ _sample(self._probability_vec) for _ in range(self._population_size) ]
class PBIL(StandardOptimizer): '''Population-based incremental learning (PBIL) algorithm. Args: solution_size: Number of bits in every solution. population_size: Number of solutions in every iteration. adjust_rate: Rate at which probability vector will move towards best solution, every iteration. mutation_chance: Chance for any given probability to mutate, every iteration. Defaults to 1 / solution_size. mutation_adjust_rate: Rate at which a probability will move towards a random probability, if it mutates. ''' def __init__(self, solution_size, population_size=20, adjust_rate=0.1, mutation_chance=None, mutation_adjust_rate=0.05): pass def initialize(self): '''Initialize algorithm parameters before each optimization run. This method is optional, but useful for some algorithms ''' pass def initial_population(self): '''Make the initial population before each optimization run. Returns: list; a list of solutions. ''' pass def next_population(self, population, fitnesses): '''Make a new population after each optimization iteration. Args: population: The population current population of solutions. fitnesses: The fitness associated with each solution in the population Returns: list; a list of solutions. ''' pass
5
4
18
2
11
5
1
0.71
1
2
0
0
4
4
4
20
89
13
45
16
35
32
20
9
15
2
3
1
5
140,503
JustinLovinger/optimal
JustinLovinger_optimal/optimal/algorithms/gsa.py
optimal.algorithms.gsa.GSA
class GSA(optimize.StandardOptimizer): """Gravitational Search Algorithm Perform gravitational search algorithm optimization with a given fitness function. """ def __init__(self, solution_size, lower_bounds, upper_bounds, population_size=20, grav_initial=100.0, grav_reduction_rate=20.0): """Create an object that optimizes a given fitness function with GSA. Args: solution_size: The number of real values in each solution. lower_bounds: list, each value is a lower bound for the corresponding component of the solution. upper_bounds: list, each value is a upper bound for the corresponding component of the solution. population_size: The number of potential solutions in every generation grav_initial: Initial value for grav parameter (0 - 1) grav_reduction_rate: Rate that grav parameter decreases over time (0 - 1) """ super(GSA, self).__init__(solution_size, population_size) # set parameters for users problem self._lower_bounds = numpy.array(lower_bounds) self._upper_bounds = numpy.array(upper_bounds) # GSA variables self._grav_initial = grav_initial # G_i in GSA paper self._grav_reduction_rate = grav_reduction_rate self._velocity_matrix = None self.initialize() # Hyperparameter definitions self._hyperparameters['_grav_initial'] = { 'type': 'float', 'min': 1e-10, 'max': 200.0 } self._hyperparameters['_grav_reduction_rate'] = { 'type': 'float', 'min': 1e-10, 'max': 40.0 } def initialize(self): # Initialize GSA variables self._velocity_matrix = numpy.zeros((self._population_size, self._solution_size)) def initial_population(self): return _initial_gsa_population(self._population_size, self._solution_size, self._lower_bounds, self._upper_bounds) def next_population(self, population, fitnesses): new_pop, self._velocity_matrix = _new_population_gsa( population, fitnesses, self._velocity_matrix, self._lower_bounds, self._upper_bounds, self._grav_initial, self._grav_reduction_rate, self.iteration, self._max_iterations) return new_pop
class GSA(optimize.StandardOptimizer): '''Gravitational Search Algorithm Perform gravitational search algorithm optimization with a given fitness function. ''' def __init__(self, solution_size, lower_bounds, upper_bounds, population_size=20, grav_initial=100.0, grav_reduction_rate=20.0): '''Create an object that optimizes a given fitness function with GSA. Args: solution_size: The number of real values in each solution. lower_bounds: list, each value is a lower bound for the corresponding component of the solution. upper_bounds: list, each value is a upper bound for the corresponding component of the solution. population_size: The number of potential solutions in every generation grav_initial: Initial value for grav parameter (0 - 1) grav_reduction_rate: Rate that grav parameter decreases over time (0 - 1) ''' pass def initialize(self): pass def initial_population(self): pass def next_population(self, population, fitnesses): pass
5
2
14
1
9
4
1
0.5
1
1
0
0
4
5
4
20
65
9
38
17
27
19
18
11
13
1
3
0
4
140,504
JustinLovinger/optimal
JustinLovinger_optimal/optimal/algorithms/crossentropy.py
optimal.algorithms.crossentropy.CrossEntropy
class CrossEntropy(optimize.StandardOptimizer): """Cross entropy optimization.""" def __init__(self, solution_size, population_size=20, pdfs=None, quantile=0.9): super(CrossEntropy, self).__init__(solution_size, population_size) # Cross entropy variables if pdfs: self.pdfs = pdfs else: # Create a default set of pdfs self.pdfs = _random_pdfs(solution_size) self.pdf = None # Values initialize in initialize function # Quantile is easier to use as an index offset (from max) # Higher the quantile, the smaller this offset # Setter will automatically set this offset self.__quantile = None self.__quantile_offset = None self._quantile = quantile # Meta optimize parameters self._hyperparameters['_quantile'] = { 'type': 'float', 'min': 0.0, 'max': 1.0 } def initialize(self): # Start with a random pdf self.pdf = random.choice(self.pdfs) def initial_population(self): # Initial population is a uniform random sample return _sample(self.pdf, self._population_size) def next_population(self, population, fitnesses): # Update pdf, then sample new population self.pdf = _update_pdf(population, fitnesses, self.pdfs, self.__quantile_offset) # New population is randomly sampled, independent of old population return _sample(self.pdf, self._population_size) # Setters and getters for quantile, so quantile_offset is automatically set @property def _quantile(self): return self.__quantile @_quantile.setter def _quantile(self, value): self.__quantile = value self.__quantile_offset = _get_quantile_offset(self._population_size, value)
class CrossEntropy(optimize.StandardOptimizer): '''Cross entropy optimization.''' def __init__(self, solution_size, population_size=20, pdfs=None, quantile=0.9): pass def initialize(self): pass def initial_population(self): pass def next_population(self, population, fitnesses): pass @property def _quantile(self): pass @_quantile.setter def _quantile(self): pass
9
1
8
1
6
2
1
0.36
1
1
0
0
6
4
6
22
58
10
36
17
23
13
23
11
16
2
3
1
7
140,505
JustinLovinger/optimal
JustinLovinger_optimal/optimal/algorithms/baseline.py
optimal.algorithms.baseline.RandomReal
class RandomReal(_RandomOptimizer): """Optimizer generating random lists of real numbers.""" def __init__(self, solution_size, lower_bounds, upper_bounds, population_size=20): """Create an object that optimizes a given fitness function with random numbers. Args: solution_size: The number of bits in every solution. lower_bounds: list, each value is a lower bound for the corresponding component of the solution. upper_bounds: list, each value is a upper bound for the corresponding component of the solution. population_size: The number of solutions in every iteration. """ super(RandomReal, self).__init__(solution_size, population_size) # Set parameters for users problem self._lower_bounds = lower_bounds self._upper_bounds = upper_bounds def _generate_solution(self): """Return a single random solution.""" return common.random_real_solution( self._solution_size, self._lower_bounds, self._upper_bounds)
class RandomReal(_RandomOptimizer): '''Optimizer generating random lists of real numbers.''' def __init__(self, solution_size, lower_bounds, upper_bounds, population_size=20): '''Create an object that optimizes a given fitness function with random numbers. Args: solution_size: The number of bits in every solution. lower_bounds: list, each value is a lower bound for the corresponding component of the solution. upper_bounds: list, each value is a upper bound for the corresponding component of the solution. population_size: The number of solutions in every iteration. ''' pass def _generate_solution(self): '''Return a single random solution.''' pass
3
3
12
1
6
6
1
1
1
1
0
0
2
2
2
22
28
4
12
9
5
12
7
5
4
1
4
0
2
140,506
JustinLovinger/optimal
JustinLovinger_optimal/optimal/algorithms/baseline.py
optimal.algorithms.baseline.RandomBinary
class RandomBinary(_RandomOptimizer): """Optimizer generating random bit strings.""" def _generate_solution(self): """Return a single random solution.""" return common.random_binary_solution(self._solution_size)
class RandomBinary(_RandomOptimizer): '''Optimizer generating random bit strings.''' def _generate_solution(self): '''Return a single random solution.''' pass
2
2
3
0
2
1
1
0.67
1
0
0
0
1
0
1
21
6
1
3
2
1
2
3
2
1
1
4
0
1
140,507
JustinLovinger/optimal
JustinLovinger_optimal/optimal/algorithms/baseline.py
optimal.algorithms.baseline.ExhaustiveBinary
class ExhaustiveBinary(optimize.StandardOptimizer): """Optimizer that generates every bit string, in ascending order. NOTE: max_iterations * population_size must be large enough to generate all solutions for an exhaustive search. """ def __init__(self, solution_size, population_size=20): """Create an object that optimizes a given fitness function. Args: solution_size: The number of bits in every solution. population_size: The number of solutions in every iteration. """ super(ExhaustiveBinary, self).__init__(solution_size, population_size) self._next_int = 0 def initialize(self): """Initialize algorithm parameters before each optimization run. This method is optional, but useful for some algorithms """ self._next_int = 0 def initial_population(self): """Make the initial population before each optimization run. Returns: list; a list of solutions. """ return [self._next_solution() for _ in range(self._population_size)] def next_population(self, population, fitnesses): """Make a new population after each optimization iteration. Args: population: The population current population of solutions. fitnesses: The fitness associated with each solution in the population Returns: list; a list of solutions. """ return [self._next_solution() for _ in range(self._population_size)] def _next_solution(self): solution = _int_to_binary(self._next_int, size=self._solution_size) self._next_int += 1 return solution
class ExhaustiveBinary(optimize.StandardOptimizer): '''Optimizer that generates every bit string, in ascending order. NOTE: max_iterations * population_size must be large enough to generate all solutions for an exhaustive search. ''' def __init__(self, solution_size, population_size=20): '''Create an object that optimizes a given fitness function. Args: solution_size: The number of bits in every solution. population_size: The number of solutions in every iteration. ''' pass def initialize(self): '''Initialize algorithm parameters before each optimization run. This method is optional, but useful for some algorithms ''' pass def initial_population(self): '''Make the initial population before each optimization run. Returns: list; a list of solutions. ''' pass def next_population(self, population, fitnesses): '''Make a new population after each optimization iteration. Args: population: The population current population of solutions. fitnesses: The fitness associated with each solution in the population Returns: list; a list of solutions. ''' pass def _next_solution(self): pass
6
5
8
1
3
4
1
1.44
1
2
0
0
5
1
5
21
48
9
16
12
8
23
14
8
8
1
3
0
5
140,508
JustinLovinger/optimal
JustinLovinger_optimal/optimal/tests/test_benchmark.py
test_benchmark.BadOptimizer
class BadOptimizer(optimize.StandardOptimizer): def initial_population(self): return [[0] * self._solution_size for _ in range(self._population_size)] def next_population(self, *args): return self.initial_population()
class BadOptimizer(optimize.StandardOptimizer): def initial_population(self): pass def next_population(self, *args): pass
3
0
3
0
3
0
1
0
1
1
0
0
2
0
2
18
7
1
6
4
3
0
5
3
2
1
3
0
2
140,509
JustusW/harparser
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/JustusW_harparser/test/log.py
test.log.TestLog.test_json_scaffold_on_exclusive_params.derived
class derived(HAR.log): pass
class derived(HAR.log): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
2
0
2
1
1
0
2
1
1
0
1
0
0
140,510
JustusW/harparser
JustusW_harparser/test/log.py
test.log.TestLog
class TestLog(unittest.TestCase): def test_json_scaffold_on_derived_classes(self): class derived(HAR.log): pass tmp = derived({ "version":"1.2", "creator":{"name":"MITMPROXY HARExtractor","version":"0.1","comment":""}, "pages":[], "entries":[] }) assert tmp.json().startswith('{"log":') def test_json_scaffold_on_exclusive_params(self): class derived(HAR.log): pass tmp = derived({ "version": "1.2", "creator": { "name": "WebInspector", "version": "537.1" }, "pages": [ { "startedDateTime": "2012-08-28T05:14:24.803Z", "id": "page_1", "title": "http://www.igvita.com/", "pageTimings": { "onContentLoad": 299, "onLoad": 301 } } ], "entries": [ { "startedDateTime": "2012-08-28T05:14:24.803Z", "time": 121, "request": { "method": "POST", "url": "http://www.igvita.com/", "httpVersion": "HTTP/1.1", "postData": { "comment": "hello world", "mimeType": "multipart/form-data", "text": "foo=bar", }, "headers": [ { "name": "Accept-Encoding", "value": "gzip,deflate,sdch" }, { "name": "Accept-Language", "value": "en-US,en;q=0.8" }, { "name": "Connection", "value": "keep-alive" }, { "name": "Accept-Charset", "value": "ISO-8859-1,utf-8;q=0.7,*;q=0.3" }, { "name": "Host", "value": "www.igvita.com" }, { "name": "User-Agent", "value": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_4) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.82 Safari/537.1" }, { "name": "Accept", "value": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8" }, { "name": "Cache-Control", "value": "max-age=0" } ], "queryString": [], "cookies": [ ], "headersSize": 678, "bodySize": 0 }, "response": { "status": 200, "statusText": "OK", "httpVersion": "HTTP/1.1", "headers": [ { "name": "Date", "value": "Tue, 28 Aug 2012 05:14:24 GMT" }, { "name": "Via", "value": "HTTP/1.1 GWA" }, { "name": "Transfer-Encoding", "value": "chunked" }, { "name": "Content-Encoding", "value": "gzip" }, { "name": "X-XSS-Protection", "value": "1; mode=block" }, { "name": "X-UA-Compatible", "value": "IE=Edge,chrome=1" }, { "name": "X-Page-Speed", "value": "50_1_cn" }, { "name": "Server", "value": "nginx/1.0.11" }, { "name": "Vary", "value": "Accept-Encoding" }, { "name": "Content-Type", "value": "text/html; charset=utf-8" }, { "name": "Cache-Control", "value": "max-age=0, no-cache" }, { "name": "Expires", "value": "Tue, 28 Aug 2012 05:14:24 GMT" } ], "cookies": [], "content": { "size": 9521, "mimeType": "text/html", "compression": 5896 }, "redirectURL": "", "headersSize": 379, "bodySize": 3625 }, "cache": {}, "timings": { "blocked": 0, "dns": -1, "connect": -1, "send": 1, "wait": 112, "receive": 6, "ssl": -1 }, "pageref": "page_1" }, { "startedDateTime": "2012-08-28T05:14:25.011Z", "time": 10, "request": { "method": "GET", "url": "http://fonts.googleapis.com/css?family=Open+Sans:400,600", "httpVersion": "HTTP/1.1", "headers": [], "queryString": [ { "name": "family", "value": "Open+Sans:400,600" } ], "cookies": [], "headersSize": 71, "bodySize": 0 }, "response": { "status": 200, "statusText": "OK", "httpVersion": "HTTP/1.1", "headers": [], "cookies": [], "content": { "size": 542, "mimeType": "text/css" }, "redirectURL": "", "headersSize": 17, "bodySize": 0 }, "cache": {}, "timings": { "blocked": 0, "dns": -1, "connect": -1, "send": -1, "wait": -1, "receive": 2, "ssl": -1 }, "pageref": "page_1" }, { "startedDateTime": "2012-08-28T05:14:25.017Z", "time": 31, "request": { "method": "GET", "url": "http://1-ps.googleusercontent.com/h/www.igvita.com/css/style.css.pagespeed.ce.LzjUDNB25e.css", "httpVersion": "HTTP/1.1", "headers": [ { "name": "Accept-Encoding", "value": "gzip,deflate,sdch" }, { "name": "Accept-Language", "value": "en-US,en;q=0.8" }, { "name": "Connection", "value": "keep-alive" }, { "name": "If-Modified-Since", "value": "Mon, 27 Aug 2012 15:28:34 GMT" }, { "name": "Accept-Charset", "value": "ISO-8859-1,utf-8;q=0.7,*;q=0.3" }, { "name": "Host", "value": "1-ps.googleusercontent.com" }, { "name": "User-Agent", "value": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_4) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.82 Safari/537.1" }, { "name": "Accept", "value": "text/css,*/*;q=0.1" }, { "name": "Cache-Control", "value": "max-age=0" }, { "name": "If-None-Match", "value": "W/0" }, { "name": "Referer", "value": "http://www.igvita.com/" } ], "queryString": [], "cookies": [], "headersSize": 539, "bodySize": 0 }, "response": { "status": 304, "statusText": "Not Modified", "httpVersion": "HTTP/1.1", "headers": [ { "name": "Date", "value": "Mon, 27 Aug 2012 06:01:49 GMT" }, { "name": "Age", "value": "83556" }, { "name": "Server", "value": "GFE/2.0" }, { "name": "ETag", "value": "W/0" }, { "name": "Expires", "value": "Tue, 27 Aug 2013 06:01:49 GMT" } ], "cookies": [], "content": { "size": 14679, "mimeType": "text/css" }, "redirectURL": "", "headersSize": 146, "bodySize": 0 }, "cache": {}, "timings": { "blocked": 0, "dns": -1, "connect": -1, "send": 1, "wait": 24, "receive": 2, "ssl": -1 }, "pageref": "page_1" }, { "startedDateTime": "2012-08-28T05:14:25.021Z", "time": 30, "request": { "method": "GET", "url": "http://1-ps.googleusercontent.com/h/www.igvita.com/js/libs/modernizr.84728.js.pagespeed.jm._DgXLhVY42.js", "httpVersion": "HTTP/1.1", "headers": [ { "name": "Accept-Encoding", "value": "gzip,deflate,sdch" }, { "name": "Accept-Language", "value": "en-US,en;q=0.8" }, { "name": "Connection", "value": "keep-alive" }, { "name": "If-Modified-Since", "value": "Sat, 25 Aug 2012 14:30:37 GMT" }, { "name": "Accept-Charset", "value": "ISO-8859-1,utf-8;q=0.7,*;q=0.3" }, { "name": "Host", "value": "1-ps.googleusercontent.com" }, { "name": "User-Agent", "value": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_4) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.82 Safari/537.1" }, { "name": "Accept", "value": "*/*" }, { "name": "Cache-Control", "value": "max-age=0" }, { "name": "If-None-Match", "value": "W/0" }, { "name": "Referer", "value": "http://www.igvita.com/" } ], "queryString": [], "cookies": [], "headersSize": 536, "bodySize": 0 }, "response": { "status": 304, "statusText": "Not Modified", "httpVersion": "HTTP/1.1", "headers": [ { "name": "Date", "value": "Sat, 25 Aug 2012 14:30:37 GMT" }, { "name": "Age", "value": "225828" }, { "name": "Server", "value": "GFE/2.0" }, { "name": "ETag", "value": "W/0" }, { "name": "Expires", "value": "Sun, 25 Aug 2013 14:30:37 GMT" } ], "cookies": [], "content": { "size": 11831, "mimeType": "text/javascript" }, "redirectURL": "", "headersSize": 147, "bodySize": 0 }, "cache": {}, "timings": { "blocked": 0, "dns": -1, "connect": 0, "send": 1, "wait": 27, "receive": 1, "ssl": -1 }, "pageref": "page_1" }, { "startedDateTime": "2012-08-28T05:14:25.103Z", "time": 0, "request": { "method": "GET", "url": "http://www.google-analytics.com/ga.js", "httpVersion": "HTTP/1.1", "headers": [], "queryString": [], "cookies": [], "headersSize": 52, "bodySize": 0 }, "response": { "status": 200, "statusText": "OK", "httpVersion": "HTTP/1.1", "headers": [ { "name": "Date", "value": "Mon, 27 Aug 2012 21:57:00 GMT" }, { "name": "Content-Encoding", "value": "gzip" }, { "name": "X-Content-Type-Options", "value": "nosniff, nosniff" }, { "name": "Age", "value": "23052" }, { "name": "Last-Modified", "value": "Thu, 16 Aug 2012 07:05:05 GMT" }, { "name": "Server", "value": "GFE/2.0" }, { "name": "Vary", "value": "Accept-Encoding" }, { "name": "Content-Type", "value": "text/javascript" }, { "name": "Expires", "value": "Tue, 28 Aug 2012 09:57:00 GMT" }, { "name": "Cache-Control", "value": "max-age=43200, public" }, { "name": "Content-Length", "value": "14804" } ], "cookies": [], "content": { "size": 36893, "mimeType": "text/javascript" }, "redirectURL": "", "headersSize": 17, "bodySize": 0 }, "cache": {}, "timings": { "blocked": 0, "dns": -1, "connect": -1, "send": -1, "wait": -1, "receive": 0, "ssl": -1 }, "pageref": "page_1" }, { "startedDateTime": "2012-08-28T05:14:25.123Z", "time": 91, "request": { "method": "GET", "url": "http://1-ps.googleusercontent.com/beacon?org=50_1_cn&ets=load:93&ifr=0&hft=32&url=http%3A%2F%2Fwww.igvita.com%2F", "httpVersion": "HTTP/1.1", "headers": [ { "name": "Accept-Encoding", "value": "gzip,deflate,sdch" }, { "name": "Accept-Language", "value": "en-US,en;q=0.8" }, { "name": "Connection", "value": "keep-alive" }, { "name": "Accept-Charset", "value": "ISO-8859-1,utf-8;q=0.7,*;q=0.3" }, { "name": "Host", "value": "1-ps.googleusercontent.com" }, { "name": "User-Agent", "value": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_4) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.82 Safari/537.1" }, { "name": "Accept", "value": "*/*" }, { "name": "Referer", "value": "http://www.igvita.com/" } ], "queryString": [ { "name": "org", "value": "50_1_cn" }, { "name": "ets", "value": "load:93" }, { "name": "ifr", "value": "0" }, { "name": "hft", "value": "32" }, { "name": "url", "value": "http%3A%2F%2Fwww.igvita.com%2F" } ], "cookies": [], "headersSize": 448, "bodySize": 0 }, "response": { "status": 204, "statusText": "No Content", "httpVersion": "HTTP/1.1", "headers": [ { "name": "Date", "value": "Tue, 28 Aug 2012 05:14:25 GMT" }, { "name": "Content-Length", "value": "0" }, { "name": "X-XSS-Protection", "value": "1; mode=block" }, { "name": "Server", "value": "PagespeedRewriteProxy 0.1" }, { "name": "Content-Type", "value": "text/plain" }, { "name": "Cache-Control", "value": "no-cache" } ], "cookies": [], "content": { "size": 0, "mimeType": "text/plain", "compression": 0 }, "redirectURL": "", "headersSize": 202, "bodySize": 0 }, "cache": {}, "timings": { "blocked": 0, "dns": -1, "connect": -1, "send": 0, "wait": 70, "receive": 7, "ssl": -1 }, "pageref": "page_1" } ] } ) assert tmp.json().startswith('{"log":')
class TestLog(unittest.TestCase): def test_json_scaffold_on_derived_classes(self): pass class derived(HAR.log): def test_json_scaffold_on_exclusive_params(self): pass class derived(HAR.log):
5
0
312
2
310
0
1
0
1
2
2
0
2
0
2
74
627
6
621
7
616
0
11
7
6
1
2
0
2
140,511
JustusW/harparser
JustusW_harparser/harparser.py
harparser._HAR
class _HAR(MutableMapping, object): """ HAR implementation as per specification version 1.2 () This class maps the specification contained in __map__ to dynamic subclasses stored in __classes__. It then exposes all of this by implementing MutableMapping, the generated subclasses being its keys. """ __map__ = {"log": {"__required__": {"version": str, "creator": {}, "entries": [], }, "__optional__": {"browser": {}, "pages": [], "comment": str, }}, "creator": {"__required__": {"name": str, "version": str, }, "__optional__": {"comment": str}, }, "browser": {"__required__": {"name": str, "version": str, }, "__optional__": {"comment": str}, }, "pages": {"__required__": {"startedDateTime": str, "id": str, "title": str, }, "__optional__": {"pageTimings": {}, "comment": str}, }, "pageTimings": {"__required__": {}, "__optional__": {"onContentLoad": int, "onLoad": int, "comment": str}, }, "entries": {"__required__": {"startedDateTime": str, "time": int, "request": {}, "response": {}, "cache": {}, "timings": {}, }, "__optional__": {"pageref": str, "serverIPAddress": str, "connection": str, "comment": str}, }, "request": {"__required__": {"method": str, "url": str, "httpVersion": str, "cookies": [], "headers": [], "queryString": [], "headersSize": int, "bodySize": int, }, "__optional__": {"postData": {}, "comment": str}, }, "response": {"__required__": {"status": int, "statusText": str, "httpVersion": str, "cookies": [], "headers": [], "content": {}, "redirectURL": str, "headersSize": int, "bodySize": int, }, "__optional__": {"comment": str}, }, "cookies": {"__required__": {"name": str, "value": str, }, "__optional__": {"path": str, "domain": str, "expires": str, "httpOnly": bool, "secure": bool, "comment": str}, }, "headers": {"__required__": {"name": str, "value": str, }, "__optional__": {"comment": str}, }, "queryString": {"__required__": {"name": str, "value": str, }, "__optional__": {"comment": str}, }, "postData": {"__required__": {"mimeType": str, }, "__required_exclusives__": {"params": [], "text": str, }, "__optional__": {"comment": str}, }, "params": {"__required__": {"name": str, }, "__optional__": {"value": str, "fileName": str, "contentType": str, "comment": str}, }, "content": {"__required__": {"size": int, "mimeType": str, }, "__optional__": {"compression": int, "text": str, "comment": str}, }, "cache": {"__required__": {}, "__optional__": {"beforeRequest": {}, "afterRequest": {}, "comment": str}, }, "beforeRequest": {"__required__": {"lastAccess": str, "eTag": str, "hitCount": int, }, "__optional__": {"expires": str, "comment": str, }, }, "afterRequest": {"__required__": {"lastAccess": str, "eTag": str, "hitCount": int, }, "__optional__": {"expires": str, "comment": str, }, }, "timings": {"__required__": {"send": int, "wait": int, "receive": int, }, "__optional__": {"blocked": int, "dns": int, "connect": int, "ssl": int, "comment": str, }, }} def __init__(self): """ Exposes the classes mapped from __map__ extending HAREncodable as a MutableMapping, dict like object. """ self.__classes__ = dict([(name, type(name, (HAREncodable, ), self.__map__[name])) for name in self.__map__]) def __getattr__(self, item): """ Exposes __getitem__ keys as attributes. """ return self[item] def __getitem__(self, *args, **kwargs): """ Directly exposes self.__classes__.__getitem__ """ return self.__classes__.__getitem__(*args, **kwargs) def __setitem__(self, *args, **kwargs): """ Directly exposes self.__classes__.__setitem__ """ return self.__classes__.__setitem__(*args, **kwargs) def __delitem__(self, *args, **kwargs): """ Directly exposes self.__classes__.__delitem__ """ return self.__classes__.__delitem__(*args, **kwargs) def __iter__(self): """ Directly exposes self.__classes__.__iter__ """ return self.__classes__.__iter__() def __len__(self): """ Directly exposes self.__classes__.__len__ """ return self.__classes__.__len__()
class _HAR(MutableMapping, object): ''' HAR implementation as per specification version 1.2 () This class maps the specification contained in __map__ to dynamic subclasses stored in __classes__. It then exposes all of this by implementing MutableMapping, the generated subclasses being its keys. ''' def __init__(self): ''' Exposes the classes mapped from __map__ extending HAREncodable as a MutableMapping, dict like object. ''' pass def __getattr__(self, item): ''' Exposes __getitem__ keys as attributes. ''' pass def __getitem__(self, *args, **kwargs): ''' Directly exposes self.__classes__.__getitem__ ''' pass def __setitem__(self, *args, **kwargs): ''' Directly exposes self.__classes__.__setitem__ ''' pass def __delitem__(self, *args, **kwargs): ''' Directly exposes self.__classes__.__delitem__ ''' pass def __iter__(self): ''' Directly exposes self.__classes__.__iter__ ''' pass def __len__(self): ''' Directly exposes self.__classes__.__len__ ''' pass
8
8
5
0
2
3
1
0.23
2
3
1
0
7
1
7
7
152
7
118
10
110
27
16
10
8
1
1
0
7
140,512
JustusW/harparser
JustusW_harparser/harparser.py
harparser.HAREncodable
class HAREncodable(MutableMapping): """ Base class that allows for recursive HAR structures using HAR as map. """ __required__ = {} __optional__ = {} def __init__(self, *args, **kwargs): """ Initialize the private dict that is used to actually store the information. Fills it with the content given in args/kwargs then checks against __required__ for missing mandatory fields. Important: If no parameters are given no checks will be done for convenience. """ self.__dict__ = {} if len(args) > 0: kwargs = args[0] elif len(kwargs) == 0: return for key, value in kwargs.items(): self[key] = value for key in self.__required__: self[key] # Rather clunky exclusives check. try: self.__required_exclusives__ except AttributeError: return found = False for key in self.__required_exclusives__: if found and key in self: raise Exception("Mutually exclusive key found. %r in %r (Violates: %r)" % (key, self, self.__required_exclusives__)) if not found and key in self: found = True if not found: for key in self.__required_exclusives__: self[key] def __setitem__(self, key, value): """ Exposes self.__dict__.__setitem__ with typecasting. Typecast any item to the correct type based on key name and position as implicitly provided by __required__ and __optional__. If a key is used that is not in the specification it will be added without type casting! """ item_type = self.__required__.get(key, self.__optional__.get(key, getattr(self, "__required_exclusives__", {}).get(key, None))) if type(item_type) is type: value = item_type(value) elif type(item_type) is list: value = [HAR[key](v) for v in value] elif type(item_type) is dict: value = HAR[key](value) # If it is None or not in the handled cases we would use pass anyway. return self.__dict__.__setitem__(key, value) def __getitem__(self, *args, **kwargs): """ Directly exposes self.__dict__.__getitem__ """ return self.__dict__.__getitem__(*args, **kwargs) def __delitem__(self, *args, **kwargs): """ Directly exposes self.__dict__.__delitem__ """ return self.__dict__.__delitem__(*args, **kwargs) def __len__(self): """ Directly exposes self.__dict__.__len__ """ return self.__dict__.__len__() def __iter__(self): """ Directly exposes self.__dict__.__iter__ """ return self.__dict__.__iter__() def json(self, json_string=None): """ Convenience method allowing easy dumping to and loading from json. """ if json_string is not None: return self.__init__(loads(json_string)) dump = self if isinstance(self, HAR.log): dump = {"log": dump} return dumps(dump, default=lambda x: dict(x)) def compress(self): """ Convenience method for compressing the json output. """ return compress(self.json()) def decompress(self, compressed_json_string): """ Convenience method for decompressing json input. """ return self.json(json_string=decompress(compressed_json_string))
class HAREncodable(MutableMapping): ''' Base class that allows for recursive HAR structures using HAR as map. ''' def __init__(self, *args, **kwargs): ''' Initialize the private dict that is used to actually store the information. Fills it with the content given in args/kwargs then checks against __required__ for missing mandatory fields. Important: If no parameters are given no checks will be done for convenience. ''' pass def __setitem__(self, key, value): ''' Exposes self.__dict__.__setitem__ with typecasting. Typecast any item to the correct type based on key name and position as implicitly provided by __required__ and __optional__. If a key is used that is not in the specification it will be added without type casting! ''' pass def __getitem__(self, *args, **kwargs): ''' Directly exposes self.__dict__.__getitem__ ''' pass def __delitem__(self, *args, **kwargs): ''' Directly exposes self.__dict__.__delitem__ ''' pass def __len__(self): ''' Directly exposes self.__dict__.__len__ ''' pass def __iter__(self): ''' Directly exposes self.__dict__.__iter__ ''' pass def json(self, json_string=None): ''' Convenience method allowing easy dumping to and loading from json. ''' pass def compress(self): ''' Convenience method for compressing the json output. ''' pass def decompress(self, compressed_json_string): ''' Convenience method for decompressing json input. ''' pass
10
10
11
1
6
4
3
0.7
1
5
0
0
9
1
9
9
110
18
54
17
44
38
51
17
41
11
1
2
24
140,513
KE-works/pykechain
KE-works_pykechain/pykechain/enums.py
pykechain.enums.KEChainPages
class KEChainPages(Enum): """ URL names of built-in KE-chain pages. :cvar DETAIL: "detail" :cvar FORMS: "forms" :cvar TASKS: "activities" :cvar WORK_BREAKDOWN: "activitytree" :cvar CATALOG_FORMS: "catalogforms" :cvar CONTEXTS: "contexts" :cvar WORKFLOWS: "workflows" :cvar DATA_MODEL: "productmodel" :cvar EXPLORER: "product" :cvar SERVICES: "scripts" """ DETAIL = "detail" FORMS = "forms" TASKS = "activities" WORK_BREAKDOWN = "activitytree" CATALOG_FORMS = "catalogforms" CONTEXTS = "contexts" WORKFLOWS = "workflows" DATA_MODEL = "productmodel" EXPLORER = "product" SERVICES = "scripts" CATALOG_WBS = "catalogtree" APP_WBS = "apptree"
class KEChainPages(Enum): ''' URL names of built-in KE-chain pages. :cvar DETAIL: "detail" :cvar FORMS: "forms" :cvar TASKS: "activities" :cvar WORK_BREAKDOWN: "activitytree" :cvar CATALOG_FORMS: "catalogforms" :cvar CONTEXTS: "contexts" :cvar WORKFLOWS: "workflows" :cvar DATA_MODEL: "productmodel" :cvar EXPLORER: "product" :cvar SERVICES: "scripts" ''' pass
1
1
0
0
0
0
0
1
1
0
0
0
0
0
0
2
28
2
13
13
12
13
13
13
12
0
1
0
0
140,514
KE-works/pykechain
KE-works_pykechain/pykechain/enums.py
pykechain.enums.ServiceEnvironmentVersion
class ServiceEnvironmentVersion(Enum): """The acceptable versions of python where services run on. :cvar PYTHON_3_6: Service execution environment is a python 3.6 container (unsupported) :cvar PYTHON_3_7: Service execution environment is a python 3.7 container (unsupported) :cvar PYTHON_3_8: Service execution environment is a python 3.8 container (unsupported) :cvar PYTHON_3_9: Service execution environment is a python 3.9 container (legacy) :cvar PYTHON_3_10: Service execution environment is a python 3.10 container (unsupported) :cvar PYTHON_3_11: Service execution environment is a python 3.11 container (unsupported) :cvar PYTHON_3_12: Service execution environment is a python 3.12 container (default) :cvar PYTHON_3_6_NOTEBOOKS: execution environment is a python 3.6 container with jupyter notebook preinstalled (unsupported) :cvar PYTHON_3_8_NOTEBOOKS: execution environment is a python 3.8 container with jupyter notebook preinstalled (unsupported) :cvar PYTHON_3_9_NOTEBOOKS: execution environment is a python 3.9 container with jupyter notebook preinstalled (unsupported) :cvar PYTHON_3_10_NOTEBOOKS: execution environment is a python 3.10 container with jupyter notebook preinstalled (unsupported) """ PYTHON_3_6 = "3.6" # unsupported PYTHON_3_7 = "3.7" # unsupported PYTHON_3_8 = "3.8" # unsupported PYTHON_3_9 = "3.9" # legacy PYTHON_3_10 = "3.10" # unsupported PYTHON_3_11 = "3.11" # unsupported PYTHON_3_12 = "3.12" # default PYTHON_3_13 = "3.13" # default PYTHON_3_6_NOTEBOOKS = "3.6_notebook" # unsupported PYTHON_3_8_NOTEBOOKS = "3.8_notebook" # unsupported PYTHON_3_9_NOTEBOOKS = "3.9_notebook" # unsupported PYTHON_3_10_NOTEBOOKS = "3.10_notebook"
class ServiceEnvironmentVersion(Enum): '''The acceptable versions of python where services run on. :cvar PYTHON_3_6: Service execution environment is a python 3.6 container (unsupported) :cvar PYTHON_3_7: Service execution environment is a python 3.7 container (unsupported) :cvar PYTHON_3_8: Service execution environment is a python 3.8 container (unsupported) :cvar PYTHON_3_9: Service execution environment is a python 3.9 container (legacy) :cvar PYTHON_3_10: Service execution environment is a python 3.10 container (unsupported) :cvar PYTHON_3_11: Service execution environment is a python 3.11 container (unsupported) :cvar PYTHON_3_12: Service execution environment is a python 3.12 container (default) :cvar PYTHON_3_6_NOTEBOOKS: execution environment is a python 3.6 container with jupyter notebook preinstalled (unsupported) :cvar PYTHON_3_8_NOTEBOOKS: execution environment is a python 3.8 container with jupyter notebook preinstalled (unsupported) :cvar PYTHON_3_9_NOTEBOOKS: execution environment is a python 3.9 container with jupyter notebook preinstalled (unsupported) :cvar PYTHON_3_10_NOTEBOOKS: execution environment is a python 3.10 container with jupyter notebook preinstalled (unsupported) '''
1
1
0
0
0
0
0
2.23
1
0
0
0
0
0
0
2
32
2
13
13
12
29
13
13
12
0
1
0
0
140,515
KE-works/pykechain
KE-works_pykechain/pykechain/enums.py
pykechain.enums.ServiceScriptUser
class ServiceScriptUser(Enum): """The acceptable usertypes under which a (trusted) service is run. :cvar KENODE_USER: Run as "kenode" user. Equivalent to a manager in a scope. :cvar TEAMMANAGER_USER: Run as "kenode_team". Equivalent to a manager in a team. (disabled until available) :cvar CONFIGURATOR_USER: Run as "kenode_configurator". Equivalent to GG:Configurator. """ KENODE_USER = "kenode" # TEAMMANAGER_USER = "kenode_team" CONFIGURATOR_USER = "kenode_configurator"
class ServiceScriptUser(Enum): '''The acceptable usertypes under which a (trusted) service is run. :cvar KENODE_USER: Run as "kenode" user. Equivalent to a manager in a scope. :cvar TEAMMANAGER_USER: Run as "kenode_team". Equivalent to a manager in a team. (disabled until available) :cvar CONFIGURATOR_USER: Run as "kenode_configurator". Equivalent to GG:Configurator. ''' pass
1
1
0
0
0
0
0
2.33
1
0
0
0
0
0
0
2
12
2
3
3
2
7
3
3
2
0
1
0
0
140,516
KE-works/pykechain
KE-works_pykechain/pykechain/enums.py
pykechain.enums.ServiceType
class ServiceType(Enum): """The file types of sim script. :cvar PYTHON_SCRIPT: service is a python script :cvar NOTEBOOK: service is a jupyter notebook """ PYTHON_SCRIPT = "PYTHON SCRIPT" NOTEBOOK = "NOTEBOOK"
class ServiceType(Enum): '''The file types of sim script. :cvar PYTHON_SCRIPT: service is a python script :cvar NOTEBOOK: service is a jupyter notebook ''' pass
1
1
0
0
0
0
0
1.33
1
0
0
0
0
0
0
2
9
2
3
3
2
4
3
3
2
0
1
0
0
140,517
KE-works/pykechain
KE-works_pykechain/pykechain/enums.py
pykechain.enums.ShowColumnTypes
class ShowColumnTypes(Enum): """The columns that can be shown in a Property grid. .. versionadded:: 2.3 :cvar UNIT: unit :cvar DESCRIPTION: description """ UNIT = "unit" DESCRIPTION = "description"
class ShowColumnTypes(Enum): '''The columns that can be shown in a Property grid. .. versionadded:: 2.3 :cvar UNIT: unit :cvar DESCRIPTION: description ''' pass
1
1
0
0
0
0
0
1.67
1
0
0
0
0
0
0
2
11
3
3
3
2
5
3
3
2
0
1
0
0
140,518
KE-works/pykechain
KE-works_pykechain/pykechain/enums.py
pykechain.enums.SidebarAccessLevelOptions
class SidebarAccessLevelOptions(Enum): """ Options for access level options for the sidebar. :cvar IS_MEMBER: "is_member" :cvar IS_LEAD_MEMBER: "is_leadmember" :cvar IS_SUPERVISOR: "is_supervisor" :cvar IS_MANAGER: "is_manager" """ IS_MEMBER = "is_member" IS_LEAD_MEMBER = "is_leadmember" IS_SUPERVISOR = "is_supervisor" IS_MANAGER = "is_manager"
class SidebarAccessLevelOptions(Enum): ''' Options for access level options for the sidebar. :cvar IS_MEMBER: "is_member" :cvar IS_LEAD_MEMBER: "is_leadmember" :cvar IS_SUPERVISOR: "is_supervisor" :cvar IS_MANAGER: "is_manager" ''' pass
1
1
0
0
0
0
0
1.4
1
0
0
2
0
0
0
2
14
2
5
5
4
7
5
5
4
0
1
0
0
140,519
KE-works/pykechain
KE-works_pykechain/pykechain/enums.py
pykechain.enums.SidebarItemAlignment
class SidebarItemAlignment(Enum): """The acceptable alignment options for sidebar button. :cvar TOP: "top" :cvar BOTTOM: "bottom" """ TOP = "top" BOTTOM = "bottom"
class SidebarItemAlignment(Enum): '''The acceptable alignment options for sidebar button. :cvar TOP: "top" :cvar BOTTOM: "bottom" ''' pass
1
1
0
0
0
0
0
1.33
1
0
0
1
0
0
0
2
9
2
3
3
2
4
3
3
2
0
1
0
0
140,520
KE-works/pykechain
KE-works_pykechain/pykechain/enums.py
pykechain.enums.SidebarType
class SidebarType(Enum): """The types that can exist as a Sidebar Item. :cvar BUTTON: a button, :cvar CARD: a card """ BUTTON = "BUTTON" CARD = "CARD"
class SidebarType(Enum): '''The types that can exist as a Sidebar Item. :cvar BUTTON: a button, :cvar CARD: a card ''' pass
1
1
0
0
0
0
0
1.33
1
0
0
0
0
0
0
2
9
2
3
3
2
4
3
3
2
0
1
0
0
140,521
KE-works/pykechain
KE-works_pykechain/pykechain/enums.py
pykechain.enums.SignatureRepresentationValues
class SignatureRepresentationValues(Enum): """ Values that can be put in the SignatureRepresentation for representing attachments as sigs. :cvar CLEAN: a clean signature representation. :cvar NAME_AND_DATE: A name and Date background to the signature field when filling in. """ CLEAN = "clean" NAME_AND_DATE = "nameAndDate"
class SignatureRepresentationValues(Enum): ''' Values that can be put in the SignatureRepresentation for representing attachments as sigs. :cvar CLEAN: a clean signature representation. :cvar NAME_AND_DATE: A name and Date background to the signature field when filling in. ''' pass
1
1
0
0
0
0
0
1.67
1
0
0
0
0
0
0
2
10
2
3
3
2
5
3
3
2
0
1
0
0
140,522
KE-works/pykechain
KE-works_pykechain/pykechain/enums.py
pykechain.enums.SortTable
class SortTable(Enum): """The acceptable sorting options for a grid/table. :cvar ASCENDING: Table is sorted in ASCENDING ORDER :cvar DESCENDING: Table is sorted in DESCENDING ORDER """ ASCENDING = "ASC" DESCENDING = "DESC"
class SortTable(Enum): '''The acceptable sorting options for a grid/table. :cvar ASCENDING: Table is sorted in ASCENDING ORDER :cvar DESCENDING: Table is sorted in DESCENDING ORDER ''' pass
1
1
0
0
0
0
0
1.33
1
0
0
0
0
0
0
2
9
2
3
3
2
4
3
3
2
0
1
0
0
140,523
KE-works/pykechain
KE-works_pykechain/pykechain/enums.py
pykechain.enums.ServiceExecutionStatus
class ServiceExecutionStatus(Enum): """The acceptable states of a running service. :cvar LOADING: Execution is in LOADING state (next RUNNING, FAILED) :cvar RUNNING: Execution is in RUNNING state (next COMPLETED, FAILED, TERMINATING) :cvar COMPLETED: Execution is in COMPLETED state :cvar FAILED: Execution is in FAILED state :cvar TERMINATING: Execution is in TERMINATING state (next TERMINATED) :cvar TERMINATED: Execution is in TERMINATED state """ LOADING = "LOADING" RUNNING = "RUNNING" COMPLETED = "COMPLETED" FAILED = "FAILED" TERMINATING = "TERMINATING" TERMINATED = "TERMINATED"
class ServiceExecutionStatus(Enum): '''The acceptable states of a running service. :cvar LOADING: Execution is in LOADING state (next RUNNING, FAILED) :cvar RUNNING: Execution is in RUNNING state (next COMPLETED, FAILED, TERMINATING) :cvar COMPLETED: Execution is in COMPLETED state :cvar FAILED: Execution is in FAILED state :cvar TERMINATING: Execution is in TERMINATING state (next TERMINATED) :cvar TERMINATED: Execution is in TERMINATED state ''' pass
1
1
0
0
0
0
0
1.14
1
0
0
0
0
0
0
2
17
2
7
7
6
8
7
7
6
0
1
0
0
140,524
KE-works/pykechain
KE-works_pykechain/pykechain/enums.py
pykechain.enums.SelectListRepresentations
class SelectListRepresentations(Enum): """ Options in which a single-select list property options are displayed. :cvar DROP_DOWN: "dropdown" :cvar CHECK_BOXES: "checkboxes" :cvar BUTTONS: "buttons" """ DROP_DOWN = "dropdown" CHECK_BOXES = "checkboxes" BUTTONS = "buttons"
class SelectListRepresentations(Enum): ''' Options in which a single-select list property options are displayed. :cvar DROP_DOWN: "dropdown" :cvar CHECK_BOXES: "checkboxes" :cvar BUTTONS: "buttons" ''' pass
1
1
0
0
0
0
0
1.5
1
0
0
0
0
0
0
2
12
2
4
4
3
6
4
4
3
0
1
0
0
140,525
KE-works/pykechain
KE-works_pykechain/pykechain/enums.py
pykechain.enums.ScopeWidgetColumnTypes
class ScopeWidgetColumnTypes(Enum): """The columns that can be shown in a Scope widget grid. .. versionadded:: 3.0 :cvar PROJECT_NAME: Name :cvar START_DATE: Start date :cvar DUE_DATE: Due date :cvar PROGRESS: Progress :cvar STATUS: Status :cvar TAGS: Tags """ PROJECT_NAME = "Name" START_DATE = "Start date" DUE_DATE = "Due date" PROGRESS = "Progress" STATUS = "Status" TAGS = "Tags"
class ScopeWidgetColumnTypes(Enum): '''The columns that can be shown in a Scope widget grid. .. versionadded:: 3.0 :cvar PROJECT_NAME: Name :cvar START_DATE: Start date :cvar DUE_DATE: Due date :cvar PROGRESS: Progress :cvar STATUS: Status :cvar TAGS: Tags ''' pass
1
1
0
0
0
0
0
1.29
1
0
0
0
0
0
0
2
19
3
7
7
6
9
7
7
6
0
1
0
0
140,526
KE-works/pykechain
KE-works_pykechain/pykechain/enums.py
pykechain.enums.ScopeStatus
class ScopeStatus(Enum): """The various status of a scope. :cvar ACTIVE: Status of a scope is active (default) :cvar CLOSED: Status of a scope is closed :cvar TEMPLATE: Status of a scope is a template (not actively used)(deprecated in KE-chain 3.0) :cvar DELETING: Status of a scope when the scope is being deleted """ ACTIVE = "ACTIVE" CLOSED = "CLOSED" TEMPLATE = "TEMPLATE" DELETING = "DELETING"
class ScopeStatus(Enum): '''The various status of a scope. :cvar ACTIVE: Status of a scope is active (default) :cvar CLOSED: Status of a scope is closed :cvar TEMPLATE: Status of a scope is a template (not actively used)(deprecated in KE-chain 3.0) :cvar DELETING: Status of a scope when the scope is being deleted '''
1
1
0
0
0
0
0
1.2
1
0
0
0
0
0
0
2
13
2
5
5
4
6
5
5
4
0
1
0
0
140,527
KE-works/pykechain
KE-works_pykechain/pykechain/enums.py
pykechain.enums.KechainEnv
class KechainEnv(Enum): """Environment variables that can be set for pykechain. :cvar KECHAIN_URL: full url of KE-chain where to connect to eg: 'https://<some>.ke-chain.com' :cvar KECHAIN_TOKEN: authentication token for the KE-chain user provided from KE-chain user account control :cvar KECHAIN_USERNAME: the username for the credentials :cvar KECHAIN_PASSWORD: the password for the credentials :cvar KECHAIN_SCOPE: the name of the project / scope. Should be unique, otherwise use scope_id :cvar KECHAIN_SCOPE_ID: the UUID of the project / scope. :cvar KECHAIN_FORCE_ENV_USE: set to 'true', '1', 'ok', or 'yes' to always use the environment variables. :cvar KECHAIN_SCOPE_STATUS: the status of the Scope to retrieve, defaults to None to retrieve all scopes :cvar KECHAIN_CHECK_CERTIFICATES: if the certificates of the URL should be checked. """ KECHAIN_FORCE_ENV_USE = "KECHAIN_FORCE_ENV_USE" KECHAIN_URL = "KECHAIN_URL" KECHAIN_TOKEN = "KECHAIN_TOKEN" KECHAIN_USERNAME = "KECHAIN_USERNAME" KECHAIN_PASSWORD = "KECHAIN_PASSWORD" KECHAIN_SCOPE = "KECHAIN_SCOPE" KECHAIN_SCOPE_ID = "KECHAIN_SCOPE_ID" KECHAIN_SCOPE_STATUS = "KECHAIN_SCOPE_STATUS" KECHAIN_CHECK_CERTIFICATES = "KECHAIN_CHECK_CERTIFICATES"
class KechainEnv(Enum): '''Environment variables that can be set for pykechain. :cvar KECHAIN_URL: full url of KE-chain where to connect to eg: 'https://<some>.ke-chain.com' :cvar KECHAIN_TOKEN: authentication token for the KE-chain user provided from KE-chain user account control :cvar KECHAIN_USERNAME: the username for the credentials :cvar KECHAIN_PASSWORD: the password for the credentials :cvar KECHAIN_SCOPE: the name of the project / scope. Should be unique, otherwise use scope_id :cvar KECHAIN_SCOPE_ID: the UUID of the project / scope. :cvar KECHAIN_FORCE_ENV_USE: set to 'true', '1', 'ok', or 'yes' to always use the environment variables. :cvar KECHAIN_SCOPE_STATUS: the status of the Scope to retrieve, defaults to None to retrieve all scopes :cvar KECHAIN_CHECK_CERTIFICATES: if the certificates of the URL should be checked. '''
1
1
0
0
0
0
0
1.4
1
0
0
0
0
0
0
2
26
2
10
10
9
14
10
10
9
0
1
0
0
140,528
KE-works/pykechain
KE-works_pykechain/pykechain/enums.py
pykechain.enums.LanguageCodes
class LanguageCodes(Enum): """ Options for the language setting of a user. :cvar ENGLISH: English :cvar FRENCH: French :cvar GERMAN: German :cvar DUTCH: Dutch :cvar ITALIAN: Italian """ ENGLISH = "en" FRENCH = "fr" GERMAN = "de" DUTCH = "nl" ITALIAN = "it"
class LanguageCodes(Enum): ''' Options for the language setting of a user. :cvar ENGLISH: English :cvar FRENCH: French :cvar GERMAN: German :cvar DUTCH: Dutch :cvar ITALIAN: Italian ''' pass
1
1
0
0
0
0
0
1.33
1
0
0
0
0
0
0
2
16
2
6
6
5
8
6
6
5
0
1
0
0
140,529
KE-works/pykechain
KE-works_pykechain/pykechain/enums.py
pykechain.enums.LinkTargets
class LinkTargets(Enum): """ Target for the CardWidget link and Link property representations. .. versionadded:: 3.0 :cvar SAME_TAB: "_self" :cvar NEW_TAB: "_blank" """ SAME_TAB = "_self" NEW_TAB = "_blank"
class LinkTargets(Enum): ''' Target for the CardWidget link and Link property representations. .. versionadded:: 3.0 :cvar SAME_TAB: "_self" :cvar NEW_TAB: "_blank" ''' pass
1
1
0
0
0
0
0
2
1
0
0
1
0
0
0
2
12
3
3
3
2
6
3
3
2
0
1
0
0
140,530
KE-works/pykechain
KE-works_pykechain/pykechain/enums.py
pykechain.enums.MaximumAccessLevelOptions
class MaximumAccessLevelOptions(SidebarAccessLevelOptions): """Options for maximum access level options for the sidebar.""" pass
class MaximumAccessLevelOptions(SidebarAccessLevelOptions): '''Options for maximum access level options for the sidebar.''' pass
1
1
0
0
0
0
0
0.5
1
0
0
0
0
0
0
2
4
1
2
1
1
1
2
1
1
0
2
0
0
140,531
KE-works/pykechain
KE-works_pykechain/pykechain/enums.py
pykechain.enums.MinimumAccessLevelOptions
class MinimumAccessLevelOptions(SidebarAccessLevelOptions): """Options for minumum access level options for the sidebar.""" pass
class MinimumAccessLevelOptions(SidebarAccessLevelOptions): '''Options for minumum access level options for the sidebar.''' pass
1
1
0
0
0
0
0
0.5
1
0
0
0
0
0
0
2
4
1
2
1
1
1
2
1
1
0
2
0
0
140,532
KE-works/pykechain
KE-works_pykechain/pykechain/enums.py
pykechain.enums.Multiplicity
class Multiplicity(Enum): """The various multiplicities that are accepted by KE-chain. For more information on the representation in KE-chain, please consult the KE-chain `Part documentation`_. :cvar ZERO_ONE: Multiplicity 0 to 1 :cvar ONE: Multiplicity 1 :cvar ZERO_MANY: Multiplicity 0 to infinity :cvar ONE_MANY: Multiplicity 1 to infinity """ ZERO_ONE = "ZERO_ONE" ONE = "ONE" ZERO_MANY = "ZERO_MANY" ONE_MANY = "ONE_MANY"
class Multiplicity(Enum): '''The various multiplicities that are accepted by KE-chain. For more information on the representation in KE-chain, please consult the KE-chain `Part documentation`_. :cvar ZERO_ONE: Multiplicity 0 to 1 :cvar ONE: Multiplicity 1 :cvar ZERO_MANY: Multiplicity 0 to infinity :cvar ONE_MANY: Multiplicity 1 to infinity ''' pass
1
1
0
0
0
0
0
1.6
1
0
0
0
0
0
0
2
16
3
5
5
4
8
5
5
4
0
1
0
0
140,533
KE-works/pykechain
KE-works_pykechain/pykechain/enums.py
pykechain.enums.NavigationBarAlignment
class NavigationBarAlignment(Alignment): """The acceptable alignment options for a Navigation Bar Widget.""" pass
class NavigationBarAlignment(Alignment): '''The acceptable alignment options for a Navigation Bar Widget.''' pass
1
1
0
0
0
0
0
0.5
1
0
0
0
0
0
0
2
4
1
2
1
1
1
2
1
1
0
2
0
0
140,534
KE-works/pykechain
KE-works_pykechain/pykechain/enums.py
pykechain.enums.NotificationChannels
class NotificationChannels(Enum): """ Options to retrieve a Notification based on its channel. :cvar EMAIL: email notification :cvar APP: app notification """ EMAIL = "EMAIL" APP = "APP"
class NotificationChannels(Enum): ''' Options to retrieve a Notification based on its channel. :cvar EMAIL: email notification :cvar APP: app notification ''' pass
1
1
0
0
0
0
0
1.67
1
0
0
0
0
0
0
2
10
2
3
3
2
5
3
3
2
0
1
0
0
140,535
KE-works/pykechain
KE-works_pykechain/pykechain/enums.py
pykechain.enums.NotificationEvent
class NotificationEvent(Enum): """ Options to retrieve a Notification based on its event. :cvar SHARE_ACTIVITY_LINK: notifications generated by sharing the link of an `Activity` :cvar EXPORT_ACTIVITY_ASYNC: notifications generated by exporting an `Activity` :cvar SHARE_ACTIVITY_PDF: notifications generated by sharing the pdf of an `Activity` """ SHARE_ACTIVITY_LINK = "SHARE_ACTIVITY_LINK" EXPORT_ACTIVITY_ASYNC = "EXPORT_ACTIVITY_ASYNC" SHARE_ACTIVITY_PDF = "SHARE_ACTIVITY_PDF"
class NotificationEvent(Enum): ''' Options to retrieve a Notification based on its event. :cvar SHARE_ACTIVITY_LINK: notifications generated by sharing the link of an `Activity` :cvar EXPORT_ACTIVITY_ASYNC: notifications generated by exporting an `Activity` :cvar SHARE_ACTIVITY_PDF: notifications generated by sharing the pdf of an `Activity` ''' pass
1
1
0
0
0
0
0
1.5
1
0
0
0
0
0
0
2
12
2
4
4
3
6
4
4
3
0
1
0
0
140,536
KE-works/pykechain
KE-works_pykechain/pykechain/enums.py
pykechain.enums.NotificationStatus
class NotificationStatus(Enum): """ Options to retrieve a Notification based on its status. normal lifecycle: - DRAFT, when a message is first saved to the backend and the status is still in draft. next states: READY - READY: when the message is ready for processing, it is complete and is to be processed next states: PROCESSING - PROCESSING: when the message is in the process of being send out next states: COMPLETED, FAILED - COMPLETED: when the message is successfully sent out next states: ARCHIVED - FAILED: when the message is not successfully sent out next states: ARCHIVED - ARCHIVED: when the message is archives and waiting for its deletion against a certain retention policy next states: None :cvar ARCHIVED: "archived" notifications :cvar COMPLETED: "completed" notifications :cvar DRAFT: "draft" notifications :cvar FAILED: "failed" notifications :cvar PROCESSING: "processing" notifications :cvar READY: "ready" notifications """ ARCHIVED = "ARCHIVED" COMPLETED = "COMPLETED" DRAFT = "DRAFT" FAILED = "FAILED" PROCESSING = "PROCESSING" READY = "READY"
class NotificationStatus(Enum): ''' Options to retrieve a Notification based on its status. normal lifecycle: - DRAFT, when a message is first saved to the backend and the status is still in draft. next states: READY - READY: when the message is ready for processing, it is complete and is to be processed next states: PROCESSING - PROCESSING: when the message is in the process of being send out next states: COMPLETED, FAILED - COMPLETED: when the message is successfully sent out next states: ARCHIVED - FAILED: when the message is not successfully sent out next states: ARCHIVED - ARCHIVED: when the message is archives and waiting for its deletion against a certain retention policy next states: None :cvar ARCHIVED: "archived" notifications :cvar COMPLETED: "completed" notifications :cvar DRAFT: "draft" notifications :cvar FAILED: "failed" notifications :cvar PROCESSING: "processing" notifications :cvar READY: "ready" notifications ''' pass
1
1
0
0
0
0
0
3.29
1
0
0
0
0
0
0
2
33
3
7
7
6
23
7
7
6
0
1
0
0
140,537
KE-works/pykechain
KE-works_pykechain/pykechain/enums.py
pykechain.enums.OtherRepresentations
class OtherRepresentations(Enum): """ Other representations used in KE-chain. :cvar CUSTOM_ICON: different font-awesome icons """ CUSTOM_ICON = "customIcon"
class OtherRepresentations(Enum): ''' Other representations used in KE-chain. :cvar CUSTOM_ICON: different font-awesome icons ''' pass
1
1
0
0
0
0
0
2
1
0
0
1
0
0
0
2
8
2
2
2
1
4
2
2
1
0
1
0
0
140,538
KE-works/pykechain
KE-works_pykechain/pykechain/enums.py
pykechain.enums.PaperOrientation
class PaperOrientation(Enum): """The acceptable paper orientation options for a downloaded PDF. :cvar PORTRAIT: Paper of orientation 'portrait' :cvar LANDSCAPE: Paper of orientation 'landscape' """ PORTRAIT = "portrait" LANDSCAPE = "landscape"
class PaperOrientation(Enum): '''The acceptable paper orientation options for a downloaded PDF. :cvar PORTRAIT: Paper of orientation 'portrait' :cvar LANDSCAPE: Paper of orientation 'landscape' ''' pass
1
1
0
0
0
0
0
1.33
1
0
0
0
0
0
0
2
9
2
3
3
2
4
3
3
2
0
1
0
0
140,539
KE-works/pykechain
KE-works_pykechain/pykechain/enums.py
pykechain.enums.PaperSize
class PaperSize(Enum): """The acceptable paper sizes options for a downloaded PDF. :cvar A0: Paper of size A0 :cvar A1: Paper of size A1 :cvar A2: Paper of size A2 :cvar A3: Paper of size A3 :cvar A4: Paper of size A4 """ A0 = "a0paper" A1 = "a1paper" A2 = "a2paper" A3 = "a3paper" A4 = "a4paper" AUTO = "automatic"
class PaperSize(Enum): '''The acceptable paper sizes options for a downloaded PDF. :cvar A0: Paper of size A0 :cvar A1: Paper of size A1 :cvar A2: Paper of size A2 :cvar A3: Paper of size A3 :cvar A4: Paper of size A4 ''' pass
1
1
0
0
0
0
0
1
1
0
0
0
0
0
0
2
16
2
7
7
6
7
7
7
6
0
1
0
0
140,540
KE-works/pykechain
KE-works_pykechain/pykechain/enums.py
pykechain.enums.ProgressBarColors
class ProgressBarColors(Enum): """ Some basic colors that can be set on a Progress Bar inside a Progress Bar Widget. .. versionadded:: 3.0 :cvar BLACK: '#000000' :cvar WHITE: '#FFFFFF' :cvar RED: 'FF0000' :cvar LIME: '#00FF00' :cvar BLUE: '#0000FF' :cvar YELLOW: '#FFFF00' :cvar CYAN: '#00FFFF' :cvar MAGENTA: '#FF00FF' :cvar SILVER: '#C0C0C0' :cvar GRAY: '#808080' :cvar MAROON: '#800000' :cvar OLIVE: '#808000' :cvar GREEN: '#008000' :cvar PURPLE: '#800080' :cvar TEAL: '#008080' :cvar NAVY: '#000080' :cvar DEFAULT_COMPLETED: '#339447' :cvar DEFAULT_IN_PROGRESS: '#FF6600' :cvar DEFAULT_NO_PROGRESS: '#EEEEEE' :cvar DEFAULT_IN_PROGRESS_BACKGROUND: '#FC7C3D' """ BLACK = "#000000" WHITE = "#FFFFFF" RED = "#FF0000" LIME = "#00FF00" BLUE = "#0000FF" YELLOW = "#FFFF00" CYAN = "#00FFFF" MAGENTA = "#FF00FF" SILVER = "#C0C0C0" GRAY = "#808080" MAROON = "#800000" OLIVE = "#808000" GREEN = "#008000" PURPLE = "#800080" TEAL = "#008080" NAVY = "#000080" DEFAULT_COMPLETED = "#339447" DEFAULT_IN_PROGRESS = "#FF6600" DEFAULT_NO_PROGRESS = "#EEEEEE" DEFAULT_IN_PROGRESS_BACKGROUND = "#FC7C3D"
class ProgressBarColors(Enum): ''' Some basic colors that can be set on a Progress Bar inside a Progress Bar Widget. .. versionadded:: 3.0 :cvar BLACK: '#000000' :cvar WHITE: '#FFFFFF' :cvar RED: 'FF0000' :cvar LIME: '#00FF00' :cvar BLUE: '#0000FF' :cvar YELLOW: '#FFFF00' :cvar CYAN: '#00FFFF' :cvar MAGENTA: '#FF00FF' :cvar SILVER: '#C0C0C0' :cvar GRAY: '#808080' :cvar MAROON: '#800000' :cvar OLIVE: '#808000' :cvar GREEN: '#008000' :cvar PURPLE: '#800080' :cvar TEAL: '#008080' :cvar NAVY: '#000080' :cvar DEFAULT_COMPLETED: '#339447' :cvar DEFAULT_IN_PROGRESS: '#FF6600' :cvar DEFAULT_NO_PROGRESS: '#EEEEEE' :cvar DEFAULT_IN_PROGRESS_BACKGROUND: '#FC7C3D' ''' pass
1
1
0
0
0
0
0
2.1
1
0
0
0
0
0
0
2
48
3
21
21
20
44
21
21
20
0
1
0
0
140,541
KE-works/pykechain
KE-works_pykechain/pykechain/enums.py
pykechain.enums.PropertyRepresentation
class PropertyRepresentation(Enum): """ The Representation configuration to display a property value. .. versionadded:: 3.0 .. versionchanged:: 3.11 added geocoordinate in line with KE-chain v2021.5.0 :cvar DECIMAL_PLACES: Amount of decimal places to show the number :cvar SIGNIFICANT_DIGITS: Number (count) of significant digits to display the number :cvar LINK_TARGET: configuration of a link to open the link in a new browsertab or not. :cvar BUTTON: options to represent the choices of a select-list :cvar THOUSANDS_SEPARATOR: option to display the thousand separator :cvar AUTOFILL: option to autofill the content of the property :cvar GEOCOORDINATE: option to display an alternative representation for the geocoordinate :cvar USE_PROPERTY_NAME: option to display the name of a property for a part actvity ref prop """ DECIMAL_PLACES = "decimalPlaces" SIGNIFICANT_DIGITS = "significantDigits" LINK_TARGET = "linkTarget" BUTTON = "buttonRepresentation" THOUSANDS_SEPARATOR = "thousandsSeparator" AUTOFILL = "autofill" GEOCOORDINATE = "geoCoordinate" USE_PROPERTY_NAME = "usePropertyName" CAMERA_SCANNER_INPUT = "cameraScannerInput" SIGNATURE = "signature" FILE_DISPLAY = "fileDisplay" SHOW_ONLY_SCOPE_MEMBERS = "showOnlyScopeMembers"
class PropertyRepresentation(Enum): ''' The Representation configuration to display a property value. .. versionadded:: 3.0 .. versionchanged:: 3.11 added geocoordinate in line with KE-chain v2021.5.0 :cvar DECIMAL_PLACES: Amount of decimal places to show the number :cvar SIGNIFICANT_DIGITS: Number (count) of significant digits to display the number :cvar LINK_TARGET: configuration of a link to open the link in a new browsertab or not. :cvar BUTTON: options to represent the choices of a select-list :cvar THOUSANDS_SEPARATOR: option to display the thousand separator :cvar AUTOFILL: option to autofill the content of the property :cvar GEOCOORDINATE: option to display an alternative representation for the geocoordinate :cvar USE_PROPERTY_NAME: option to display the name of a property for a part actvity ref prop ''' pass
1
1
0
0
0
0
0
1
1
0
0
1
0
0
0
2
29
3
13
13
12
13
13
13
12
0
1
0
0
140,542
KE-works/pykechain
KE-works_pykechain/pykechain/enums.py
pykechain.enums.PropertyType
class PropertyType(Enum): """The various property types that are accepted by KE-chain. For more information on the representation in KE-chain, please consult the KE-chain `Property documentation`_. :cvar CHAR_VALUE: a charfield property (single line text) :cvar TEXT_VALUE: text property (long text, may span multiple lines) :cvar BOOLEAN_VALUE: a boolean value property (True/False) :cvar INT_VALUE: integer property (whole number) :cvar FLOAT_VALUE: floating point number property (with digits) :cvar DATETIME_VALUE: a datetime value property :cvar ATTACHMENT_VALUE: an attachment property :cvar LINK_VALUE: url property :cvar REFERENCE_VALUE: a reference property, a UUID value referring to other part model .. versionadded:: 1.14 :cvar SINGLE_SELECT_VALUE: single select list property (choose from a list) :cvar REFERENCES_VALUE: a multi reference property, a list of UUID values referring to other part models .. versionadded:: 3.6 :cvar ACTIVITY_REFERENCES_VALUE: Activity References Property :cvar SCOPE_REFERENCES_VALUE: Scope References Property :cvar SERVICE_REFERENCES_VALUE: Service Referenes Property :cvar TEAM_REFERENCES_VALUE: Team References Property :cvar USER_REFERENCES_VALUE: User References Property :cvar FORM_REFERENCES_VALUE: Form References Property :cvar CONTEXT_REFERENCES_VALUE: Context References Property :cvar JSON_VALUE: Generic JSON storage Property :cvar GEOJSON_VALUE: GEOJSON property to store map data :cvar WEATHER_VALUE: Weather JSON property compatible with the response of weatherapi.com :cvar DATE_VALUE: Date value :cvar TIME_VALUE: Time value :cvar DURATION_VALUE: Duration value .. versionadded:: 3.19 :cvar STATUS_REFERENCES_VALUE: Status References Property .. _Property documentation: https://support.ke-chain.com/confluence/dosearchsite.action? queryString=concept+property """ CHAR_VALUE = "CHAR_VALUE" TEXT_VALUE = "TEXT_VALUE" BOOLEAN_VALUE = "BOOLEAN_VALUE" INT_VALUE = "INT_VALUE" FLOAT_VALUE = "FLOAT_VALUE" DATETIME_VALUE = "DATETIME_VALUE" DATE_VALUE = "DATE_VALUE" TIME_VALUE = "TIME_VALUE" DURATION_VALUE = "DURATION_VALUE" ATTACHMENT_VALUE = "ATTACHMENT_VALUE" LINK_VALUE = "LINK_VALUE" SINGLE_SELECT_VALUE = "SINGLE_SELECT_VALUE" MULTI_SELECT_VALUE = "MULTI_SELECT_VALUE" REFERENCE_VALUE = "REFERENCE_VALUE" REFERENCES_VALUE = "REFERENCES_VALUE" ACTIVITY_REFERENCES_VALUE = "ACTIVITY_REFERENCES_VALUE" SCOPE_REFERENCES_VALUE = "SCOPE_REFERENCES_VALUE" SERVICE_REFERENCES_VALUE = "SERVICE_REFERENCES_VALUE" FORM_REFERENCES_VALUE = "FORM_REFERENCES_VALUE" CONTEXT_REFERENCES_VALUE = "CONTEXT_REFERENCES_VALUE" STATUS_REFERENCES_VALUE = "STATUS_REFERENCES_VALUE" TEAM_REFERENCES_VALUE = "TEAM_REFERENCES_VALUE" USER_REFERENCES_VALUE = "USER_REFERENCES_VALUE" STOREDFILE_REFERENCES_VALUE = "STOREDFILE_REFERENCES_VALUE" SIGNATURE_VALUE = "SIGNATURE_VALUE" JSON_VALUE = "JSON_VALUE" GEOJSON_VALUE = "GEOJSON_VALUE" WEATHER_VALUE = "WEATHER_VALUE"
class PropertyType(Enum): '''The various property types that are accepted by KE-chain. For more information on the representation in KE-chain, please consult the KE-chain `Property documentation`_. :cvar CHAR_VALUE: a charfield property (single line text) :cvar TEXT_VALUE: text property (long text, may span multiple lines) :cvar BOOLEAN_VALUE: a boolean value property (True/False) :cvar INT_VALUE: integer property (whole number) :cvar FLOAT_VALUE: floating point number property (with digits) :cvar DATETIME_VALUE: a datetime value property :cvar ATTACHMENT_VALUE: an attachment property :cvar LINK_VALUE: url property :cvar REFERENCE_VALUE: a reference property, a UUID value referring to other part model .. versionadded:: 1.14 :cvar SINGLE_SELECT_VALUE: single select list property (choose from a list) :cvar REFERENCES_VALUE: a multi reference property, a list of UUID values referring to other part models .. versionadded:: 3.6 :cvar ACTIVITY_REFERENCES_VALUE: Activity References Property :cvar SCOPE_REFERENCES_VALUE: Scope References Property :cvar SERVICE_REFERENCES_VALUE: Service Referenes Property :cvar TEAM_REFERENCES_VALUE: Team References Property :cvar USER_REFERENCES_VALUE: User References Property :cvar FORM_REFERENCES_VALUE: Form References Property :cvar CONTEXT_REFERENCES_VALUE: Context References Property :cvar JSON_VALUE: Generic JSON storage Property :cvar GEOJSON_VALUE: GEOJSON property to store map data :cvar WEATHER_VALUE: Weather JSON property compatible with the response of weatherapi.com :cvar DATE_VALUE: Date value :cvar TIME_VALUE: Time value :cvar DURATION_VALUE: Duration value .. versionadded:: 3.19 :cvar STATUS_REFERENCES_VALUE: Status References Property .. _Property documentation: https://support.ke-chain.com/confluence/dosearchsite.action? queryString=concept+property ''' pass
1
1
0
0
0
0
0
1.21
1
0
0
0
0
0
0
2
72
8
29
29
28
35
29
29
28
0
1
0
0
140,543
KE-works/pykechain
KE-works_pykechain/pykechain/enums.py
pykechain.enums.ScopeCategory
class ScopeCategory(Enum): """The various categories of a scope. :cvar LIBRARY_SCOPE: The scope is a library scope :cvar USER_SCOPE: The scope is a normal user scope :cvar TEMPLATE_SCOPE: The scope is a template scope """ LIBRARY_SCOPE = "LIBRARY_SCOPE" USER_SCOPE = "USER_SCOPE" TEMPLATE_SCOPE = "TEMPLATE_SCOPE"
class ScopeCategory(Enum): '''The various categories of a scope. :cvar LIBRARY_SCOPE: The scope is a library scope :cvar USER_SCOPE: The scope is a normal user scope :cvar TEMPLATE_SCOPE: The scope is a template scope ''' pass
1
1
0
0
0
0
0
1.25
1
0
0
0
0
0
0
2
11
2
4
4
3
5
4
4
3
0
1
0
0
140,544
KE-works/pykechain
KE-works_pykechain/pykechain/enums.py
pykechain.enums.ScopeMemberActions
class ScopeMemberActions(Enum): """ Actions to be performed on the members of a scope. :cvar ADD: add a member to the scope :cvar REMOVE: delete a member from the scope """ ADD = "add" REMOVE = "remove"
class ScopeMemberActions(Enum): ''' Actions to be performed on the members of a scope. :cvar ADD: add a member to the scope :cvar REMOVE: delete a member from the scope ''' pass
1
1
0
0
0
0
0
1.67
1
0
0
0
0
0
0
2
10
2
3
3
2
5
3
3
2
0
1
0
0
140,545
KE-works/pykechain
KE-works_pykechain/pykechain/enums.py
pykechain.enums.ScopeReferenceColumns
class ScopeReferenceColumns(Enum): """ List of columns visible in the Scope Reference dialog. :cvar START_DATE: start date of the scope :cvar DUE_DATE: due date of the scope :cvar STATUS: status of the scope :cvar PROGRESS: progress of the scope :cvar TAGS: tags of the scope """ START_DATE = "start_date" DUE_DATE = "due_date" STATUS = "status" PROGRESS = "progress" TAGS = "tags"
class ScopeReferenceColumns(Enum): ''' List of columns visible in the Scope Reference dialog. :cvar START_DATE: start date of the scope :cvar DUE_DATE: due date of the scope :cvar STATUS: status of the scope :cvar PROGRESS: progress of the scope :cvar TAGS: tags of the scope ''' pass
1
1
0
0
0
0
0
1.33
1
0
0
0
0
0
0
2
16
2
6
6
5
8
6
6
5
0
1
0
0
140,546
KE-works/pykechain
KE-works_pykechain/pykechain/enums.py
pykechain.enums.ImageSize
class ImageSize(Enum): """ Options for the Image Size the picture would be saved as from an Attachment Property. :cvar SQXS: SQXS (100, 100) # pixels square :cvar XS: XS (100, ) # pixels width :cvar S: S (320, ) :cvar SQS: SQS (320, 320) :cvar M: M (640, ) :cvar SQM: SQM (640, 640) :cvar L: L (1024, ) :cvar SQL: SQL (1024, 1024) :cvar XL: XL (2048, ) :cvar SQXL: SQXL (2048, 2048) :cvar XXL: XXL (4096, ) :cvar SQXXL: SQXXL (4096, 4096) """ SQXS = "SQXS" XS = "XS" S = "S" SQS = "SQS" M = "M" SQM = "SQM" L = "L" SQL = "SQL" XL = "XL" SQXL = "SQXL" XXL = "XXL" SQXXL = "SQXXL"
class ImageSize(Enum): ''' Options for the Image Size the picture would be saved as from an Attachment Property. :cvar SQXS: SQXS (100, 100) # pixels square :cvar XS: XS (100, ) # pixels width :cvar S: S (320, ) :cvar SQS: SQS (320, 320) :cvar M: M (640, ) :cvar SQM: SQM (640, 640) :cvar L: L (1024, ) :cvar SQL: SQL (1024, 1024) :cvar XL: XL (2048, ) :cvar SQXL: SQXL (2048, 2048) :cvar XXL: XXL (4096, ) :cvar SQXXL: SQXXL (4096, 4096) ''' pass
1
1
0
0
0
0
0
1.15
1
0
0
0
0
0
0
2
30
2
13
13
12
15
13
13
12
0
1
0
0
140,547
KE-works/pykechain
KE-works_pykechain/pykechain/enums.py
pykechain.enums.ScopeRoles
class ScopeRoles(Enum): """ Roles that exist for a member of a scope. :cvar MANAGER: owner of the scope, has full rights :cvar SUPERVISOR: supervisor member of a scope, has the rights as leadmember and rights to manage catalog tasks. :cvar LEADMEMBER: elevated member, has assignment rights, no rights on App tasks or Catalog tasks. :cvar MEMBER: normal member, only has viewing rights """ MANAGER = "manager" SUPERVISOR = "supervisor" LEADMEMBER = "leadmember" MEMBER = "member"
class ScopeRoles(Enum): ''' Roles that exist for a member of a scope. :cvar MANAGER: owner of the scope, has full rights :cvar SUPERVISOR: supervisor member of a scope, has the rights as leadmember and rights to manage catalog tasks. :cvar LEADMEMBER: elevated member, has assignment rights, no rights on App tasks or Catalog tasks. :cvar MEMBER: normal member, only has viewing rights ''' pass
1
1
0
0
0
0
0
1.8
1
0
0
0
0
0
0
2
16
2
5
5
4
9
5
5
4
0
1
0
0