Search is not available for this dataset
identifier
stringlengths
1
155
parameters
stringlengths
2
6.09k
docstring
stringlengths
11
63.4k
docstring_summary
stringlengths
0
63.4k
function
stringlengths
29
99.8k
function_tokens
sequence
start_point
sequence
end_point
sequence
language
stringclasses
1 value
docstring_language
stringlengths
2
7
docstring_language_predictions
stringlengths
18
23
is_langid_reliable
stringclasses
2 values
VmSchedulingBusinessEngine.get_vm_cpu_utilization_series
(self, vm_id: int)
Get the CPU utilization series of the specific VM by the given ID.
Get the CPU utilization series of the specific VM by the given ID.
def get_vm_cpu_utilization_series(self, vm_id: int) -> List[float]: """Get the CPU utilization series of the specific VM by the given ID.""" if vm_id in self._live_vms: return self._live_vms[vm_id].get_historical_utilization_series(cur_tick=self._tick) return []
[ "def", "get_vm_cpu_utilization_series", "(", "self", ",", "vm_id", ":", "int", ")", "->", "List", "[", "float", "]", ":", "if", "vm_id", "in", "self", ".", "_live_vms", ":", "return", "self", ".", "_live_vms", "[", "vm_id", "]", ".", "get_historical_utilization_series", "(", "cur_tick", "=", "self", ".", "_tick", ")", "return", "[", "]" ]
[ 551, 4 ]
[ 556, 17 ]
python
en
['en', 'en', 'en']
True
VmSchedulingBusinessEngine.get_metrics
(self)
Get current environment metrics information. Returns: DocableDict: Metrics information.
Get current environment metrics information.
def get_metrics(self) -> DocableDict: """Get current environment metrics information. Returns: DocableDict: Metrics information. """ return DocableDict( metrics_desc, total_vm_requests=self._total_vm_requests, total_incomes=self._total_incomes, energy_consumption_cost=self._energy_consumption_cost, total_profit=self._total_profit, total_energy_consumption=self._total_energy_consumption, successful_allocation=self._successful_allocation, successful_completion=self._successful_completion, failed_allocation=self._failed_allocation, failed_completion=self._failed_completion, total_latency=self._total_latency, total_oversubscriptions=self._total_oversubscriptions, total_overload_pms=self._total_overload_pms, total_overload_vms=self._total_overload_vms )
[ "def", "get_metrics", "(", "self", ")", "->", "DocableDict", ":", "return", "DocableDict", "(", "metrics_desc", ",", "total_vm_requests", "=", "self", ".", "_total_vm_requests", ",", "total_incomes", "=", "self", ".", "_total_incomes", ",", "energy_consumption_cost", "=", "self", ".", "_energy_consumption_cost", ",", "total_profit", "=", "self", ".", "_total_profit", ",", "total_energy_consumption", "=", "self", ".", "_total_energy_consumption", ",", "successful_allocation", "=", "self", ".", "_successful_allocation", ",", "successful_completion", "=", "self", ".", "_successful_completion", ",", "failed_allocation", "=", "self", ".", "_failed_allocation", ",", "failed_completion", "=", "self", ".", "_failed_completion", ",", "total_latency", "=", "self", ".", "_total_latency", ",", "total_oversubscriptions", "=", "self", ".", "_total_oversubscriptions", ",", "total_overload_pms", "=", "self", ".", "_total_overload_pms", ",", "total_overload_vms", "=", "self", ".", "_total_overload_vms", ")" ]
[ 558, 4 ]
[ 580, 9 ]
python
en
['fr', 'en', 'en']
True
VmSchedulingBusinessEngine._update_vm_workload
(self, cur_tick_cpu_utilization: dict)
Update all live VMs CPU utilization. The length of VMs utilization series could be difference among all VMs, because index 0 represents the VM's CPU utilization at the tick it starts.
Update all live VMs CPU utilization.
def _update_vm_workload(self, cur_tick_cpu_utilization: dict): """Update all live VMs CPU utilization. The length of VMs utilization series could be difference among all VMs, because index 0 represents the VM's CPU utilization at the tick it starts. """ for live_vm in self._live_vms.values(): # NOTE: Some data could be lost. We use -1.0 to represent the missing data. if live_vm.id not in cur_tick_cpu_utilization: live_vm.add_utilization(cpu_utilization=-1.0) else: live_vm.add_utilization(cpu_utilization=cur_tick_cpu_utilization[live_vm.id]) live_vm.cpu_utilization = live_vm.get_utilization(cur_tick=self._tick) for pending_vm_payload in self._pending_vm_request_payload.values(): pending_vm = pending_vm_payload.vm_info if pending_vm.id not in cur_tick_cpu_utilization: pending_vm.add_utilization(cpu_utilization=-1.0) else: pending_vm.add_utilization(cpu_utilization=cur_tick_cpu_utilization[pending_vm.id])
[ "def", "_update_vm_workload", "(", "self", ",", "cur_tick_cpu_utilization", ":", "dict", ")", ":", "for", "live_vm", "in", "self", ".", "_live_vms", ".", "values", "(", ")", ":", "# NOTE: Some data could be lost. We use -1.0 to represent the missing data.", "if", "live_vm", ".", "id", "not", "in", "cur_tick_cpu_utilization", ":", "live_vm", ".", "add_utilization", "(", "cpu_utilization", "=", "-", "1.0", ")", "else", ":", "live_vm", ".", "add_utilization", "(", "cpu_utilization", "=", "cur_tick_cpu_utilization", "[", "live_vm", ".", "id", "]", ")", "live_vm", ".", "cpu_utilization", "=", "live_vm", ".", "get_utilization", "(", "cur_tick", "=", "self", ".", "_tick", ")", "for", "pending_vm_payload", "in", "self", ".", "_pending_vm_request_payload", ".", "values", "(", ")", ":", "pending_vm", "=", "pending_vm_payload", ".", "vm_info", "if", "pending_vm", ".", "id", "not", "in", "cur_tick_cpu_utilization", ":", "pending_vm", ".", "add_utilization", "(", "cpu_utilization", "=", "-", "1.0", ")", "else", ":", "pending_vm", ".", "add_utilization", "(", "cpu_utilization", "=", "cur_tick_cpu_utilization", "[", "pending_vm", ".", "id", "]", ")" ]
[ 588, 4 ]
[ 607, 99 ]
python
en
['en', 'co', 'en']
True
VmSchedulingBusinessEngine._update_pm_workload
(self)
Update CPU utilization occupied by total VMs on each PM.
Update CPU utilization occupied by total VMs on each PM.
def _update_pm_workload(self): """Update CPU utilization occupied by total VMs on each PM.""" for pm in self._machines: total_pm_cpu_cores_used: float = 0.0 for vm_id in pm.live_vms: vm = self._live_vms[vm_id] total_pm_cpu_cores_used += vm.cpu_utilization * vm.cpu_cores_requirement pm.update_cpu_utilization(vm=None, cpu_utilization=total_pm_cpu_cores_used / pm.cpu_cores_capacity) pm.energy_consumption = self._cpu_utilization_to_energy_consumption( pm_type=self._pm_config_dict[pm.pm_type], cpu_utilization=pm.cpu_utilization )
[ "def", "_update_pm_workload", "(", "self", ")", ":", "for", "pm", "in", "self", ".", "_machines", ":", "total_pm_cpu_cores_used", ":", "float", "=", "0.0", "for", "vm_id", "in", "pm", ".", "live_vms", ":", "vm", "=", "self", ".", "_live_vms", "[", "vm_id", "]", "total_pm_cpu_cores_used", "+=", "vm", ".", "cpu_utilization", "*", "vm", ".", "cpu_cores_requirement", "pm", ".", "update_cpu_utilization", "(", "vm", "=", "None", ",", "cpu_utilization", "=", "total_pm_cpu_cores_used", "/", "pm", ".", "cpu_cores_capacity", ")", "pm", ".", "energy_consumption", "=", "self", ".", "_cpu_utilization_to_energy_consumption", "(", "pm_type", "=", "self", ".", "_pm_config_dict", "[", "pm", ".", "pm_type", "]", ",", "cpu_utilization", "=", "pm", ".", "cpu_utilization", ")" ]
[ 649, 4 ]
[ 660, 13 ]
python
en
['en', 'en', 'en']
True
VmSchedulingBusinessEngine._overload
(self, pm_id: int, tick: int)
Overload logic. Currently only support killing all VMs on the overload PM and note them as failed allocations.
Overload logic.
def _overload(self, pm_id: int, tick: int): """Overload logic. Currently only support killing all VMs on the overload PM and note them as failed allocations. """ # TODO: Future features of overload modeling. # 1. Performance degradation # 2. Quiesce specific VMs. pm: PhysicalMachine = self._machines[pm_id] vm_ids: List[int] = [vm_id for vm_id in pm.live_vms] if self._kill_all_vms_if_overload: for vm_id in vm_ids: self._total_incomes -= self._live_vms[vm_id].get_income_till_now(tick) self._live_vms.pop(vm_id) pm.deallocate_vms(vm_ids=vm_ids) self._failed_completion += len(vm_ids) self._total_overload_vms += len(vm_ids)
[ "def", "_overload", "(", "self", ",", "pm_id", ":", "int", ",", "tick", ":", "int", ")", ":", "# TODO: Future features of overload modeling.", "# 1. Performance degradation", "# 2. Quiesce specific VMs.", "pm", ":", "PhysicalMachine", "=", "self", ".", "_machines", "[", "pm_id", "]", "vm_ids", ":", "List", "[", "int", "]", "=", "[", "vm_id", "for", "vm_id", "in", "pm", ".", "live_vms", "]", "if", "self", ".", "_kill_all_vms_if_overload", ":", "for", "vm_id", "in", "vm_ids", ":", "self", ".", "_total_incomes", "-=", "self", ".", "_live_vms", "[", "vm_id", "]", ".", "get_income_till_now", "(", "tick", ")", "self", ".", "_live_vms", ".", "pop", "(", "vm_id", ")", "pm", ".", "deallocate_vms", "(", "vm_ids", "=", "vm_ids", ")", "self", ".", "_failed_completion", "+=", "len", "(", "vm_ids", ")", "self", ".", "_total_overload_vms", "+=", "len", "(", "vm_ids", ")" ]
[ 662, 4 ]
[ 681, 47 ]
python
en
['en', 'sm', 'en']
False
VmSchedulingBusinessEngine._cpu_utilization_to_energy_consumption
(self, pm_type: dict, cpu_utilization: float)
Convert the CPU utilization to energy consumption. The formulation refers to https://dl.acm.org/doi/epdf/10.1145/1273440.1250665
Convert the CPU utilization to energy consumption.
def _cpu_utilization_to_energy_consumption(self, pm_type: dict, cpu_utilization: float) -> float: """Convert the CPU utilization to energy consumption. The formulation refers to https://dl.acm.org/doi/epdf/10.1145/1273440.1250665 """ power: float = pm_type["power_curve"]["calibration_parameter"] busy_power: int = pm_type["power_curve"]["busy_power"] idle_power: int = pm_type["power_curve"]["idle_power"] cpu_utilization /= 100 cpu_utilization = min(1, cpu_utilization) energy_consumption_per_hour = ( idle_power + (busy_power - idle_power) * (2 * cpu_utilization - pow(cpu_utilization, power)) ) return (energy_consumption_per_hour / self._ticks_per_hour) / 1000
[ "def", "_cpu_utilization_to_energy_consumption", "(", "self", ",", "pm_type", ":", "dict", ",", "cpu_utilization", ":", "float", ")", "->", "float", ":", "power", ":", "float", "=", "pm_type", "[", "\"power_curve\"", "]", "[", "\"calibration_parameter\"", "]", "busy_power", ":", "int", "=", "pm_type", "[", "\"power_curve\"", "]", "[", "\"busy_power\"", "]", "idle_power", ":", "int", "=", "pm_type", "[", "\"power_curve\"", "]", "[", "\"idle_power\"", "]", "cpu_utilization", "/=", "100", "cpu_utilization", "=", "min", "(", "1", ",", "cpu_utilization", ")", "energy_consumption_per_hour", "=", "(", "idle_power", "+", "(", "busy_power", "-", "idle_power", ")", "*", "(", "2", "*", "cpu_utilization", "-", "pow", "(", "cpu_utilization", ",", "power", ")", ")", ")", "return", "(", "energy_consumption_per_hour", "/", "self", ".", "_ticks_per_hour", ")", "/", "1000" ]
[ 683, 4 ]
[ 698, 74 ]
python
en
['en', 'en', 'en']
True
VmSchedulingBusinessEngine._postpone_vm_request
(self, postpone_type: PostponeType, vm_id: int, remaining_buffer_time: int)
Postpone VM request.
Postpone VM request.
def _postpone_vm_request(self, postpone_type: PostponeType, vm_id: int, remaining_buffer_time: int): """Postpone VM request.""" if remaining_buffer_time >= self._delay_duration: if postpone_type == PostponeType.Resource: self._total_latency.due_to_resource += self._delay_duration elif postpone_type == PostponeType.Agent: self._total_latency.due_to_agent += self._delay_duration postpone_payload = self._pending_vm_request_payload[vm_id] postpone_payload.remaining_buffer_time -= self._delay_duration postpone_event = self._event_buffer.gen_cascade_event( tick=self._tick + self._delay_duration, event_type=Events.REQUEST, payload=postpone_payload ) self._event_buffer.insert_event(event=postpone_event) else: # Fail # Pop out VM request payload. self._pending_vm_request_payload.pop(vm_id) # Add failed allocation. self._failed_allocation += 1
[ "def", "_postpone_vm_request", "(", "self", ",", "postpone_type", ":", "PostponeType", ",", "vm_id", ":", "int", ",", "remaining_buffer_time", ":", "int", ")", ":", "if", "remaining_buffer_time", ">=", "self", ".", "_delay_duration", ":", "if", "postpone_type", "==", "PostponeType", ".", "Resource", ":", "self", ".", "_total_latency", ".", "due_to_resource", "+=", "self", ".", "_delay_duration", "elif", "postpone_type", "==", "PostponeType", ".", "Agent", ":", "self", ".", "_total_latency", ".", "due_to_agent", "+=", "self", ".", "_delay_duration", "postpone_payload", "=", "self", ".", "_pending_vm_request_payload", "[", "vm_id", "]", "postpone_payload", ".", "remaining_buffer_time", "-=", "self", ".", "_delay_duration", "postpone_event", "=", "self", ".", "_event_buffer", ".", "gen_cascade_event", "(", "tick", "=", "self", ".", "_tick", "+", "self", ".", "_delay_duration", ",", "event_type", "=", "Events", ".", "REQUEST", ",", "payload", "=", "postpone_payload", ")", "self", ".", "_event_buffer", ".", "insert_event", "(", "event", "=", "postpone_event", ")", "else", ":", "# Fail", "# Pop out VM request payload.", "self", ".", "_pending_vm_request_payload", ".", "pop", "(", "vm_id", ")", "# Add failed allocation.", "self", ".", "_failed_allocation", "+=", "1" ]
[ 700, 4 ]
[ 721, 40 ]
python
en
['en', 'kk', 'en']
True
VmSchedulingBusinessEngine._get_valid_pms
( self, vm_cpu_cores_requirement: int, vm_memory_requirement: int, vm_category: VmCategory )
Check all valid PMs. Args: vm_cpu_cores_requirement (int): The CPU cores requested by the VM. vm_memory_requirement (int): The memory requested by the VM. vm_category (VmCategory): The VM category. Delay-insensitive: 0, Interactive: 1, Unknown: 2.
Check all valid PMs.
def _get_valid_pms( self, vm_cpu_cores_requirement: int, vm_memory_requirement: int, vm_category: VmCategory ) -> List[int]: """Check all valid PMs. Args: vm_cpu_cores_requirement (int): The CPU cores requested by the VM. vm_memory_requirement (int): The memory requested by the VM. vm_category (VmCategory): The VM category. Delay-insensitive: 0, Interactive: 1, Unknown: 2. """ # NOTE: Should we implement this logic inside the action scope? valid_pm_list = [] # Delay-insensitive: 0, Interactive: 1, and Unknown: 2. if vm_category == VmCategory.INTERACTIVE or vm_category == VmCategory.UNKNOWN: valid_pm_list = self._get_valid_non_oversubscribable_pms( vm_cpu_cores_requirement=vm_cpu_cores_requirement, vm_memory_requirement=vm_memory_requirement ) else: valid_pm_list = self._get_valid_oversubscribable_pms( vm_cpu_cores_requirement=vm_cpu_cores_requirement, vm_memory_requirement=vm_memory_requirement ) return valid_pm_list
[ "def", "_get_valid_pms", "(", "self", ",", "vm_cpu_cores_requirement", ":", "int", ",", "vm_memory_requirement", ":", "int", ",", "vm_category", ":", "VmCategory", ")", "->", "List", "[", "int", "]", ":", "# NOTE: Should we implement this logic inside the action scope?", "valid_pm_list", "=", "[", "]", "# Delay-insensitive: 0, Interactive: 1, and Unknown: 2.", "if", "vm_category", "==", "VmCategory", ".", "INTERACTIVE", "or", "vm_category", "==", "VmCategory", ".", "UNKNOWN", ":", "valid_pm_list", "=", "self", ".", "_get_valid_non_oversubscribable_pms", "(", "vm_cpu_cores_requirement", "=", "vm_cpu_cores_requirement", ",", "vm_memory_requirement", "=", "vm_memory_requirement", ")", "else", ":", "valid_pm_list", "=", "self", ".", "_get_valid_oversubscribable_pms", "(", "vm_cpu_cores_requirement", "=", "vm_cpu_cores_requirement", ",", "vm_memory_requirement", "=", "vm_memory_requirement", ")", "return", "valid_pm_list" ]
[ 723, 4 ]
[ 748, 28 ]
python
en
['en', 'en', 'en']
True
VmSchedulingBusinessEngine._process_finished_vm
(self)
Release PM resource from the finished VM.
Release PM resource from the finished VM.
def _process_finished_vm(self): """Release PM resource from the finished VM.""" # Get the VM info. vm_id_list = [] for vm in self._live_vms.values(): if vm.deletion_tick == self._tick: # Release PM resources. pm: PhysicalMachine = self._machines[vm.pm_id] pm.cpu_cores_allocated -= vm.cpu_cores_requirement pm.memory_allocated -= vm.memory_requirement pm.deallocate_vms(vm_ids=[vm.id]) # If the VM list is empty, switch the state to empty. if not pm.live_vms: pm.oversubscribable = PmState.EMPTY vm_id_list.append(vm.id) # VM completed task succeed. self._successful_completion += 1 # Remove dead VM. for vm_id in vm_id_list: self._live_vms.pop(vm_id)
[ "def", "_process_finished_vm", "(", "self", ")", ":", "# Get the VM info.", "vm_id_list", "=", "[", "]", "for", "vm", "in", "self", ".", "_live_vms", ".", "values", "(", ")", ":", "if", "vm", ".", "deletion_tick", "==", "self", ".", "_tick", ":", "# Release PM resources.", "pm", ":", "PhysicalMachine", "=", "self", ".", "_machines", "[", "vm", ".", "pm_id", "]", "pm", ".", "cpu_cores_allocated", "-=", "vm", ".", "cpu_cores_requirement", "pm", ".", "memory_allocated", "-=", "vm", ".", "memory_requirement", "pm", ".", "deallocate_vms", "(", "vm_ids", "=", "[", "vm", ".", "id", "]", ")", "# If the VM list is empty, switch the state to empty.", "if", "not", "pm", ".", "live_vms", ":", "pm", ".", "oversubscribable", "=", "PmState", ".", "EMPTY", "vm_id_list", ".", "append", "(", "vm", ".", "id", ")", "# VM completed task succeed.", "self", ".", "_successful_completion", "+=", "1", "# Remove dead VM.", "for", "vm_id", "in", "vm_id_list", ":", "self", ".", "_live_vms", ".", "pop", "(", "vm_id", ")" ]
[ 785, 4 ]
[ 806, 37 ]
python
en
['en', 'en', 'en']
True
VmSchedulingBusinessEngine._on_vm_required
(self, vm_request_event: CascadeEvent)
Callback when there is a VM request generated.
Callback when there is a VM request generated.
def _on_vm_required(self, vm_request_event: CascadeEvent): """Callback when there is a VM request generated.""" # Get VM data from payload. payload: VmRequestPayload = vm_request_event.payload vm_info: VirtualMachine = payload.vm_info remaining_buffer_time: int = payload.remaining_buffer_time # Store the payload inside business engine. self._pending_vm_request_payload[vm_info.id] = payload # Get valid pm list. valid_pm_list = self._get_valid_pms( vm_cpu_cores_requirement=vm_info.cpu_cores_requirement, vm_memory_requirement=vm_info.memory_requirement, vm_category=vm_info.category ) if len(valid_pm_list) > 0: # Generate pending decision. decision_payload = DecisionPayload( frame_index=self.frame_index(tick=self._tick), valid_pms=valid_pm_list, vm_id=vm_info.id, vm_cpu_cores_requirement=vm_info.cpu_cores_requirement, vm_memory_requirement=vm_info.memory_requirement, vm_sub_id=vm_info.sub_id, vm_category=vm_info.category, remaining_buffer_time=remaining_buffer_time ) self._pending_action_vm_id = vm_info.id pending_decision_event = self._event_buffer.gen_decision_event( tick=vm_request_event.tick, payload=decision_payload) vm_request_event.add_immediate_event(event=pending_decision_event) else: # Either postpone the requirement event or failed. self._postpone_vm_request( postpone_type=PostponeType.Resource, vm_id=vm_info.id, remaining_buffer_time=remaining_buffer_time )
[ "def", "_on_vm_required", "(", "self", ",", "vm_request_event", ":", "CascadeEvent", ")", ":", "# Get VM data from payload.", "payload", ":", "VmRequestPayload", "=", "vm_request_event", ".", "payload", "vm_info", ":", "VirtualMachine", "=", "payload", ".", "vm_info", "remaining_buffer_time", ":", "int", "=", "payload", ".", "remaining_buffer_time", "# Store the payload inside business engine.", "self", ".", "_pending_vm_request_payload", "[", "vm_info", ".", "id", "]", "=", "payload", "# Get valid pm list.", "valid_pm_list", "=", "self", ".", "_get_valid_pms", "(", "vm_cpu_cores_requirement", "=", "vm_info", ".", "cpu_cores_requirement", ",", "vm_memory_requirement", "=", "vm_info", ".", "memory_requirement", ",", "vm_category", "=", "vm_info", ".", "category", ")", "if", "len", "(", "valid_pm_list", ")", ">", "0", ":", "# Generate pending decision.", "decision_payload", "=", "DecisionPayload", "(", "frame_index", "=", "self", ".", "frame_index", "(", "tick", "=", "self", ".", "_tick", ")", ",", "valid_pms", "=", "valid_pm_list", ",", "vm_id", "=", "vm_info", ".", "id", ",", "vm_cpu_cores_requirement", "=", "vm_info", ".", "cpu_cores_requirement", ",", "vm_memory_requirement", "=", "vm_info", ".", "memory_requirement", ",", "vm_sub_id", "=", "vm_info", ".", "sub_id", ",", "vm_category", "=", "vm_info", ".", "category", ",", "remaining_buffer_time", "=", "remaining_buffer_time", ")", "self", ".", "_pending_action_vm_id", "=", "vm_info", ".", "id", "pending_decision_event", "=", "self", ".", "_event_buffer", ".", "gen_decision_event", "(", "tick", "=", "vm_request_event", ".", "tick", ",", "payload", "=", "decision_payload", ")", "vm_request_event", ".", "add_immediate_event", "(", "event", "=", "pending_decision_event", ")", "else", ":", "# Either postpone the requirement event or failed.", "self", ".", "_postpone_vm_request", "(", "postpone_type", "=", "PostponeType", ".", "Resource", ",", "vm_id", "=", "vm_info", ".", "id", ",", "remaining_buffer_time", "=", "remaining_buffer_time", ")" ]
[ 808, 4 ]
[ 846, 13 ]
python
en
['en', 'en', 'en']
True
VmSchedulingBusinessEngine._on_action_received
(self, event: CascadeEvent)
Callback wen we get an action from agent.
Callback wen we get an action from agent.
def _on_action_received(self, event: CascadeEvent): """Callback wen we get an action from agent.""" action = None if event is None or event.payload is None: self._pending_vm_request_payload.pop(self._pending_action_vm_id) return cur_tick: int = event.tick for action in event.payload: vm_id: int = action.vm_id if vm_id not in self._pending_vm_request_payload: raise Exception(f"The VM id: '{vm_id}' sent by agent is invalid.") if type(action) == AllocateAction: pm_id = action.pm_id vm: VirtualMachine = self._pending_vm_request_payload[vm_id].vm_info lifetime = vm.lifetime # Update VM information. vm.pm_id = pm_id vm.creation_tick = cur_tick vm.deletion_tick = cur_tick + lifetime vm.cpu_utilization = vm.get_utilization(cur_tick=cur_tick) # Pop out the VM from pending requests and add to live VM dict. self._pending_vm_request_payload.pop(vm_id) self._live_vms[vm_id] = vm # Update PM resources requested by VM. pm = self._machines[pm_id] # Empty pm (init state). if pm.oversubscribable == PmState.EMPTY: # Delay-Insensitive: oversubscribable. if vm.category == VmCategory.DELAY_INSENSITIVE: pm.oversubscribable = PmState.OVERSUBSCRIBABLE # Interactive or Unknown: non-oversubscribable else: pm.oversubscribable = PmState.NON_OVERSUBSCRIBABLE pm.allocate_vms(vm_ids=[vm.id]) pm.cpu_cores_allocated += vm.cpu_cores_requirement pm.memory_allocated += vm.memory_requirement pm.update_cpu_utilization( vm=vm, cpu_utilization=None ) pm.energy_consumption = self._cpu_utilization_to_energy_consumption( pm_type=self._pm_config_dict[pm.pm_type], cpu_utilization=pm.cpu_utilization ) self._successful_allocation += 1 elif type(action) == PostponeAction: postpone_step = action.postpone_step remaining_buffer_time = self._pending_vm_request_payload[vm_id].remaining_buffer_time # Either postpone the requirement event or failed. self._postpone_vm_request( postpone_type=PostponeType.Agent, vm_id=vm_id, remaining_buffer_time=remaining_buffer_time - postpone_step * self._delay_duration )
[ "def", "_on_action_received", "(", "self", ",", "event", ":", "CascadeEvent", ")", ":", "action", "=", "None", "if", "event", "is", "None", "or", "event", ".", "payload", "is", "None", ":", "self", ".", "_pending_vm_request_payload", ".", "pop", "(", "self", ".", "_pending_action_vm_id", ")", "return", "cur_tick", ":", "int", "=", "event", ".", "tick", "for", "action", "in", "event", ".", "payload", ":", "vm_id", ":", "int", "=", "action", ".", "vm_id", "if", "vm_id", "not", "in", "self", ".", "_pending_vm_request_payload", ":", "raise", "Exception", "(", "f\"The VM id: '{vm_id}' sent by agent is invalid.\"", ")", "if", "type", "(", "action", ")", "==", "AllocateAction", ":", "pm_id", "=", "action", ".", "pm_id", "vm", ":", "VirtualMachine", "=", "self", ".", "_pending_vm_request_payload", "[", "vm_id", "]", ".", "vm_info", "lifetime", "=", "vm", ".", "lifetime", "# Update VM information.", "vm", ".", "pm_id", "=", "pm_id", "vm", ".", "creation_tick", "=", "cur_tick", "vm", ".", "deletion_tick", "=", "cur_tick", "+", "lifetime", "vm", ".", "cpu_utilization", "=", "vm", ".", "get_utilization", "(", "cur_tick", "=", "cur_tick", ")", "# Pop out the VM from pending requests and add to live VM dict.", "self", ".", "_pending_vm_request_payload", ".", "pop", "(", "vm_id", ")", "self", ".", "_live_vms", "[", "vm_id", "]", "=", "vm", "# Update PM resources requested by VM.", "pm", "=", "self", ".", "_machines", "[", "pm_id", "]", "# Empty pm (init state).", "if", "pm", ".", "oversubscribable", "==", "PmState", ".", "EMPTY", ":", "# Delay-Insensitive: oversubscribable.", "if", "vm", ".", "category", "==", "VmCategory", ".", "DELAY_INSENSITIVE", ":", "pm", ".", "oversubscribable", "=", "PmState", ".", "OVERSUBSCRIBABLE", "# Interactive or Unknown: non-oversubscribable", "else", ":", "pm", ".", "oversubscribable", "=", "PmState", ".", "NON_OVERSUBSCRIBABLE", "pm", ".", "allocate_vms", "(", "vm_ids", "=", "[", "vm", ".", "id", "]", ")", "pm", ".", "cpu_cores_allocated", "+=", "vm", ".", "cpu_cores_requirement", "pm", ".", "memory_allocated", "+=", "vm", ".", "memory_requirement", "pm", ".", "update_cpu_utilization", "(", "vm", "=", "vm", ",", "cpu_utilization", "=", "None", ")", "pm", ".", "energy_consumption", "=", "self", ".", "_cpu_utilization_to_energy_consumption", "(", "pm_type", "=", "self", ".", "_pm_config_dict", "[", "pm", ".", "pm_type", "]", ",", "cpu_utilization", "=", "pm", ".", "cpu_utilization", ")", "self", ".", "_successful_allocation", "+=", "1", "elif", "type", "(", "action", ")", "==", "PostponeAction", ":", "postpone_step", "=", "action", ".", "postpone_step", "remaining_buffer_time", "=", "self", ".", "_pending_vm_request_payload", "[", "vm_id", "]", ".", "remaining_buffer_time", "# Either postpone the requirement event or failed.", "self", ".", "_postpone_vm_request", "(", "postpone_type", "=", "PostponeType", ".", "Agent", ",", "vm_id", "=", "vm_id", ",", "remaining_buffer_time", "=", "remaining_buffer_time", "-", "postpone_step", "*", "self", ".", "_delay_duration", ")" ]
[ 848, 4 ]
[ 911, 17 ]
python
en
['en', 'en', 'en']
True
VmSchedulingBusinessEngine._download_processed_data
(self)
Build processed data.
Build processed data.
def _download_processed_data(self): """Build processed data.""" data_root = StaticParameter.data_root build_folder = os.path.join(data_root, self._scenario_name, ".build", self._topology) source = self._config.PROCESSED_DATA_URL download_file_name = source.split('/')[-1] download_file_path = os.path.join(build_folder, download_file_name) # Download file from the Azure blob storage. if not os.path.exists(download_file_path): logger.info_green(f"Downloading data from {source} to {download_file_path}.") download_file(source=source, destination=download_file_path) else: logger.info_green("File already exists, skipping download.") # Unzip files. logger.info_green(f"Unzip {download_file_path} to {build_folder}") tar = tarfile.open(download_file_path, "r:gz") tar.extractall(path=build_folder) tar.close() # Move to the correct path. for _, directories, _ in os.walk(build_folder): for directory in directories: unzip_file = os.path.join(build_folder, directory) logger.info_green(f"Move files to {build_folder} from {unzip_file}") for file_name in os.listdir(unzip_file): if file_name.endswith(".bin"): shutil.move(os.path.join(unzip_file, file_name), build_folder) os.rmdir(unzip_file)
[ "def", "_download_processed_data", "(", "self", ")", ":", "data_root", "=", "StaticParameter", ".", "data_root", "build_folder", "=", "os", ".", "path", ".", "join", "(", "data_root", ",", "self", ".", "_scenario_name", ",", "\".build\"", ",", "self", ".", "_topology", ")", "source", "=", "self", ".", "_config", ".", "PROCESSED_DATA_URL", "download_file_name", "=", "source", ".", "split", "(", "'/'", ")", "[", "-", "1", "]", "download_file_path", "=", "os", ".", "path", ".", "join", "(", "build_folder", ",", "download_file_name", ")", "# Download file from the Azure blob storage.", "if", "not", "os", ".", "path", ".", "exists", "(", "download_file_path", ")", ":", "logger", ".", "info_green", "(", "f\"Downloading data from {source} to {download_file_path}.\"", ")", "download_file", "(", "source", "=", "source", ",", "destination", "=", "download_file_path", ")", "else", ":", "logger", ".", "info_green", "(", "\"File already exists, skipping download.\"", ")", "# Unzip files.", "logger", ".", "info_green", "(", "f\"Unzip {download_file_path} to {build_folder}\"", ")", "tar", "=", "tarfile", ".", "open", "(", "download_file_path", ",", "\"r:gz\"", ")", "tar", ".", "extractall", "(", "path", "=", "build_folder", ")", "tar", ".", "close", "(", ")", "# Move to the correct path.", "for", "_", ",", "directories", ",", "_", "in", "os", ".", "walk", "(", "build_folder", ")", ":", "for", "directory", "in", "directories", ":", "unzip_file", "=", "os", ".", "path", ".", "join", "(", "build_folder", ",", "directory", ")", "logger", ".", "info_green", "(", "f\"Move files to {build_folder} from {unzip_file}\"", ")", "for", "file_name", "in", "os", ".", "listdir", "(", "unzip_file", ")", ":", "if", "file_name", ".", "endswith", "(", "\".bin\"", ")", ":", "shutil", ".", "move", "(", "os", ".", "path", ".", "join", "(", "unzip_file", ",", "file_name", ")", ",", "build_folder", ")", "os", ".", "rmdir", "(", "unzip_file", ")" ]
[ 926, 4 ]
[ 957, 28 ]
python
en
['en', 'la', 'en']
True
PulseHub.__init__
(self, hass, config_entry)
Initialize the system.
Initialize the system.
def __init__(self, hass, config_entry): """Initialize the system.""" self.config_entry = config_entry self.hass = hass self.api: Optional[aiopulse.Hub] = None self.tasks = [] self.current_rollers = {} self.cleanup_callbacks = []
[ "def", "__init__", "(", "self", ",", "hass", ",", "config_entry", ")", ":", "self", ".", "config_entry", "=", "config_entry", "self", ".", "hass", "=", "hass", "self", ".", "api", ":", "Optional", "[", "aiopulse", ".", "Hub", "]", "=", "None", "self", ".", "tasks", "=", "[", "]", "self", ".", "current_rollers", "=", "{", "}", "self", ".", "cleanup_callbacks", "=", "[", "]" ]
[ 15, 4 ]
[ 22, 35 ]
python
en
['en', 'en', 'en']
True
PulseHub.title
(self)
Return the title of the hub shown in the integrations list.
Return the title of the hub shown in the integrations list.
def title(self): """Return the title of the hub shown in the integrations list.""" return f"{self.api.id} ({self.api.host})"
[ "def", "title", "(", "self", ")", ":", "return", "f\"{self.api.id} ({self.api.host})\"" ]
[ 25, 4 ]
[ 27, 49 ]
python
en
['en', 'en', 'en']
True
PulseHub.host
(self)
Return the host of this hub.
Return the host of this hub.
def host(self): """Return the host of this hub.""" return self.config_entry.data["host"]
[ "def", "host", "(", "self", ")", ":", "return", "self", ".", "config_entry", ".", "data", "[", "\"host\"", "]" ]
[ 30, 4 ]
[ 32, 45 ]
python
en
['en', 'en', 'en']
True
PulseHub.async_setup
(self, tries=0)
Set up a hub based on host parameter.
Set up a hub based on host parameter.
async def async_setup(self, tries=0): """Set up a hub based on host parameter.""" host = self.host hub = aiopulse.Hub(host) self.api = hub hub.callback_subscribe(self.async_notify_update) self.tasks.append(asyncio.create_task(hub.run())) LOGGER.debug("Hub setup complete") return True
[ "async", "def", "async_setup", "(", "self", ",", "tries", "=", "0", ")", ":", "host", "=", "self", ".", "host", "hub", "=", "aiopulse", ".", "Hub", "(", "host", ")", "self", ".", "api", "=", "hub", "hub", ".", "callback_subscribe", "(", "self", ".", "async_notify_update", ")", "self", ".", "tasks", ".", "append", "(", "asyncio", ".", "create_task", "(", "hub", ".", "run", "(", ")", ")", ")", "LOGGER", ".", "debug", "(", "\"Hub setup complete\"", ")", "return", "True" ]
[ 34, 4 ]
[ 45, 19 ]
python
en
['en', 'da', 'en']
True
PulseHub.async_reset
(self)
Reset this hub to default state.
Reset this hub to default state.
async def async_reset(self): """Reset this hub to default state.""" for cleanup_callback in self.cleanup_callbacks: cleanup_callback() # If not setup if self.api is None: return False self.api.callback_unsubscribe(self.async_notify_update) await self.api.stop() del self.api self.api = None # Wait for any running tasks to complete await asyncio.wait(self.tasks) return True
[ "async", "def", "async_reset", "(", "self", ")", ":", "for", "cleanup_callback", "in", "self", ".", "cleanup_callbacks", ":", "cleanup_callback", "(", ")", "# If not setup", "if", "self", ".", "api", "is", "None", ":", "return", "False", "self", ".", "api", ".", "callback_unsubscribe", "(", "self", ".", "async_notify_update", ")", "await", "self", ".", "api", ".", "stop", "(", ")", "del", "self", ".", "api", "self", ".", "api", "=", "None", "# Wait for any running tasks to complete", "await", "asyncio", ".", "wait", "(", "self", ".", "tasks", ")", "return", "True" ]
[ 47, 4 ]
[ 65, 19 ]
python
en
['en', 'en', 'en']
True
PulseHub.async_notify_update
(self, update_type)
Evaluate entities when hub reports that update has occurred.
Evaluate entities when hub reports that update has occurred.
async def async_notify_update(self, update_type): """Evaluate entities when hub reports that update has occurred.""" LOGGER.debug("Hub {update_type.name} updated") if update_type == aiopulse.UpdateType.rollers: await update_devices(self.hass, self.config_entry, self.api.rollers) self.hass.config_entries.async_update_entry( self.config_entry, title=self.title ) async_dispatcher_send( self.hass, ACMEDA_HUB_UPDATE.format(self.config_entry.entry_id) ) for unique_id in list(self.current_rollers): if unique_id not in self.api.rollers: LOGGER.debug("Notifying remove of %s", unique_id) self.current_rollers.pop(unique_id) async_dispatcher_send( self.hass, ACMEDA_ENTITY_REMOVE.format(unique_id) )
[ "async", "def", "async_notify_update", "(", "self", ",", "update_type", ")", ":", "LOGGER", ".", "debug", "(", "\"Hub {update_type.name} updated\"", ")", "if", "update_type", "==", "aiopulse", ".", "UpdateType", ".", "rollers", ":", "await", "update_devices", "(", "self", ".", "hass", ",", "self", ".", "config_entry", ",", "self", ".", "api", ".", "rollers", ")", "self", ".", "hass", ".", "config_entries", ".", "async_update_entry", "(", "self", ".", "config_entry", ",", "title", "=", "self", ".", "title", ")", "async_dispatcher_send", "(", "self", ".", "hass", ",", "ACMEDA_HUB_UPDATE", ".", "format", "(", "self", ".", "config_entry", ".", "entry_id", ")", ")", "for", "unique_id", "in", "list", "(", "self", ".", "current_rollers", ")", ":", "if", "unique_id", "not", "in", "self", ".", "api", ".", "rollers", ":", "LOGGER", ".", "debug", "(", "\"Notifying remove of %s\"", ",", "unique_id", ")", "self", ".", "current_rollers", ".", "pop", "(", "unique_id", ")", "async_dispatcher_send", "(", "self", ".", "hass", ",", "ACMEDA_ENTITY_REMOVE", ".", "format", "(", "unique_id", ")", ")" ]
[ 67, 4 ]
[ 87, 21 ]
python
en
['en', 'en', 'en']
True
async_setup_platform
(hass, config, async_add_entities, discovery_info=None)
Set up the Demo water_heater devices.
Set up the Demo water_heater devices.
async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Set up the Demo water_heater devices.""" async_add_entities( [ DemoWaterHeater("Demo Water Heater", 119, TEMP_FAHRENHEIT, False, "eco"), DemoWaterHeater("Demo Water Heater Celsius", 45, TEMP_CELSIUS, True, "eco"), ] )
[ "async", "def", "async_setup_platform", "(", "hass", ",", "config", ",", "async_add_entities", ",", "discovery_info", "=", "None", ")", ":", "async_add_entities", "(", "[", "DemoWaterHeater", "(", "\"Demo Water Heater\"", ",", "119", ",", "TEMP_FAHRENHEIT", ",", "False", ",", "\"eco\"", ")", ",", "DemoWaterHeater", "(", "\"Demo Water Heater Celsius\"", ",", "45", ",", "TEMP_CELSIUS", ",", "True", ",", "\"eco\"", ")", ",", "]", ")" ]
[ 14, 0 ]
[ 21, 5 ]
python
en
['en', 'en', 'en']
True
async_setup_entry
(hass, config_entry, async_add_entities)
Set up the Demo config entry.
Set up the Demo config entry.
async def async_setup_entry(hass, config_entry, async_add_entities): """Set up the Demo config entry.""" await async_setup_platform(hass, {}, async_add_entities)
[ "async", "def", "async_setup_entry", "(", "hass", ",", "config_entry", ",", "async_add_entities", ")", ":", "await", "async_setup_platform", "(", "hass", ",", "{", "}", ",", "async_add_entities", ")" ]
[ 24, 0 ]
[ 26, 60 ]
python
en
['en', 'en', 'en']
True
DemoWaterHeater.__init__
( self, name, target_temperature, unit_of_measurement, away, current_operation )
Initialize the water_heater device.
Initialize the water_heater device.
def __init__( self, name, target_temperature, unit_of_measurement, away, current_operation ): """Initialize the water_heater device.""" self._name = name self._support_flags = SUPPORT_FLAGS_HEATER if target_temperature is not None: self._support_flags = self._support_flags | SUPPORT_TARGET_TEMPERATURE if away is not None: self._support_flags = self._support_flags | SUPPORT_AWAY_MODE if current_operation is not None: self._support_flags = self._support_flags | SUPPORT_OPERATION_MODE self._target_temperature = target_temperature self._unit_of_measurement = unit_of_measurement self._away = away self._current_operation = current_operation self._operation_list = [ "eco", "electric", "performance", "high_demand", "heat_pump", "gas", "off", ]
[ "def", "__init__", "(", "self", ",", "name", ",", "target_temperature", ",", "unit_of_measurement", ",", "away", ",", "current_operation", ")", ":", "self", ".", "_name", "=", "name", "self", ".", "_support_flags", "=", "SUPPORT_FLAGS_HEATER", "if", "target_temperature", "is", "not", "None", ":", "self", ".", "_support_flags", "=", "self", ".", "_support_flags", "|", "SUPPORT_TARGET_TEMPERATURE", "if", "away", "is", "not", "None", ":", "self", ".", "_support_flags", "=", "self", ".", "_support_flags", "|", "SUPPORT_AWAY_MODE", "if", "current_operation", "is", "not", "None", ":", "self", ".", "_support_flags", "=", "self", ".", "_support_flags", "|", "SUPPORT_OPERATION_MODE", "self", ".", "_target_temperature", "=", "target_temperature", "self", ".", "_unit_of_measurement", "=", "unit_of_measurement", "self", ".", "_away", "=", "away", "self", ".", "_current_operation", "=", "current_operation", "self", ".", "_operation_list", "=", "[", "\"eco\"", ",", "\"electric\"", ",", "\"performance\"", ",", "\"high_demand\"", ",", "\"heat_pump\"", ",", "\"gas\"", ",", "\"off\"", ",", "]" ]
[ 32, 4 ]
[ 56, 9 ]
python
en
['en', 'en', 'en']
True
DemoWaterHeater.supported_features
(self)
Return the list of supported features.
Return the list of supported features.
def supported_features(self): """Return the list of supported features.""" return self._support_flags
[ "def", "supported_features", "(", "self", ")", ":", "return", "self", ".", "_support_flags" ]
[ 59, 4 ]
[ 61, 34 ]
python
en
['en', 'en', 'en']
True
DemoWaterHeater.should_poll
(self)
Return the polling state.
Return the polling state.
def should_poll(self): """Return the polling state.""" return False
[ "def", "should_poll", "(", "self", ")", ":", "return", "False" ]
[ 64, 4 ]
[ 66, 20 ]
python
en
['en', 'en', 'en']
True
DemoWaterHeater.name
(self)
Return the name of the water_heater device.
Return the name of the water_heater device.
def name(self): """Return the name of the water_heater device.""" return self._name
[ "def", "name", "(", "self", ")", ":", "return", "self", ".", "_name" ]
[ 69, 4 ]
[ 71, 25 ]
python
en
['en', 'en', 'en']
True
DemoWaterHeater.temperature_unit
(self)
Return the unit of measurement.
Return the unit of measurement.
def temperature_unit(self): """Return the unit of measurement.""" return self._unit_of_measurement
[ "def", "temperature_unit", "(", "self", ")", ":", "return", "self", ".", "_unit_of_measurement" ]
[ 74, 4 ]
[ 76, 40 ]
python
en
['en', 'la', 'en']
True
DemoWaterHeater.target_temperature
(self)
Return the temperature we try to reach.
Return the temperature we try to reach.
def target_temperature(self): """Return the temperature we try to reach.""" return self._target_temperature
[ "def", "target_temperature", "(", "self", ")", ":", "return", "self", ".", "_target_temperature" ]
[ 79, 4 ]
[ 81, 39 ]
python
en
['en', 'en', 'en']
True
DemoWaterHeater.current_operation
(self)
Return current operation ie. heat, cool, idle.
Return current operation ie. heat, cool, idle.
def current_operation(self): """Return current operation ie. heat, cool, idle.""" return self._current_operation
[ "def", "current_operation", "(", "self", ")", ":", "return", "self", ".", "_current_operation" ]
[ 84, 4 ]
[ 86, 38 ]
python
en
['nl', 'en', 'en']
True
DemoWaterHeater.operation_list
(self)
Return the list of available operation modes.
Return the list of available operation modes.
def operation_list(self): """Return the list of available operation modes.""" return self._operation_list
[ "def", "operation_list", "(", "self", ")", ":", "return", "self", ".", "_operation_list" ]
[ 89, 4 ]
[ 91, 35 ]
python
en
['en', 'en', 'en']
True
DemoWaterHeater.is_away_mode_on
(self)
Return if away mode is on.
Return if away mode is on.
def is_away_mode_on(self): """Return if away mode is on.""" return self._away
[ "def", "is_away_mode_on", "(", "self", ")", ":", "return", "self", ".", "_away" ]
[ 94, 4 ]
[ 96, 25 ]
python
en
['en', 'en', 'en']
True
DemoWaterHeater.set_temperature
(self, **kwargs)
Set new target temperatures.
Set new target temperatures.
def set_temperature(self, **kwargs): """Set new target temperatures.""" self._target_temperature = kwargs.get(ATTR_TEMPERATURE) self.schedule_update_ha_state()
[ "def", "set_temperature", "(", "self", ",", "*", "*", "kwargs", ")", ":", "self", ".", "_target_temperature", "=", "kwargs", ".", "get", "(", "ATTR_TEMPERATURE", ")", "self", ".", "schedule_update_ha_state", "(", ")" ]
[ 98, 4 ]
[ 101, 39 ]
python
en
['en', 'ca', 'en']
True
DemoWaterHeater.set_operation_mode
(self, operation_mode)
Set new operation mode.
Set new operation mode.
def set_operation_mode(self, operation_mode): """Set new operation mode.""" self._current_operation = operation_mode self.schedule_update_ha_state()
[ "def", "set_operation_mode", "(", "self", ",", "operation_mode", ")", ":", "self", ".", "_current_operation", "=", "operation_mode", "self", ".", "schedule_update_ha_state", "(", ")" ]
[ 103, 4 ]
[ 106, 39 ]
python
en
['en', 'ny', 'en']
True
DemoWaterHeater.turn_away_mode_on
(self)
Turn away mode on.
Turn away mode on.
def turn_away_mode_on(self): """Turn away mode on.""" self._away = True self.schedule_update_ha_state()
[ "def", "turn_away_mode_on", "(", "self", ")", ":", "self", ".", "_away", "=", "True", "self", ".", "schedule_update_ha_state", "(", ")" ]
[ 108, 4 ]
[ 111, 39 ]
python
en
['en', 'yo', 'en']
True
DemoWaterHeater.turn_away_mode_off
(self)
Turn away mode off.
Turn away mode off.
def turn_away_mode_off(self): """Turn away mode off.""" self._away = False self.schedule_update_ha_state()
[ "def", "turn_away_mode_off", "(", "self", ")", ":", "self", ".", "_away", "=", "False", "self", ".", "schedule_update_ha_state", "(", ")" ]
[ 113, 4 ]
[ 116, 39 ]
python
en
['en', 'yo', 'en']
True
async_setup_platform
( hass, hass_config, async_add_entities, discovery_info=None )
Set up the LCN scene platform.
Set up the LCN scene platform.
async def async_setup_platform( hass, hass_config, async_add_entities, discovery_info=None ): """Set up the LCN scene platform.""" if discovery_info is None: return devices = [] for config in discovery_info: address, connection_id = config[CONF_ADDRESS] addr = pypck.lcn_addr.LcnAddr(*address) connections = hass.data[DATA_LCN][CONF_CONNECTIONS] connection = get_connection(connections, connection_id) address_connection = connection.get_address_conn(addr) devices.append(LcnScene(config, address_connection)) async_add_entities(devices)
[ "async", "def", "async_setup_platform", "(", "hass", ",", "hass_config", ",", "async_add_entities", ",", "discovery_info", "=", "None", ")", ":", "if", "discovery_info", "is", "None", ":", "return", "devices", "=", "[", "]", "for", "config", "in", "discovery_info", ":", "address", ",", "connection_id", "=", "config", "[", "CONF_ADDRESS", "]", "addr", "=", "pypck", ".", "lcn_addr", ".", "LcnAddr", "(", "*", "address", ")", "connections", "=", "hass", ".", "data", "[", "DATA_LCN", "]", "[", "CONF_CONNECTIONS", "]", "connection", "=", "get_connection", "(", "connections", ",", "connection_id", ")", "address_connection", "=", "connection", ".", "get_address_conn", "(", "addr", ")", "devices", ".", "append", "(", "LcnScene", "(", "config", ",", "address_connection", ")", ")", "async_add_entities", "(", "devices", ")" ]
[ 21, 0 ]
[ 38, 31 ]
python
en
['en', 'da', 'en']
True
LcnScene.__init__
(self, config, address_connection)
Initialize the LCN scene.
Initialize the LCN scene.
def __init__(self, config, address_connection): """Initialize the LCN scene.""" super().__init__(config, address_connection) self.register_id = config[CONF_REGISTER] self.scene_id = config[CONF_SCENE] self.output_ports = [] self.relay_ports = [] for port in config[CONF_OUTPUTS]: if port in OUTPUT_PORTS: self.output_ports.append(pypck.lcn_defs.OutputPort[port]) else: # in RELEAY_PORTS self.relay_ports.append(pypck.lcn_defs.RelayPort[port]) if config[CONF_TRANSITION] is None: self.transition = None else: self.transition = pypck.lcn_defs.time_to_ramp_value(config[CONF_TRANSITION])
[ "def", "__init__", "(", "self", ",", "config", ",", "address_connection", ")", ":", "super", "(", ")", ".", "__init__", "(", "config", ",", "address_connection", ")", "self", ".", "register_id", "=", "config", "[", "CONF_REGISTER", "]", "self", ".", "scene_id", "=", "config", "[", "CONF_SCENE", "]", "self", ".", "output_ports", "=", "[", "]", "self", ".", "relay_ports", "=", "[", "]", "for", "port", "in", "config", "[", "CONF_OUTPUTS", "]", ":", "if", "port", "in", "OUTPUT_PORTS", ":", "self", ".", "output_ports", ".", "append", "(", "pypck", ".", "lcn_defs", ".", "OutputPort", "[", "port", "]", ")", "else", ":", "# in RELEAY_PORTS", "self", ".", "relay_ports", ".", "append", "(", "pypck", ".", "lcn_defs", ".", "RelayPort", "[", "port", "]", ")", "if", "config", "[", "CONF_TRANSITION", "]", "is", "None", ":", "self", ".", "transition", "=", "None", "else", ":", "self", ".", "transition", "=", "pypck", ".", "lcn_defs", ".", "time_to_ramp_value", "(", "config", "[", "CONF_TRANSITION", "]", ")" ]
[ 44, 4 ]
[ 62, 88 ]
python
en
['en', 'fy', 'en']
True
LcnScene.async_added_to_hass
(self)
Run when entity about to be added to hass.
Run when entity about to be added to hass.
async def async_added_to_hass(self): """Run when entity about to be added to hass."""
[ "async", "def", "async_added_to_hass", "(", "self", ")", ":" ]
[ 64, 4 ]
[ 65, 56 ]
python
en
['en', 'en', 'en']
True
LcnScene.async_activate
(self, **kwargs: Any)
Activate scene.
Activate scene.
async def async_activate(self, **kwargs: Any) -> None: """Activate scene.""" self.address_connection.activate_scene( self.register_id, self.scene_id, self.output_ports, self.relay_ports, self.transition, )
[ "async", "def", "async_activate", "(", "self", ",", "*", "*", "kwargs", ":", "Any", ")", "->", "None", ":", "self", ".", "address_connection", ".", "activate_scene", "(", "self", ".", "register_id", ",", "self", ".", "scene_id", ",", "self", ".", "output_ports", ",", "self", ".", "relay_ports", ",", "self", ".", "transition", ",", ")" ]
[ 67, 4 ]
[ 75, 9 ]
python
en
['it', 'la', 'en']
False
setup_platform
(hass, config, add_entities, discovery_info=None)
Set up the Dark Sky sensor.
Set up the Dark Sky sensor.
def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the Dark Sky sensor.""" latitude = config.get(CONF_LATITUDE, hass.config.latitude) longitude = config.get(CONF_LONGITUDE, hass.config.longitude) language = config.get(CONF_LANGUAGE) interval = config.get(CONF_SCAN_INTERVAL, SCAN_INTERVAL) if CONF_UNITS in config: units = config[CONF_UNITS] elif hass.config.units.is_metric: units = "si" else: units = "us" forecast_data = DarkSkyData( api_key=config.get(CONF_API_KEY), latitude=latitude, longitude=longitude, units=units, language=language, interval=interval, ) forecast_data.update() forecast_data.update_currently() # If connection failed don't setup platform. if forecast_data.data is None: return name = config.get(CONF_NAME) forecast = config.get(CONF_FORECAST) forecast_hour = config.get(CONF_HOURLY_FORECAST) sensors = [] for variable in config[CONF_MONITORED_CONDITIONS]: if variable in DEPRECATED_SENSOR_TYPES: _LOGGER.warning("Monitored condition %s is deprecated", variable) if not SENSOR_TYPES[variable][7] or "currently" in SENSOR_TYPES[variable][7]: if variable == "alerts": sensors.append(DarkSkyAlertSensor(forecast_data, variable, name)) else: sensors.append(DarkSkySensor(forecast_data, variable, name)) if forecast is not None and "daily" in SENSOR_TYPES[variable][7]: for forecast_day in forecast: sensors.append( DarkSkySensor( forecast_data, variable, name, forecast_day=forecast_day ) ) if forecast_hour is not None and "hourly" in SENSOR_TYPES[variable][7]: for forecast_h in forecast_hour: sensors.append( DarkSkySensor( forecast_data, variable, name, forecast_hour=forecast_h ) ) add_entities(sensors, True)
[ "def", "setup_platform", "(", "hass", ",", "config", ",", "add_entities", ",", "discovery_info", "=", "None", ")", ":", "latitude", "=", "config", ".", "get", "(", "CONF_LATITUDE", ",", "hass", ".", "config", ".", "latitude", ")", "longitude", "=", "config", ".", "get", "(", "CONF_LONGITUDE", ",", "hass", ".", "config", ".", "longitude", ")", "language", "=", "config", ".", "get", "(", "CONF_LANGUAGE", ")", "interval", "=", "config", ".", "get", "(", "CONF_SCAN_INTERVAL", ",", "SCAN_INTERVAL", ")", "if", "CONF_UNITS", "in", "config", ":", "units", "=", "config", "[", "CONF_UNITS", "]", "elif", "hass", ".", "config", ".", "units", ".", "is_metric", ":", "units", "=", "\"si\"", "else", ":", "units", "=", "\"us\"", "forecast_data", "=", "DarkSkyData", "(", "api_key", "=", "config", ".", "get", "(", "CONF_API_KEY", ")", ",", "latitude", "=", "latitude", ",", "longitude", "=", "longitude", ",", "units", "=", "units", ",", "language", "=", "language", ",", "interval", "=", "interval", ",", ")", "forecast_data", ".", "update", "(", ")", "forecast_data", ".", "update_currently", "(", ")", "# If connection failed don't setup platform.", "if", "forecast_data", ".", "data", "is", "None", ":", "return", "name", "=", "config", ".", "get", "(", "CONF_NAME", ")", "forecast", "=", "config", ".", "get", "(", "CONF_FORECAST", ")", "forecast_hour", "=", "config", ".", "get", "(", "CONF_HOURLY_FORECAST", ")", "sensors", "=", "[", "]", "for", "variable", "in", "config", "[", "CONF_MONITORED_CONDITIONS", "]", ":", "if", "variable", "in", "DEPRECATED_SENSOR_TYPES", ":", "_LOGGER", ".", "warning", "(", "\"Monitored condition %s is deprecated\"", ",", "variable", ")", "if", "not", "SENSOR_TYPES", "[", "variable", "]", "[", "7", "]", "or", "\"currently\"", "in", "SENSOR_TYPES", "[", "variable", "]", "[", "7", "]", ":", "if", "variable", "==", "\"alerts\"", ":", "sensors", ".", "append", "(", "DarkSkyAlertSensor", "(", "forecast_data", ",", "variable", ",", "name", ")", ")", "else", ":", "sensors", ".", "append", "(", "DarkSkySensor", "(", "forecast_data", ",", "variable", ",", "name", ")", ")", "if", "forecast", "is", "not", "None", "and", "\"daily\"", "in", "SENSOR_TYPES", "[", "variable", "]", "[", "7", "]", ":", "for", "forecast_day", "in", "forecast", ":", "sensors", ".", "append", "(", "DarkSkySensor", "(", "forecast_data", ",", "variable", ",", "name", ",", "forecast_day", "=", "forecast_day", ")", ")", "if", "forecast_hour", "is", "not", "None", "and", "\"hourly\"", "in", "SENSOR_TYPES", "[", "variable", "]", "[", "7", "]", ":", "for", "forecast_h", "in", "forecast_hour", ":", "sensors", ".", "append", "(", "DarkSkySensor", "(", "forecast_data", ",", "variable", ",", "name", ",", "forecast_hour", "=", "forecast_h", ")", ")", "add_entities", "(", "sensors", ",", "True", ")" ]
[ 485, 0 ]
[ 543, 31 ]
python
en
['en', 'bs', 'en']
True
convert_to_camel
(data)
Convert snake case (foo_bar_bat) to camel case (fooBarBat). This is not pythonic, but needed for certain situations.
Convert snake case (foo_bar_bat) to camel case (fooBarBat).
def convert_to_camel(data): """ Convert snake case (foo_bar_bat) to camel case (fooBarBat). This is not pythonic, but needed for certain situations. """ components = data.split("_") capital_components = "".join(x.title() for x in components[1:]) return f"{components[0]}{capital_components}"
[ "def", "convert_to_camel", "(", "data", ")", ":", "components", "=", "data", ".", "split", "(", "\"_\"", ")", "capital_components", "=", "\"\"", ".", "join", "(", "x", ".", "title", "(", ")", "for", "x", "in", "components", "[", "1", ":", "]", ")", "return", "f\"{components[0]}{capital_components}\"" ]
[ 780, 0 ]
[ 788, 49 ]
python
en
['en', 'error', 'th']
False
DarkSkySensor.__init__
( self, forecast_data, sensor_type, name, forecast_day=None, forecast_hour=None )
Initialize the sensor.
Initialize the sensor.
def __init__( self, forecast_data, sensor_type, name, forecast_day=None, forecast_hour=None ): """Initialize the sensor.""" self.client_name = name self._name = SENSOR_TYPES[sensor_type][0] self.forecast_data = forecast_data self.type = sensor_type self.forecast_day = forecast_day self.forecast_hour = forecast_hour self._state = None self._icon = None self._unit_of_measurement = None
[ "def", "__init__", "(", "self", ",", "forecast_data", ",", "sensor_type", ",", "name", ",", "forecast_day", "=", "None", ",", "forecast_hour", "=", "None", ")", ":", "self", ".", "client_name", "=", "name", "self", ".", "_name", "=", "SENSOR_TYPES", "[", "sensor_type", "]", "[", "0", "]", "self", ".", "forecast_data", "=", "forecast_data", "self", ".", "type", "=", "sensor_type", "self", ".", "forecast_day", "=", "forecast_day", "self", ".", "forecast_hour", "=", "forecast_hour", "self", ".", "_state", "=", "None", "self", ".", "_icon", "=", "None", "self", ".", "_unit_of_measurement", "=", "None" ]
[ 549, 4 ]
[ 561, 40 ]
python
en
['en', 'en', 'en']
True
DarkSkySensor.name
(self)
Return the name of the sensor.
Return the name of the sensor.
def name(self): """Return the name of the sensor.""" if self.forecast_day is not None: return f"{self.client_name} {self._name} {self.forecast_day}d" if self.forecast_hour is not None: return f"{self.client_name} {self._name} {self.forecast_hour}h" return f"{self.client_name} {self._name}"
[ "def", "name", "(", "self", ")", ":", "if", "self", ".", "forecast_day", "is", "not", "None", ":", "return", "f\"{self.client_name} {self._name} {self.forecast_day}d\"", "if", "self", ".", "forecast_hour", "is", "not", "None", ":", "return", "f\"{self.client_name} {self._name} {self.forecast_hour}h\"", "return", "f\"{self.client_name} {self._name}\"" ]
[ 564, 4 ]
[ 570, 49 ]
python
en
['en', 'mi', 'en']
True
DarkSkySensor.state
(self)
Return the state of the sensor.
Return the state of the sensor.
def state(self): """Return the state of the sensor.""" return self._state
[ "def", "state", "(", "self", ")", ":", "return", "self", ".", "_state" ]
[ 573, 4 ]
[ 575, 26 ]
python
en
['en', 'en', 'en']
True
DarkSkySensor.unit_of_measurement
(self)
Return the unit of measurement of this entity, if any.
Return the unit of measurement of this entity, if any.
def unit_of_measurement(self): """Return the unit of measurement of this entity, if any.""" return self._unit_of_measurement
[ "def", "unit_of_measurement", "(", "self", ")", ":", "return", "self", ".", "_unit_of_measurement" ]
[ 578, 4 ]
[ 580, 40 ]
python
en
['en', 'en', 'en']
True
DarkSkySensor.unit_system
(self)
Return the unit system of this entity.
Return the unit system of this entity.
def unit_system(self): """Return the unit system of this entity.""" return self.forecast_data.unit_system
[ "def", "unit_system", "(", "self", ")", ":", "return", "self", ".", "forecast_data", ".", "unit_system" ]
[ 583, 4 ]
[ 585, 45 ]
python
en
['en', 'en', 'en']
True
DarkSkySensor.entity_picture
(self)
Return the entity picture to use in the frontend, if any.
Return the entity picture to use in the frontend, if any.
def entity_picture(self): """Return the entity picture to use in the frontend, if any.""" if self._icon is None or "summary" not in self.type: return None if self._icon in CONDITION_PICTURES: return CONDITION_PICTURES[self._icon][0] return None
[ "def", "entity_picture", "(", "self", ")", ":", "if", "self", ".", "_icon", "is", "None", "or", "\"summary\"", "not", "in", "self", ".", "type", ":", "return", "None", "if", "self", ".", "_icon", "in", "CONDITION_PICTURES", ":", "return", "CONDITION_PICTURES", "[", "self", ".", "_icon", "]", "[", "0", "]", "return", "None" ]
[ 588, 4 ]
[ 596, 19 ]
python
en
['en', 'en', 'en']
True
DarkSkySensor.update_unit_of_measurement
(self)
Update units based on unit system.
Update units based on unit system.
def update_unit_of_measurement(self): """Update units based on unit system.""" unit_index = {"si": 1, "us": 2, "ca": 3, "uk": 4, "uk2": 5}.get( self.unit_system, 1 ) self._unit_of_measurement = SENSOR_TYPES[self.type][unit_index]
[ "def", "update_unit_of_measurement", "(", "self", ")", ":", "unit_index", "=", "{", "\"si\"", ":", "1", ",", "\"us\"", ":", "2", ",", "\"ca\"", ":", "3", ",", "\"uk\"", ":", "4", ",", "\"uk2\"", ":", "5", "}", ".", "get", "(", "self", ".", "unit_system", ",", "1", ")", "self", ".", "_unit_of_measurement", "=", "SENSOR_TYPES", "[", "self", ".", "type", "]", "[", "unit_index", "]" ]
[ 598, 4 ]
[ 603, 71 ]
python
en
['en', 'en', 'en']
True
DarkSkySensor.icon
(self)
Icon to use in the frontend, if any.
Icon to use in the frontend, if any.
def icon(self): """Icon to use in the frontend, if any.""" if "summary" in self.type and self._icon in CONDITION_PICTURES: return CONDITION_PICTURES[self._icon][1] return SENSOR_TYPES[self.type][6]
[ "def", "icon", "(", "self", ")", ":", "if", "\"summary\"", "in", "self", ".", "type", "and", "self", ".", "_icon", "in", "CONDITION_PICTURES", ":", "return", "CONDITION_PICTURES", "[", "self", ".", "_icon", "]", "[", "1", "]", "return", "SENSOR_TYPES", "[", "self", ".", "type", "]", "[", "6", "]" ]
[ 606, 4 ]
[ 611, 41 ]
python
en
['en', 'en', 'en']
True
DarkSkySensor.device_class
(self)
Device class of the entity.
Device class of the entity.
def device_class(self): """Device class of the entity.""" if SENSOR_TYPES[self.type][1] == TEMP_CELSIUS: return DEVICE_CLASS_TEMPERATURE return None
[ "def", "device_class", "(", "self", ")", ":", "if", "SENSOR_TYPES", "[", "self", ".", "type", "]", "[", "1", "]", "==", "TEMP_CELSIUS", ":", "return", "DEVICE_CLASS_TEMPERATURE", "return", "None" ]
[ 614, 4 ]
[ 619, 19 ]
python
en
['en', 'en', 'en']
True
DarkSkySensor.device_state_attributes
(self)
Return the state attributes.
Return the state attributes.
def device_state_attributes(self): """Return the state attributes.""" return {ATTR_ATTRIBUTION: ATTRIBUTION}
[ "def", "device_state_attributes", "(", "self", ")", ":", "return", "{", "ATTR_ATTRIBUTION", ":", "ATTRIBUTION", "}" ]
[ 622, 4 ]
[ 624, 46 ]
python
en
['en', 'en', 'en']
True
DarkSkySensor.update
(self)
Get the latest data from Dark Sky and updates the states.
Get the latest data from Dark Sky and updates the states.
def update(self): """Get the latest data from Dark Sky and updates the states.""" # Call the API for new forecast data. Each sensor will re-trigger this # same exact call, but that's fine. We cache results for a short period # of time to prevent hitting API limits. Note that Dark Sky will # charge users for too many calls in 1 day, so take care when updating. self.forecast_data.update() self.update_unit_of_measurement() if self.type == "minutely_summary": self.forecast_data.update_minutely() minutely = self.forecast_data.data_minutely self._state = getattr(minutely, "summary", "") self._icon = getattr(minutely, "icon", "") elif self.type == "hourly_summary": self.forecast_data.update_hourly() hourly = self.forecast_data.data_hourly self._state = getattr(hourly, "summary", "") self._icon = getattr(hourly, "icon", "") elif self.forecast_hour is not None: self.forecast_data.update_hourly() hourly = self.forecast_data.data_hourly if hasattr(hourly, "data"): self._state = self.get_state(hourly.data[self.forecast_hour]) else: self._state = 0 elif self.type == "daily_summary": self.forecast_data.update_daily() daily = self.forecast_data.data_daily self._state = getattr(daily, "summary", "") self._icon = getattr(daily, "icon", "") elif self.forecast_day is not None: self.forecast_data.update_daily() daily = self.forecast_data.data_daily if hasattr(daily, "data"): self._state = self.get_state(daily.data[self.forecast_day]) else: self._state = 0 else: self.forecast_data.update_currently() currently = self.forecast_data.data_currently self._state = self.get_state(currently)
[ "def", "update", "(", "self", ")", ":", "# Call the API for new forecast data. Each sensor will re-trigger this", "# same exact call, but that's fine. We cache results for a short period", "# of time to prevent hitting API limits. Note that Dark Sky will", "# charge users for too many calls in 1 day, so take care when updating.", "self", ".", "forecast_data", ".", "update", "(", ")", "self", ".", "update_unit_of_measurement", "(", ")", "if", "self", ".", "type", "==", "\"minutely_summary\"", ":", "self", ".", "forecast_data", ".", "update_minutely", "(", ")", "minutely", "=", "self", ".", "forecast_data", ".", "data_minutely", "self", ".", "_state", "=", "getattr", "(", "minutely", ",", "\"summary\"", ",", "\"\"", ")", "self", ".", "_icon", "=", "getattr", "(", "minutely", ",", "\"icon\"", ",", "\"\"", ")", "elif", "self", ".", "type", "==", "\"hourly_summary\"", ":", "self", ".", "forecast_data", ".", "update_hourly", "(", ")", "hourly", "=", "self", ".", "forecast_data", ".", "data_hourly", "self", ".", "_state", "=", "getattr", "(", "hourly", ",", "\"summary\"", ",", "\"\"", ")", "self", ".", "_icon", "=", "getattr", "(", "hourly", ",", "\"icon\"", ",", "\"\"", ")", "elif", "self", ".", "forecast_hour", "is", "not", "None", ":", "self", ".", "forecast_data", ".", "update_hourly", "(", ")", "hourly", "=", "self", ".", "forecast_data", ".", "data_hourly", "if", "hasattr", "(", "hourly", ",", "\"data\"", ")", ":", "self", ".", "_state", "=", "self", ".", "get_state", "(", "hourly", ".", "data", "[", "self", ".", "forecast_hour", "]", ")", "else", ":", "self", ".", "_state", "=", "0", "elif", "self", ".", "type", "==", "\"daily_summary\"", ":", "self", ".", "forecast_data", ".", "update_daily", "(", ")", "daily", "=", "self", ".", "forecast_data", ".", "data_daily", "self", ".", "_state", "=", "getattr", "(", "daily", ",", "\"summary\"", ",", "\"\"", ")", "self", ".", "_icon", "=", "getattr", "(", "daily", ",", "\"icon\"", ",", "\"\"", ")", "elif", "self", ".", "forecast_day", "is", "not", "None", ":", "self", ".", "forecast_data", ".", "update_daily", "(", ")", "daily", "=", "self", ".", "forecast_data", ".", "data_daily", "if", "hasattr", "(", "daily", ",", "\"data\"", ")", ":", "self", ".", "_state", "=", "self", ".", "get_state", "(", "daily", ".", "data", "[", "self", ".", "forecast_day", "]", ")", "else", ":", "self", ".", "_state", "=", "0", "else", ":", "self", ".", "forecast_data", ".", "update_currently", "(", ")", "currently", "=", "self", ".", "forecast_data", ".", "data_currently", "self", ".", "_state", "=", "self", ".", "get_state", "(", "currently", ")" ]
[ 626, 4 ]
[ 667, 51 ]
python
en
['en', 'en', 'en']
True
DarkSkySensor.get_state
(self, data)
Return a new state based on the type. If the sensor type is unknown, the current state is returned.
Return a new state based on the type.
def get_state(self, data): """ Return a new state based on the type. If the sensor type is unknown, the current state is returned. """ lookup_type = convert_to_camel(self.type) state = getattr(data, lookup_type, None) if state is None: return state if "summary" in self.type: self._icon = getattr(data, "icon", "") # Some state data needs to be rounded to whole values or converted to # percentages if self.type in ["precip_probability", "cloud_cover", "humidity"]: return round(state * 100, 1) if self.type in [ "dew_point", "temperature", "apparent_temperature", "temperature_low", "apparent_temperature_low", "temperature_min", "apparent_temperature_min", "temperature_high", "apparent_temperature_high", "temperature_max", "apparent_temperature_max", "precip_accumulation", "pressure", "ozone", "uvIndex", ]: return round(state, 1) return state
[ "def", "get_state", "(", "self", ",", "data", ")", ":", "lookup_type", "=", "convert_to_camel", "(", "self", ".", "type", ")", "state", "=", "getattr", "(", "data", ",", "lookup_type", ",", "None", ")", "if", "state", "is", "None", ":", "return", "state", "if", "\"summary\"", "in", "self", ".", "type", ":", "self", ".", "_icon", "=", "getattr", "(", "data", ",", "\"icon\"", ",", "\"\"", ")", "# Some state data needs to be rounded to whole values or converted to", "# percentages", "if", "self", ".", "type", "in", "[", "\"precip_probability\"", ",", "\"cloud_cover\"", ",", "\"humidity\"", "]", ":", "return", "round", "(", "state", "*", "100", ",", "1", ")", "if", "self", ".", "type", "in", "[", "\"dew_point\"", ",", "\"temperature\"", ",", "\"apparent_temperature\"", ",", "\"temperature_low\"", ",", "\"apparent_temperature_low\"", ",", "\"temperature_min\"", ",", "\"apparent_temperature_min\"", ",", "\"temperature_high\"", ",", "\"apparent_temperature_high\"", ",", "\"temperature_max\"", ",", "\"apparent_temperature_max\"", ",", "\"precip_accumulation\"", ",", "\"pressure\"", ",", "\"ozone\"", ",", "\"uvIndex\"", ",", "]", ":", "return", "round", "(", "state", ",", "1", ")", "return", "state" ]
[ 669, 4 ]
[ 707, 20 ]
python
en
['en', 'error', 'th']
False
DarkSkyAlertSensor.__init__
(self, forecast_data, sensor_type, name)
Initialize the sensor.
Initialize the sensor.
def __init__(self, forecast_data, sensor_type, name): """Initialize the sensor.""" self.client_name = name self._name = SENSOR_TYPES[sensor_type][0] self.forecast_data = forecast_data self.type = sensor_type self._state = None self._icon = None self._alerts = None
[ "def", "__init__", "(", "self", ",", "forecast_data", ",", "sensor_type", ",", "name", ")", ":", "self", ".", "client_name", "=", "name", "self", ".", "_name", "=", "SENSOR_TYPES", "[", "sensor_type", "]", "[", "0", "]", "self", ".", "forecast_data", "=", "forecast_data", "self", ".", "type", "=", "sensor_type", "self", ".", "_state", "=", "None", "self", ".", "_icon", "=", "None", "self", ".", "_alerts", "=", "None" ]
[ 713, 4 ]
[ 721, 27 ]
python
en
['en', 'en', 'en']
True
DarkSkyAlertSensor.name
(self)
Return the name of the sensor.
Return the name of the sensor.
def name(self): """Return the name of the sensor.""" return f"{self.client_name} {self._name}"
[ "def", "name", "(", "self", ")", ":", "return", "f\"{self.client_name} {self._name}\"" ]
[ 724, 4 ]
[ 726, 49 ]
python
en
['en', 'mi', 'en']
True
DarkSkyAlertSensor.state
(self)
Return the state of the sensor.
Return the state of the sensor.
def state(self): """Return the state of the sensor.""" return self._state
[ "def", "state", "(", "self", ")", ":", "return", "self", ".", "_state" ]
[ 729, 4 ]
[ 731, 26 ]
python
en
['en', 'en', 'en']
True
DarkSkyAlertSensor.icon
(self)
Icon to use in the frontend, if any.
Icon to use in the frontend, if any.
def icon(self): """Icon to use in the frontend, if any.""" if self._state is not None and self._state > 0: return "mdi:alert-circle" return "mdi:alert-circle-outline"
[ "def", "icon", "(", "self", ")", ":", "if", "self", ".", "_state", "is", "not", "None", "and", "self", ".", "_state", ">", "0", ":", "return", "\"mdi:alert-circle\"", "return", "\"mdi:alert-circle-outline\"" ]
[ 734, 4 ]
[ 738, 41 ]
python
en
['en', 'en', 'en']
True
DarkSkyAlertSensor.device_state_attributes
(self)
Return the state attributes.
Return the state attributes.
def device_state_attributes(self): """Return the state attributes.""" return self._alerts
[ "def", "device_state_attributes", "(", "self", ")", ":", "return", "self", ".", "_alerts" ]
[ 741, 4 ]
[ 743, 27 ]
python
en
['en', 'en', 'en']
True
DarkSkyAlertSensor.update
(self)
Get the latest data from Dark Sky and updates the states.
Get the latest data from Dark Sky and updates the states.
def update(self): """Get the latest data from Dark Sky and updates the states.""" # Call the API for new forecast data. Each sensor will re-trigger this # same exact call, but that's fine. We cache results for a short period # of time to prevent hitting API limits. Note that Dark Sky will # charge users for too many calls in 1 day, so take care when updating. self.forecast_data.update() self.forecast_data.update_alerts() alerts = self.forecast_data.data_alerts self._state = self.get_state(alerts)
[ "def", "update", "(", "self", ")", ":", "# Call the API for new forecast data. Each sensor will re-trigger this", "# same exact call, but that's fine. We cache results for a short period", "# of time to prevent hitting API limits. Note that Dark Sky will", "# charge users for too many calls in 1 day, so take care when updating.", "self", ".", "forecast_data", ".", "update", "(", ")", "self", ".", "forecast_data", ".", "update_alerts", "(", ")", "alerts", "=", "self", ".", "forecast_data", ".", "data_alerts", "self", ".", "_state", "=", "self", ".", "get_state", "(", "alerts", ")" ]
[ 745, 4 ]
[ 754, 44 ]
python
en
['en', 'en', 'en']
True
DarkSkyAlertSensor.get_state
(self, data)
Return a new state based on the type. If the sensor type is unknown, the current state is returned.
Return a new state based on the type.
def get_state(self, data): """ Return a new state based on the type. If the sensor type is unknown, the current state is returned. """ alerts = {} if data is None: self._alerts = alerts return data multiple_alerts = len(data) > 1 for i, alert in enumerate(data): for attr in ALERTS_ATTRS: if multiple_alerts: dkey = f"{attr}_{i!s}" else: dkey = attr alerts[dkey] = getattr(alert, attr) self._alerts = alerts return len(data)
[ "def", "get_state", "(", "self", ",", "data", ")", ":", "alerts", "=", "{", "}", "if", "data", "is", "None", ":", "self", ".", "_alerts", "=", "alerts", "return", "data", "multiple_alerts", "=", "len", "(", "data", ")", ">", "1", "for", "i", ",", "alert", "in", "enumerate", "(", "data", ")", ":", "for", "attr", "in", "ALERTS_ATTRS", ":", "if", "multiple_alerts", ":", "dkey", "=", "f\"{attr}_{i!s}\"", "else", ":", "dkey", "=", "attr", "alerts", "[", "dkey", "]", "=", "getattr", "(", "alert", ",", "attr", ")", "self", ".", "_alerts", "=", "alerts", "return", "len", "(", "data", ")" ]
[ 756, 4 ]
[ 777, 24 ]
python
en
['en', 'error', 'th']
False
DarkSkyData.__init__
(self, api_key, latitude, longitude, units, language, interval)
Initialize the data object.
Initialize the data object.
def __init__(self, api_key, latitude, longitude, units, language, interval): """Initialize the data object.""" self._api_key = api_key self.latitude = latitude self.longitude = longitude self.units = units self.language = language self._connect_error = False self.data = None self.unit_system = None self.data_currently = None self.data_minutely = None self.data_hourly = None self.data_daily = None self.data_alerts = None # Apply throttling to methods using configured interval self.update = Throttle(interval)(self._update) self.update_currently = Throttle(interval)(self._update_currently) self.update_minutely = Throttle(interval)(self._update_minutely) self.update_hourly = Throttle(interval)(self._update_hourly) self.update_daily = Throttle(interval)(self._update_daily) self.update_alerts = Throttle(interval)(self._update_alerts)
[ "def", "__init__", "(", "self", ",", "api_key", ",", "latitude", ",", "longitude", ",", "units", ",", "language", ",", "interval", ")", ":", "self", ".", "_api_key", "=", "api_key", "self", ".", "latitude", "=", "latitude", "self", ".", "longitude", "=", "longitude", "self", ".", "units", "=", "units", "self", ".", "language", "=", "language", "self", ".", "_connect_error", "=", "False", "self", ".", "data", "=", "None", "self", ".", "unit_system", "=", "None", "self", ".", "data_currently", "=", "None", "self", ".", "data_minutely", "=", "None", "self", ".", "data_hourly", "=", "None", "self", ".", "data_daily", "=", "None", "self", ".", "data_alerts", "=", "None", "# Apply throttling to methods using configured interval", "self", ".", "update", "=", "Throttle", "(", "interval", ")", "(", "self", ".", "_update", ")", "self", ".", "update_currently", "=", "Throttle", "(", "interval", ")", "(", "self", ".", "_update_currently", ")", "self", ".", "update_minutely", "=", "Throttle", "(", "interval", ")", "(", "self", ".", "_update_minutely", ")", "self", ".", "update_hourly", "=", "Throttle", "(", "interval", ")", "(", "self", ".", "_update_hourly", ")", "self", ".", "update_daily", "=", "Throttle", "(", "interval", ")", "(", "self", ".", "_update_daily", ")", "self", ".", "update_alerts", "=", "Throttle", "(", "interval", ")", "(", "self", ".", "_update_alerts", ")" ]
[ 794, 4 ]
[ 817, 68 ]
python
en
['en', 'en', 'en']
True
DarkSkyData._update
(self)
Get the latest data from Dark Sky.
Get the latest data from Dark Sky.
def _update(self): """Get the latest data from Dark Sky.""" try: self.data = forecastio.load_forecast( self._api_key, self.latitude, self.longitude, units=self.units, lang=self.language, ) if self._connect_error: self._connect_error = False _LOGGER.info("Reconnected to Dark Sky") except (ConnectError, HTTPError, Timeout, ValueError) as error: if not self._connect_error: self._connect_error = True _LOGGER.error("Unable to connect to Dark Sky: %s", error) self.data = None self.unit_system = self.data and self.data.json["flags"]["units"]
[ "def", "_update", "(", "self", ")", ":", "try", ":", "self", ".", "data", "=", "forecastio", ".", "load_forecast", "(", "self", ".", "_api_key", ",", "self", ".", "latitude", ",", "self", ".", "longitude", ",", "units", "=", "self", ".", "units", ",", "lang", "=", "self", ".", "language", ",", ")", "if", "self", ".", "_connect_error", ":", "self", ".", "_connect_error", "=", "False", "_LOGGER", ".", "info", "(", "\"Reconnected to Dark Sky\"", ")", "except", "(", "ConnectError", ",", "HTTPError", ",", "Timeout", ",", "ValueError", ")", "as", "error", ":", "if", "not", "self", ".", "_connect_error", ":", "self", ".", "_connect_error", "=", "True", "_LOGGER", ".", "error", "(", "\"Unable to connect to Dark Sky: %s\"", ",", "error", ")", "self", ".", "data", "=", "None", "self", ".", "unit_system", "=", "self", ".", "data", "and", "self", ".", "data", ".", "json", "[", "\"flags\"", "]", "[", "\"units\"", "]" ]
[ 819, 4 ]
[ 837, 73 ]
python
en
['en', 'en', 'en']
True
DarkSkyData._update_currently
(self)
Update currently data.
Update currently data.
def _update_currently(self): """Update currently data.""" self.data_currently = self.data and self.data.currently()
[ "def", "_update_currently", "(", "self", ")", ":", "self", ".", "data_currently", "=", "self", ".", "data", "and", "self", ".", "data", ".", "currently", "(", ")" ]
[ 839, 4 ]
[ 841, 65 ]
python
en
['en', 'en', 'en']
True
DarkSkyData._update_minutely
(self)
Update minutely data.
Update minutely data.
def _update_minutely(self): """Update minutely data.""" self.data_minutely = self.data and self.data.minutely()
[ "def", "_update_minutely", "(", "self", ")", ":", "self", ".", "data_minutely", "=", "self", ".", "data", "and", "self", ".", "data", ".", "minutely", "(", ")" ]
[ 843, 4 ]
[ 845, 63 ]
python
en
['en', 'en', 'en']
True
DarkSkyData._update_hourly
(self)
Update hourly data.
Update hourly data.
def _update_hourly(self): """Update hourly data.""" self.data_hourly = self.data and self.data.hourly()
[ "def", "_update_hourly", "(", "self", ")", ":", "self", ".", "data_hourly", "=", "self", ".", "data", "and", "self", ".", "data", ".", "hourly", "(", ")" ]
[ 847, 4 ]
[ 849, 59 ]
python
en
['en', 'sn', 'en']
True
DarkSkyData._update_daily
(self)
Update daily data.
Update daily data.
def _update_daily(self): """Update daily data.""" self.data_daily = self.data and self.data.daily()
[ "def", "_update_daily", "(", "self", ")", ":", "self", ".", "data_daily", "=", "self", ".", "data", "and", "self", ".", "data", ".", "daily", "(", ")" ]
[ 851, 4 ]
[ 853, 57 ]
python
en
['en', 'sn', 'en']
True
DarkSkyData._update_alerts
(self)
Update alerts data.
Update alerts data.
def _update_alerts(self): """Update alerts data.""" self.data_alerts = self.data and self.data.alerts()
[ "def", "_update_alerts", "(", "self", ")", ":", "self", ".", "data_alerts", "=", "self", ".", "data", "and", "self", ".", "data", ".", "alerts", "(", ")" ]
[ 855, 4 ]
[ 857, 59 ]
python
co
['fr', 'co', 'en']
False
async_setup
(hass: HomeAssistant, config: dict)
Set up the NuHeat component.
Set up the NuHeat component.
async def async_setup(hass: HomeAssistant, config: dict): """Set up the NuHeat component.""" hass.data.setdefault(DOMAIN, {}) conf = config.get(DOMAIN) if not conf: return True for serial_number in conf[CONF_DEVICES]: # Since the api currently doesn't permit fetching the serial numbers # and they have to be specified we create a separate config entry for # each serial number. This won't increase the number of http # requests as each thermostat has to be updated anyways. # This also allows us to validate that the entered valid serial # numbers and do not end up with a config entry where half of the # devices work. hass.async_create_task( hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data={ CONF_USERNAME: conf[CONF_USERNAME], CONF_PASSWORD: conf[CONF_PASSWORD], CONF_SERIAL_NUMBER: serial_number, }, ) ) return True
[ "async", "def", "async_setup", "(", "hass", ":", "HomeAssistant", ",", "config", ":", "dict", ")", ":", "hass", ".", "data", ".", "setdefault", "(", "DOMAIN", ",", "{", "}", ")", "conf", "=", "config", ".", "get", "(", "DOMAIN", ")", "if", "not", "conf", ":", "return", "True", "for", "serial_number", "in", "conf", "[", "CONF_DEVICES", "]", ":", "# Since the api currently doesn't permit fetching the serial numbers", "# and they have to be specified we create a separate config entry for", "# each serial number. This won't increase the number of http", "# requests as each thermostat has to be updated anyways.", "# This also allows us to validate that the entered valid serial", "# numbers and do not end up with a config entry where half of the", "# devices work.", "hass", ".", "async_create_task", "(", "hass", ".", "config_entries", ".", "flow", ".", "async_init", "(", "DOMAIN", ",", "context", "=", "{", "\"source\"", ":", "SOURCE_IMPORT", "}", ",", "data", "=", "{", "CONF_USERNAME", ":", "conf", "[", "CONF_USERNAME", "]", ",", "CONF_PASSWORD", ":", "conf", "[", "CONF_PASSWORD", "]", ",", "CONF_SERIAL_NUMBER", ":", "serial_number", ",", "}", ",", ")", ")", "return", "True" ]
[ 42, 0 ]
[ 69, 15 ]
python
en
['en', 'fr', 'en']
True
_get_thermostat
(api, serial_number)
Authenticate and create the thermostat object.
Authenticate and create the thermostat object.
def _get_thermostat(api, serial_number): """Authenticate and create the thermostat object.""" api.authenticate() return api.get_thermostat(serial_number)
[ "def", "_get_thermostat", "(", "api", ",", "serial_number", ")", ":", "api", ".", "authenticate", "(", ")", "return", "api", ".", "get_thermostat", "(", "serial_number", ")" ]
[ 72, 0 ]
[ 75, 44 ]
python
en
['en', 'en', 'en']
True
async_setup_entry
(hass: HomeAssistant, entry: ConfigEntry)
Set up NuHeat from a config entry.
Set up NuHeat from a config entry.
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry): """Set up NuHeat from a config entry.""" conf = entry.data username = conf[CONF_USERNAME] password = conf[CONF_PASSWORD] serial_number = conf[CONF_SERIAL_NUMBER] api = nuheat.NuHeat(username, password) try: thermostat = await hass.async_add_executor_job( _get_thermostat, api, serial_number ) except requests.exceptions.Timeout as ex: raise ConfigEntryNotReady from ex except requests.exceptions.HTTPError as ex: if ( ex.response.status_code > HTTP_BAD_REQUEST and ex.response.status_code < HTTP_INTERNAL_SERVER_ERROR ): _LOGGER.error("Failed to login to nuheat: %s", ex) return False raise ConfigEntryNotReady from ex except Exception as ex: # pylint: disable=broad-except _LOGGER.error("Failed to login to nuheat: %s", ex) return False async def _async_update_data(): """Fetch data from API endpoint.""" await hass.async_add_executor_job(thermostat.get_data) coordinator = DataUpdateCoordinator( hass, _LOGGER, name=f"nuheat {serial_number}", update_method=_async_update_data, update_interval=timedelta(minutes=5), ) hass.data[DOMAIN][entry.entry_id] = (thermostat, coordinator) for component in PLATFORMS: hass.async_create_task( hass.config_entries.async_forward_entry_setup(entry, component) ) return True
[ "async", "def", "async_setup_entry", "(", "hass", ":", "HomeAssistant", ",", "entry", ":", "ConfigEntry", ")", ":", "conf", "=", "entry", ".", "data", "username", "=", "conf", "[", "CONF_USERNAME", "]", "password", "=", "conf", "[", "CONF_PASSWORD", "]", "serial_number", "=", "conf", "[", "CONF_SERIAL_NUMBER", "]", "api", "=", "nuheat", ".", "NuHeat", "(", "username", ",", "password", ")", "try", ":", "thermostat", "=", "await", "hass", ".", "async_add_executor_job", "(", "_get_thermostat", ",", "api", ",", "serial_number", ")", "except", "requests", ".", "exceptions", ".", "Timeout", "as", "ex", ":", "raise", "ConfigEntryNotReady", "from", "ex", "except", "requests", ".", "exceptions", ".", "HTTPError", "as", "ex", ":", "if", "(", "ex", ".", "response", ".", "status_code", ">", "HTTP_BAD_REQUEST", "and", "ex", ".", "response", ".", "status_code", "<", "HTTP_INTERNAL_SERVER_ERROR", ")", ":", "_LOGGER", ".", "error", "(", "\"Failed to login to nuheat: %s\"", ",", "ex", ")", "return", "False", "raise", "ConfigEntryNotReady", "from", "ex", "except", "Exception", "as", "ex", ":", "# pylint: disable=broad-except", "_LOGGER", ".", "error", "(", "\"Failed to login to nuheat: %s\"", ",", "ex", ")", "return", "False", "async", "def", "_async_update_data", "(", ")", ":", "\"\"\"Fetch data from API endpoint.\"\"\"", "await", "hass", ".", "async_add_executor_job", "(", "thermostat", ".", "get_data", ")", "coordinator", "=", "DataUpdateCoordinator", "(", "hass", ",", "_LOGGER", ",", "name", "=", "f\"nuheat {serial_number}\"", ",", "update_method", "=", "_async_update_data", ",", "update_interval", "=", "timedelta", "(", "minutes", "=", "5", ")", ",", ")", "hass", ".", "data", "[", "DOMAIN", "]", "[", "entry", ".", "entry_id", "]", "=", "(", "thermostat", ",", "coordinator", ")", "for", "component", "in", "PLATFORMS", ":", "hass", ".", "async_create_task", "(", "hass", ".", "config_entries", ".", "async_forward_entry_setup", "(", "entry", ",", "component", ")", ")", "return", "True" ]
[ 78, 0 ]
[ 126, 15 ]
python
en
['en', 'en', 'en']
True
async_unload_entry
(hass: HomeAssistant, entry: ConfigEntry)
Unload a config entry.
Unload a config entry.
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry): """Unload a config entry.""" unload_ok = all( await asyncio.gather( *[ hass.config_entries.async_forward_entry_unload(entry, component) for component in PLATFORMS ] ) ) if unload_ok: hass.data[DOMAIN].pop(entry.entry_id) return unload_ok
[ "async", "def", "async_unload_entry", "(", "hass", ":", "HomeAssistant", ",", "entry", ":", "ConfigEntry", ")", ":", "unload_ok", "=", "all", "(", "await", "asyncio", ".", "gather", "(", "*", "[", "hass", ".", "config_entries", ".", "async_forward_entry_unload", "(", "entry", ",", "component", ")", "for", "component", "in", "PLATFORMS", "]", ")", ")", "if", "unload_ok", ":", "hass", ".", "data", "[", "DOMAIN", "]", ".", "pop", "(", "entry", ".", "entry_id", ")", "return", "unload_ok" ]
[ 129, 0 ]
[ 142, 20 ]
python
en
['en', 'es', 'en']
True
_ratio_scores
(parameters_value, clusteringmodel_gmm_good, clusteringmodel_gmm_bad)
The ratio is smaller the better
The ratio is smaller the better
def _ratio_scores(parameters_value, clusteringmodel_gmm_good, clusteringmodel_gmm_bad): ''' The ratio is smaller the better ''' ratio = clusteringmodel_gmm_good.score( [parameters_value]) / clusteringmodel_gmm_bad.score([parameters_value]) sigma = 0 return ratio, sigma
[ "def", "_ratio_scores", "(", "parameters_value", ",", "clusteringmodel_gmm_good", ",", "clusteringmodel_gmm_bad", ")", ":", "ratio", "=", "clusteringmodel_gmm_good", ".", "score", "(", "[", "parameters_value", "]", ")", "/", "clusteringmodel_gmm_bad", ".", "score", "(", "[", "parameters_value", "]", ")", "sigma", "=", "0", "return", "ratio", ",", "sigma" ]
[ 18, 0 ]
[ 26, 23 ]
python
en
['en', 'error', 'th']
False
selection_r
(x_bounds, x_types, clusteringmodel_gmm_good, clusteringmodel_gmm_bad, num_starting_points=100, minimize_constraints_fun=None)
Select using different types.
Select using different types.
def selection_r(x_bounds, x_types, clusteringmodel_gmm_good, clusteringmodel_gmm_bad, num_starting_points=100, minimize_constraints_fun=None): ''' Select using different types. ''' minimize_starting_points = clusteringmodel_gmm_good.sample(n_samples=num_starting_points) outputs = selection(x_bounds, x_types, clusteringmodel_gmm_good, clusteringmodel_gmm_bad, minimize_starting_points[0], minimize_constraints_fun) return outputs
[ "def", "selection_r", "(", "x_bounds", ",", "x_types", ",", "clusteringmodel_gmm_good", ",", "clusteringmodel_gmm_bad", ",", "num_starting_points", "=", "100", ",", "minimize_constraints_fun", "=", "None", ")", ":", "minimize_starting_points", "=", "clusteringmodel_gmm_good", ".", "sample", "(", "n_samples", "=", "num_starting_points", ")", "outputs", "=", "selection", "(", "x_bounds", ",", "x_types", ",", "clusteringmodel_gmm_good", ",", "clusteringmodel_gmm_bad", ",", "minimize_starting_points", "[", "0", "]", ",", "minimize_constraints_fun", ")", "return", "outputs" ]
[ 29, 0 ]
[ 46, 18 ]
python
en
['en', 'error', 'th']
False
selection
(x_bounds, x_types, clusteringmodel_gmm_good, clusteringmodel_gmm_bad, minimize_starting_points, minimize_constraints_fun=None)
Select the lowest mu value
Select the lowest mu value
def selection(x_bounds, x_types, clusteringmodel_gmm_good, clusteringmodel_gmm_bad, minimize_starting_points, minimize_constraints_fun=None): ''' Select the lowest mu value ''' results = lib_acquisition_function.next_hyperparameter_lowest_mu( _ratio_scores, [clusteringmodel_gmm_good, clusteringmodel_gmm_bad], x_bounds, x_types, minimize_starting_points, minimize_constraints_fun=minimize_constraints_fun) return results
[ "def", "selection", "(", "x_bounds", ",", "x_types", ",", "clusteringmodel_gmm_good", ",", "clusteringmodel_gmm_bad", ",", "minimize_starting_points", ",", "minimize_constraints_fun", "=", "None", ")", ":", "results", "=", "lib_acquisition_function", ".", "next_hyperparameter_lowest_mu", "(", "_ratio_scores", ",", "[", "clusteringmodel_gmm_good", ",", "clusteringmodel_gmm_bad", "]", ",", "x_bounds", ",", "x_types", ",", "minimize_starting_points", ",", "minimize_constraints_fun", "=", "minimize_constraints_fun", ")", "return", "results" ]
[ 49, 0 ]
[ 63, 18 ]
python
en
['en', 'error', 'th']
False
_rand_with_constraints
(x_bounds, x_types)
Random generate the variable with constraints
Random generate the variable with constraints
def _rand_with_constraints(x_bounds, x_types): ''' Random generate the variable with constraints ''' outputs = None x_bounds_withconstraints = [x_bounds[i] for i in CONSTRAINT_PARAMS_IDX] x_types_withconstraints = [x_types[i] for i in CONSTRAINT_PARAMS_IDX] x_val_withconstraints = lib_constraint_summation.rand(x_bounds_withconstraints, x_types_withconstraints, CONSTRAINT_LOWERBOUND, CONSTRAINT_UPPERBOUND) if x_val_withconstraints is not None: outputs = [None] * len(x_bounds) for i, _ in enumerate(CONSTRAINT_PARAMS_IDX): outputs[CONSTRAINT_PARAMS_IDX[i]] = x_val_withconstraints[i] for i, _ in enumerate(outputs): if outputs[i] is None: outputs[i] = random.randint(x_bounds[i][0], x_bounds[i][1]) return outputs
[ "def", "_rand_with_constraints", "(", "x_bounds", ",", "x_types", ")", ":", "outputs", "=", "None", "x_bounds_withconstraints", "=", "[", "x_bounds", "[", "i", "]", "for", "i", "in", "CONSTRAINT_PARAMS_IDX", "]", "x_types_withconstraints", "=", "[", "x_types", "[", "i", "]", "for", "i", "in", "CONSTRAINT_PARAMS_IDX", "]", "x_val_withconstraints", "=", "lib_constraint_summation", ".", "rand", "(", "x_bounds_withconstraints", ",", "x_types_withconstraints", ",", "CONSTRAINT_LOWERBOUND", ",", "CONSTRAINT_UPPERBOUND", ")", "if", "x_val_withconstraints", "is", "not", "None", ":", "outputs", "=", "[", "None", "]", "*", "len", "(", "x_bounds", ")", "for", "i", ",", "_", "in", "enumerate", "(", "CONSTRAINT_PARAMS_IDX", ")", ":", "outputs", "[", "CONSTRAINT_PARAMS_IDX", "[", "i", "]", "]", "=", "x_val_withconstraints", "[", "i", "]", "for", "i", ",", "_", "in", "enumerate", "(", "outputs", ")", ":", "if", "outputs", "[", "i", "]", "is", "None", ":", "outputs", "[", "i", "]", "=", "random", ".", "randint", "(", "x_bounds", "[", "i", "]", "[", "0", "]", ",", "x_bounds", "[", "i", "]", "[", "1", "]", ")", "return", "outputs" ]
[ 66, 0 ]
[ 84, 18 ]
python
en
['en', 'error', 'th']
False
_minimize_constraints_fun_summation
(x)
Minimize constraints fun summation
Minimize constraints fun summation
def _minimize_constraints_fun_summation(x): ''' Minimize constraints fun summation ''' summation = sum([x[i] for i in CONSTRAINT_PARAMS_IDX]) return CONSTRAINT_UPPERBOUND >= summation >= CONSTRAINT_LOWERBOUND
[ "def", "_minimize_constraints_fun_summation", "(", "x", ")", ":", "summation", "=", "sum", "(", "[", "x", "[", "i", "]", "for", "i", "in", "CONSTRAINT_PARAMS_IDX", "]", ")", "return", "CONSTRAINT_UPPERBOUND", ">=", "summation", ">=", "CONSTRAINT_LOWERBOUND" ]
[ 87, 0 ]
[ 92, 70 ]
python
en
['en', 'error', 'th']
False
setup_platform
(hass, config, add_entities, discovery_info=None)
Set up the Vultr subscription (server) sensor.
Set up the Vultr subscription (server) sensor.
def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the Vultr subscription (server) sensor.""" vultr = hass.data[DATA_VULTR] subscription = config.get(CONF_SUBSCRIPTION) name = config.get(CONF_NAME) monitored_conditions = config.get(CONF_MONITORED_CONDITIONS) if subscription not in vultr.data: _LOGGER.error("Subscription %s not found", subscription) return sensors = [] for condition in monitored_conditions: sensors.append(VultrSensor(vultr, subscription, condition, name)) add_entities(sensors, True)
[ "def", "setup_platform", "(", "hass", ",", "config", ",", "add_entities", ",", "discovery_info", "=", "None", ")", ":", "vultr", "=", "hass", ".", "data", "[", "DATA_VULTR", "]", "subscription", "=", "config", ".", "get", "(", "CONF_SUBSCRIPTION", ")", "name", "=", "config", ".", "get", "(", "CONF_NAME", ")", "monitored_conditions", "=", "config", ".", "get", "(", "CONF_MONITORED_CONDITIONS", ")", "if", "subscription", "not", "in", "vultr", ".", "data", ":", "_LOGGER", ".", "error", "(", "\"Subscription %s not found\"", ",", "subscription", ")", "return", "sensors", "=", "[", "]", "for", "condition", "in", "monitored_conditions", ":", "sensors", ".", "append", "(", "VultrSensor", "(", "vultr", ",", "subscription", ",", "condition", ",", "name", ")", ")", "add_entities", "(", "sensors", ",", "True", ")" ]
[ 40, 0 ]
[ 57, 31 ]
python
en
['en', 'da', 'en']
True
VultrSensor.__init__
(self, vultr, subscription, condition, name)
Initialize a new Vultr sensor.
Initialize a new Vultr sensor.
def __init__(self, vultr, subscription, condition, name): """Initialize a new Vultr sensor.""" self._vultr = vultr self._condition = condition self._name = name self.subscription = subscription self.data = None condition_info = MONITORED_CONDITIONS[condition] self._condition_name = condition_info[0] self._units = condition_info[1] self._icon = condition_info[2]
[ "def", "__init__", "(", "self", ",", "vultr", ",", "subscription", ",", "condition", ",", "name", ")", ":", "self", ".", "_vultr", "=", "vultr", "self", ".", "_condition", "=", "condition", "self", ".", "_name", "=", "name", "self", ".", "subscription", "=", "subscription", "self", ".", "data", "=", "None", "condition_info", "=", "MONITORED_CONDITIONS", "[", "condition", "]", "self", ".", "_condition_name", "=", "condition_info", "[", "0", "]", "self", ".", "_units", "=", "condition_info", "[", "1", "]", "self", ".", "_icon", "=", "condition_info", "[", "2", "]" ]
[ 63, 4 ]
[ 76, 38 ]
python
en
['en', 'en', 'en']
True
VultrSensor.name
(self)
Return the name of the sensor.
Return the name of the sensor.
def name(self): """Return the name of the sensor.""" try: return self._name.format(self._condition_name) except IndexError: try: return self._name.format(self.data["label"], self._condition_name) except (KeyError, TypeError): return self._name
[ "def", "name", "(", "self", ")", ":", "try", ":", "return", "self", ".", "_name", ".", "format", "(", "self", ".", "_condition_name", ")", "except", "IndexError", ":", "try", ":", "return", "self", ".", "_name", ".", "format", "(", "self", ".", "data", "[", "\"label\"", "]", ",", "self", ".", "_condition_name", ")", "except", "(", "KeyError", ",", "TypeError", ")", ":", "return", "self", ".", "_name" ]
[ 79, 4 ]
[ 87, 33 ]
python
en
['en', 'mi', 'en']
True
VultrSensor.icon
(self)
Return the icon used in the frontend if any.
Return the icon used in the frontend if any.
def icon(self): """Return the icon used in the frontend if any.""" return self._icon
[ "def", "icon", "(", "self", ")", ":", "return", "self", ".", "_icon" ]
[ 90, 4 ]
[ 92, 25 ]
python
en
['en', 'en', 'en']
True
VultrSensor.unit_of_measurement
(self)
Return the unit of measurement to present the value in.
Return the unit of measurement to present the value in.
def unit_of_measurement(self): """Return the unit of measurement to present the value in.""" return self._units
[ "def", "unit_of_measurement", "(", "self", ")", ":", "return", "self", ".", "_units" ]
[ 95, 4 ]
[ 97, 26 ]
python
en
['en', 'en', 'en']
True
VultrSensor.state
(self)
Return the value of this given sensor type.
Return the value of this given sensor type.
def state(self): """Return the value of this given sensor type.""" try: return round(float(self.data.get(self._condition)), 2) except (TypeError, ValueError): return self.data.get(self._condition)
[ "def", "state", "(", "self", ")", ":", "try", ":", "return", "round", "(", "float", "(", "self", ".", "data", ".", "get", "(", "self", ".", "_condition", ")", ")", ",", "2", ")", "except", "(", "TypeError", ",", "ValueError", ")", ":", "return", "self", ".", "data", ".", "get", "(", "self", ".", "_condition", ")" ]
[ 100, 4 ]
[ 105, 49 ]
python
en
['en', 'en', 'en']
True
VultrSensor.update
(self)
Update state of sensor.
Update state of sensor.
def update(self): """Update state of sensor.""" self._vultr.update() self.data = self._vultr.data[self.subscription]
[ "def", "update", "(", "self", ")", ":", "self", ".", "_vultr", ".", "update", "(", ")", "self", ".", "data", "=", "self", ".", "_vultr", ".", "data", "[", "self", ".", "subscription", "]" ]
[ 107, 4 ]
[ 110, 55 ]
python
en
['en', 'co', 'en']
True
async_get_conditions
(hass: HomeAssistant, device_id: str)
List device conditions for Cover devices.
List device conditions for Cover devices.
async def async_get_conditions(hass: HomeAssistant, device_id: str) -> List[dict]: """List device conditions for Cover devices.""" registry = await entity_registry.async_get_registry(hass) conditions: List[Dict[str, Any]] = [] # Get all the integrations entities for this device for entry in entity_registry.async_entries_for_device(registry, device_id): if entry.domain != DOMAIN: continue state = hass.states.get(entry.entity_id) if not state or ATTR_SUPPORTED_FEATURES not in state.attributes: continue supported_features = state.attributes[ATTR_SUPPORTED_FEATURES] supports_open_close = supported_features & (SUPPORT_OPEN | SUPPORT_CLOSE) # Add conditions for each entity that belongs to this integration if supports_open_close: conditions.append( { CONF_CONDITION: "device", CONF_DEVICE_ID: device_id, CONF_DOMAIN: DOMAIN, CONF_ENTITY_ID: entry.entity_id, CONF_TYPE: "is_open", } ) conditions.append( { CONF_CONDITION: "device", CONF_DEVICE_ID: device_id, CONF_DOMAIN: DOMAIN, CONF_ENTITY_ID: entry.entity_id, CONF_TYPE: "is_closed", } ) conditions.append( { CONF_CONDITION: "device", CONF_DEVICE_ID: device_id, CONF_DOMAIN: DOMAIN, CONF_ENTITY_ID: entry.entity_id, CONF_TYPE: "is_opening", } ) conditions.append( { CONF_CONDITION: "device", CONF_DEVICE_ID: device_id, CONF_DOMAIN: DOMAIN, CONF_ENTITY_ID: entry.entity_id, CONF_TYPE: "is_closing", } ) if supported_features & SUPPORT_SET_POSITION: conditions.append( { CONF_CONDITION: "device", CONF_DEVICE_ID: device_id, CONF_DOMAIN: DOMAIN, CONF_ENTITY_ID: entry.entity_id, CONF_TYPE: "is_position", } ) if supported_features & SUPPORT_SET_TILT_POSITION: conditions.append( { CONF_CONDITION: "device", CONF_DEVICE_ID: device_id, CONF_DOMAIN: DOMAIN, CONF_ENTITY_ID: entry.entity_id, CONF_TYPE: "is_tilt_position", } ) return conditions
[ "async", "def", "async_get_conditions", "(", "hass", ":", "HomeAssistant", ",", "device_id", ":", "str", ")", "->", "List", "[", "dict", "]", ":", "registry", "=", "await", "entity_registry", ".", "async_get_registry", "(", "hass", ")", "conditions", ":", "List", "[", "Dict", "[", "str", ",", "Any", "]", "]", "=", "[", "]", "# Get all the integrations entities for this device", "for", "entry", "in", "entity_registry", ".", "async_entries_for_device", "(", "registry", ",", "device_id", ")", ":", "if", "entry", ".", "domain", "!=", "DOMAIN", ":", "continue", "state", "=", "hass", ".", "states", ".", "get", "(", "entry", ".", "entity_id", ")", "if", "not", "state", "or", "ATTR_SUPPORTED_FEATURES", "not", "in", "state", ".", "attributes", ":", "continue", "supported_features", "=", "state", ".", "attributes", "[", "ATTR_SUPPORTED_FEATURES", "]", "supports_open_close", "=", "supported_features", "&", "(", "SUPPORT_OPEN", "|", "SUPPORT_CLOSE", ")", "# Add conditions for each entity that belongs to this integration", "if", "supports_open_close", ":", "conditions", ".", "append", "(", "{", "CONF_CONDITION", ":", "\"device\"", ",", "CONF_DEVICE_ID", ":", "device_id", ",", "CONF_DOMAIN", ":", "DOMAIN", ",", "CONF_ENTITY_ID", ":", "entry", ".", "entity_id", ",", "CONF_TYPE", ":", "\"is_open\"", ",", "}", ")", "conditions", ".", "append", "(", "{", "CONF_CONDITION", ":", "\"device\"", ",", "CONF_DEVICE_ID", ":", "device_id", ",", "CONF_DOMAIN", ":", "DOMAIN", ",", "CONF_ENTITY_ID", ":", "entry", ".", "entity_id", ",", "CONF_TYPE", ":", "\"is_closed\"", ",", "}", ")", "conditions", ".", "append", "(", "{", "CONF_CONDITION", ":", "\"device\"", ",", "CONF_DEVICE_ID", ":", "device_id", ",", "CONF_DOMAIN", ":", "DOMAIN", ",", "CONF_ENTITY_ID", ":", "entry", ".", "entity_id", ",", "CONF_TYPE", ":", "\"is_opening\"", ",", "}", ")", "conditions", ".", "append", "(", "{", "CONF_CONDITION", ":", "\"device\"", ",", "CONF_DEVICE_ID", ":", "device_id", ",", "CONF_DOMAIN", ":", "DOMAIN", ",", "CONF_ENTITY_ID", ":", "entry", ".", "entity_id", ",", "CONF_TYPE", ":", "\"is_closing\"", ",", "}", ")", "if", "supported_features", "&", "SUPPORT_SET_POSITION", ":", "conditions", ".", "append", "(", "{", "CONF_CONDITION", ":", "\"device\"", ",", "CONF_DEVICE_ID", ":", "device_id", ",", "CONF_DOMAIN", ":", "DOMAIN", ",", "CONF_ENTITY_ID", ":", "entry", ".", "entity_id", ",", "CONF_TYPE", ":", "\"is_position\"", ",", "}", ")", "if", "supported_features", "&", "SUPPORT_SET_TILT_POSITION", ":", "conditions", ".", "append", "(", "{", "CONF_CONDITION", ":", "\"device\"", ",", "CONF_DEVICE_ID", ":", "device_id", ",", "CONF_DOMAIN", ":", "DOMAIN", ",", "CONF_ENTITY_ID", ":", "entry", ".", "entity_id", ",", "CONF_TYPE", ":", "\"is_tilt_position\"", ",", "}", ")", "return", "conditions" ]
[ 67, 0 ]
[ 143, 21 ]
python
en
['fr', 'en', 'en']
True
async_get_condition_capabilities
(hass: HomeAssistant, config: dict)
List condition capabilities.
List condition capabilities.
async def async_get_condition_capabilities(hass: HomeAssistant, config: dict) -> dict: """List condition capabilities.""" if config[CONF_TYPE] not in ["is_position", "is_tilt_position"]: return {} return { "extra_fields": vol.Schema( { vol.Optional(CONF_ABOVE, default=0): vol.All( vol.Coerce(int), vol.Range(min=0, max=100) ), vol.Optional(CONF_BELOW, default=100): vol.All( vol.Coerce(int), vol.Range(min=0, max=100) ), } ) }
[ "async", "def", "async_get_condition_capabilities", "(", "hass", ":", "HomeAssistant", ",", "config", ":", "dict", ")", "->", "dict", ":", "if", "config", "[", "CONF_TYPE", "]", "not", "in", "[", "\"is_position\"", ",", "\"is_tilt_position\"", "]", ":", "return", "{", "}", "return", "{", "\"extra_fields\"", ":", "vol", ".", "Schema", "(", "{", "vol", ".", "Optional", "(", "CONF_ABOVE", ",", "default", "=", "0", ")", ":", "vol", ".", "All", "(", "vol", ".", "Coerce", "(", "int", ")", ",", "vol", ".", "Range", "(", "min", "=", "0", ",", "max", "=", "100", ")", ")", ",", "vol", ".", "Optional", "(", "CONF_BELOW", ",", "default", "=", "100", ")", ":", "vol", ".", "All", "(", "vol", ".", "Coerce", "(", "int", ")", ",", "vol", ".", "Range", "(", "min", "=", "0", ",", "max", "=", "100", ")", ")", ",", "}", ")", "}" ]
[ 146, 0 ]
[ 162, 5 ]
python
en
['ro', 'sr', 'en']
False
async_condition_from_config
( config: ConfigType, config_validation: bool )
Create a function to test a device condition.
Create a function to test a device condition.
def async_condition_from_config( config: ConfigType, config_validation: bool ) -> condition.ConditionCheckerType: """Create a function to test a device condition.""" if config_validation: config = CONDITION_SCHEMA(config) if config[CONF_TYPE] in STATE_CONDITION_TYPES: if config[CONF_TYPE] == "is_open": state = STATE_OPEN elif config[CONF_TYPE] == "is_closed": state = STATE_CLOSED elif config[CONF_TYPE] == "is_opening": state = STATE_OPENING elif config[CONF_TYPE] == "is_closing": state = STATE_CLOSING def test_is_state(hass: HomeAssistant, variables: TemplateVarsType) -> bool: """Test if an entity is a certain state.""" return condition.state(hass, config[ATTR_ENTITY_ID], state) return test_is_state if config[CONF_TYPE] == "is_position": position = "current_position" if config[CONF_TYPE] == "is_tilt_position": position = "current_tilt_position" min_pos = config.get(CONF_ABOVE) max_pos = config.get(CONF_BELOW) value_template = template.Template( # type: ignore f"{{{{ state.attributes.{position} }}}}" ) @callback def template_if(hass: HomeAssistant, variables: TemplateVarsType = None) -> bool: """Validate template based if-condition.""" value_template.hass = hass return condition.async_numeric_state( hass, config[ATTR_ENTITY_ID], max_pos, min_pos, value_template ) return template_if
[ "def", "async_condition_from_config", "(", "config", ":", "ConfigType", ",", "config_validation", ":", "bool", ")", "->", "condition", ".", "ConditionCheckerType", ":", "if", "config_validation", ":", "config", "=", "CONDITION_SCHEMA", "(", "config", ")", "if", "config", "[", "CONF_TYPE", "]", "in", "STATE_CONDITION_TYPES", ":", "if", "config", "[", "CONF_TYPE", "]", "==", "\"is_open\"", ":", "state", "=", "STATE_OPEN", "elif", "config", "[", "CONF_TYPE", "]", "==", "\"is_closed\"", ":", "state", "=", "STATE_CLOSED", "elif", "config", "[", "CONF_TYPE", "]", "==", "\"is_opening\"", ":", "state", "=", "STATE_OPENING", "elif", "config", "[", "CONF_TYPE", "]", "==", "\"is_closing\"", ":", "state", "=", "STATE_CLOSING", "def", "test_is_state", "(", "hass", ":", "HomeAssistant", ",", "variables", ":", "TemplateVarsType", ")", "->", "bool", ":", "\"\"\"Test if an entity is a certain state.\"\"\"", "return", "condition", ".", "state", "(", "hass", ",", "config", "[", "ATTR_ENTITY_ID", "]", ",", "state", ")", "return", "test_is_state", "if", "config", "[", "CONF_TYPE", "]", "==", "\"is_position\"", ":", "position", "=", "\"current_position\"", "if", "config", "[", "CONF_TYPE", "]", "==", "\"is_tilt_position\"", ":", "position", "=", "\"current_tilt_position\"", "min_pos", "=", "config", ".", "get", "(", "CONF_ABOVE", ")", "max_pos", "=", "config", ".", "get", "(", "CONF_BELOW", ")", "value_template", "=", "template", ".", "Template", "(", "# type: ignore", "f\"{{{{ state.attributes.{position} }}}}\"", ")", "@", "callback", "def", "template_if", "(", "hass", ":", "HomeAssistant", ",", "variables", ":", "TemplateVarsType", "=", "None", ")", "->", "bool", ":", "\"\"\"Validate template based if-condition.\"\"\"", "value_template", ".", "hass", "=", "hass", "return", "condition", ".", "async_numeric_state", "(", "hass", ",", "config", "[", "ATTR_ENTITY_ID", "]", ",", "max_pos", ",", "min_pos", ",", "value_template", ")", "return", "template_if" ]
[ 166, 0 ]
[ 208, 22 ]
python
en
['en', 'en', 'en']
True
test_sensors
(hass)
Test creation of the sensors.
Test creation of the sensors.
async def test_sensors(hass): """Test creation of the sensors.""" mock_powerwall = await _mock_powerwall_with_fixtures(hass) with patch( "homeassistant.components.powerwall.config_flow.Powerwall", return_value=mock_powerwall, ), patch( "homeassistant.components.powerwall.Powerwall", return_value=mock_powerwall ): assert await async_setup_component(hass, DOMAIN, _mock_get_config()) await hass.async_block_till_done() device_registry = await hass.helpers.device_registry.async_get_registry() reg_device = device_registry.async_get_device( identifiers={("powerwall", "TG0123456789AB_TG9876543210BA")}, connections=set(), ) assert reg_device.model == "PowerWall 2 (GW1)" assert reg_device.sw_version == "1.45.1" assert reg_device.manufacturer == "Tesla" assert reg_device.name == "MySite" state = hass.states.get("sensor.powerwall_site_now") assert state.state == "0.032" expected_attributes = { "frequency": 60, "energy_exported_(in_kW)": 10429.5, "energy_imported_(in_kW)": 4824.2, "instant_average_voltage": 120.7, "unit_of_measurement": "kW", "friendly_name": "Powerwall Site Now", "device_class": "power", "is_active": False, } # Only test for a subset of attributes in case # HA changes the implementation and a new one appears for key, value in expected_attributes.items(): assert state.attributes[key] == value state = hass.states.get("sensor.powerwall_load_now") assert state.state == "1.971" expected_attributes = { "frequency": 60, "energy_exported_(in_kW)": 1056.8, "energy_imported_(in_kW)": 4693.0, "instant_average_voltage": 120.7, "unit_of_measurement": "kW", "friendly_name": "Powerwall Load Now", "device_class": "power", "is_active": True, } # Only test for a subset of attributes in case # HA changes the implementation and a new one appears for key, value in expected_attributes.items(): assert state.attributes[key] == value state = hass.states.get("sensor.powerwall_battery_now") assert state.state == "-8.55" expected_attributes = { "frequency": 60.0, "energy_exported_(in_kW)": 3620.0, "energy_imported_(in_kW)": 4216.2, "instant_average_voltage": 240.6, "unit_of_measurement": "kW", "friendly_name": "Powerwall Battery Now", "device_class": "power", "is_active": True, } # Only test for a subset of attributes in case # HA changes the implementation and a new one appears for key, value in expected_attributes.items(): assert state.attributes[key] == value state = hass.states.get("sensor.powerwall_solar_now") assert state.state == "10.49" expected_attributes = { "frequency": 60, "energy_exported_(in_kW)": 9864.2, "energy_imported_(in_kW)": 28.2, "instant_average_voltage": 120.7, "unit_of_measurement": "kW", "friendly_name": "Powerwall Solar Now", "device_class": "power", "is_active": True, } # Only test for a subset of attributes in case # HA changes the implementation and a new one appears for key, value in expected_attributes.items(): assert state.attributes[key] == value state = hass.states.get("sensor.powerwall_charge") assert state.state == "47" expected_attributes = { "unit_of_measurement": PERCENTAGE, "friendly_name": "Powerwall Charge", "device_class": "battery", } # Only test for a subset of attributes in case # HA changes the implementation and a new one appears for key, value in expected_attributes.items(): assert state.attributes[key] == value
[ "async", "def", "test_sensors", "(", "hass", ")", ":", "mock_powerwall", "=", "await", "_mock_powerwall_with_fixtures", "(", "hass", ")", "with", "patch", "(", "\"homeassistant.components.powerwall.config_flow.Powerwall\"", ",", "return_value", "=", "mock_powerwall", ",", ")", ",", "patch", "(", "\"homeassistant.components.powerwall.Powerwall\"", ",", "return_value", "=", "mock_powerwall", ")", ":", "assert", "await", "async_setup_component", "(", "hass", ",", "DOMAIN", ",", "_mock_get_config", "(", ")", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "device_registry", "=", "await", "hass", ".", "helpers", ".", "device_registry", ".", "async_get_registry", "(", ")", "reg_device", "=", "device_registry", ".", "async_get_device", "(", "identifiers", "=", "{", "(", "\"powerwall\"", ",", "\"TG0123456789AB_TG9876543210BA\"", ")", "}", ",", "connections", "=", "set", "(", ")", ",", ")", "assert", "reg_device", ".", "model", "==", "\"PowerWall 2 (GW1)\"", "assert", "reg_device", ".", "sw_version", "==", "\"1.45.1\"", "assert", "reg_device", ".", "manufacturer", "==", "\"Tesla\"", "assert", "reg_device", ".", "name", "==", "\"MySite\"", "state", "=", "hass", ".", "states", ".", "get", "(", "\"sensor.powerwall_site_now\"", ")", "assert", "state", ".", "state", "==", "\"0.032\"", "expected_attributes", "=", "{", "\"frequency\"", ":", "60", ",", "\"energy_exported_(in_kW)\"", ":", "10429.5", ",", "\"energy_imported_(in_kW)\"", ":", "4824.2", ",", "\"instant_average_voltage\"", ":", "120.7", ",", "\"unit_of_measurement\"", ":", "\"kW\"", ",", "\"friendly_name\"", ":", "\"Powerwall Site Now\"", ",", "\"device_class\"", ":", "\"power\"", ",", "\"is_active\"", ":", "False", ",", "}", "# Only test for a subset of attributes in case", "# HA changes the implementation and a new one appears", "for", "key", ",", "value", "in", "expected_attributes", ".", "items", "(", ")", ":", "assert", "state", ".", "attributes", "[", "key", "]", "==", "value", "state", "=", "hass", ".", "states", ".", "get", "(", "\"sensor.powerwall_load_now\"", ")", "assert", "state", ".", "state", "==", "\"1.971\"", "expected_attributes", "=", "{", "\"frequency\"", ":", "60", ",", "\"energy_exported_(in_kW)\"", ":", "1056.8", ",", "\"energy_imported_(in_kW)\"", ":", "4693.0", ",", "\"instant_average_voltage\"", ":", "120.7", ",", "\"unit_of_measurement\"", ":", "\"kW\"", ",", "\"friendly_name\"", ":", "\"Powerwall Load Now\"", ",", "\"device_class\"", ":", "\"power\"", ",", "\"is_active\"", ":", "True", ",", "}", "# Only test for a subset of attributes in case", "# HA changes the implementation and a new one appears", "for", "key", ",", "value", "in", "expected_attributes", ".", "items", "(", ")", ":", "assert", "state", ".", "attributes", "[", "key", "]", "==", "value", "state", "=", "hass", ".", "states", ".", "get", "(", "\"sensor.powerwall_battery_now\"", ")", "assert", "state", ".", "state", "==", "\"-8.55\"", "expected_attributes", "=", "{", "\"frequency\"", ":", "60.0", ",", "\"energy_exported_(in_kW)\"", ":", "3620.0", ",", "\"energy_imported_(in_kW)\"", ":", "4216.2", ",", "\"instant_average_voltage\"", ":", "240.6", ",", "\"unit_of_measurement\"", ":", "\"kW\"", ",", "\"friendly_name\"", ":", "\"Powerwall Battery Now\"", ",", "\"device_class\"", ":", "\"power\"", ",", "\"is_active\"", ":", "True", ",", "}", "# Only test for a subset of attributes in case", "# HA changes the implementation and a new one appears", "for", "key", ",", "value", "in", "expected_attributes", ".", "items", "(", ")", ":", "assert", "state", ".", "attributes", "[", "key", "]", "==", "value", "state", "=", "hass", ".", "states", ".", "get", "(", "\"sensor.powerwall_solar_now\"", ")", "assert", "state", ".", "state", "==", "\"10.49\"", "expected_attributes", "=", "{", "\"frequency\"", ":", "60", ",", "\"energy_exported_(in_kW)\"", ":", "9864.2", ",", "\"energy_imported_(in_kW)\"", ":", "28.2", ",", "\"instant_average_voltage\"", ":", "120.7", ",", "\"unit_of_measurement\"", ":", "\"kW\"", ",", "\"friendly_name\"", ":", "\"Powerwall Solar Now\"", ",", "\"device_class\"", ":", "\"power\"", ",", "\"is_active\"", ":", "True", ",", "}", "# Only test for a subset of attributes in case", "# HA changes the implementation and a new one appears", "for", "key", ",", "value", "in", "expected_attributes", ".", "items", "(", ")", ":", "assert", "state", ".", "attributes", "[", "key", "]", "==", "value", "state", "=", "hass", ".", "states", ".", "get", "(", "\"sensor.powerwall_charge\"", ")", "assert", "state", ".", "state", "==", "\"47\"", "expected_attributes", "=", "{", "\"unit_of_measurement\"", ":", "PERCENTAGE", ",", "\"friendly_name\"", ":", "\"Powerwall Charge\"", ",", "\"device_class\"", ":", "\"battery\"", ",", "}", "# Only test for a subset of attributes in case", "# HA changes the implementation and a new one appears", "for", "key", ",", "value", "in", "expected_attributes", ".", "items", "(", ")", ":", "assert", "state", ".", "attributes", "[", "key", "]", "==", "value" ]
[ 11, 0 ]
[ 113, 45 ]
python
en
['en', 'en', 'en']
True
send_message
(hass, message, title=None, data=None)
Send a notification message.
Send a notification message.
def send_message(hass, message, title=None, data=None): """Send a notification message.""" info = {ATTR_MESSAGE: message} if title is not None: info[ATTR_TITLE] = title if data is not None: info[ATTR_DATA] = data hass.services.call(DOMAIN, SERVICE_NOTIFY, info)
[ "def", "send_message", "(", "hass", ",", "message", ",", "title", "=", "None", ",", "data", "=", "None", ")", ":", "info", "=", "{", "ATTR_MESSAGE", ":", "message", "}", "if", "title", "is", "not", "None", ":", "info", "[", "ATTR_TITLE", "]", "=", "title", "if", "data", "is", "not", "None", ":", "info", "[", "ATTR_DATA", "]", "=", "data", "hass", ".", "services", ".", "call", "(", "DOMAIN", ",", "SERVICE_NOTIFY", ",", "info", ")" ]
[ 16, 0 ]
[ 26, 52 ]
python
en
['en', 'lb', 'en']
True
DecisionEvent.action_scope
(self)
ActionScope: Load and discharge scope for agent to generate decision.
ActionScope: Load and discharge scope for agent to generate decision.
def action_scope(self) -> ActionScope: """ActionScope: Load and discharge scope for agent to generate decision. """ if self._action_scope is None: self._action_scope = self._action_scope_func(self.port_idx, self.vessel_idx) return self._action_scope
[ "def", "action_scope", "(", "self", ")", "->", "ActionScope", ":", "if", "self", ".", "_action_scope", "is", "None", ":", "self", ".", "_action_scope", "=", "self", ".", "_action_scope_func", "(", "self", ".", "port_idx", ",", "self", ".", "vessel_idx", ")", "return", "self", ".", "_action_scope" ]
[ 94, 4 ]
[ 100, 33 ]
python
en
['en', 'en', 'en']
True
DecisionEvent.early_discharge
(self)
int: Early discharge number of corresponding vessel.
int: Early discharge number of corresponding vessel.
def early_discharge(self) -> int: """int: Early discharge number of corresponding vessel. """ if self._early_discharge is None: self._early_discharge = self._early_discharge_func(self.vessel_idx) return self._early_discharge
[ "def", "early_discharge", "(", "self", ")", "->", "int", ":", "if", "self", ".", "_early_discharge", "is", "None", ":", "self", ".", "_early_discharge", "=", "self", ".", "_early_discharge_func", "(", "self", ".", "vessel_idx", ")", "return", "self", ".", "_early_discharge" ]
[ 103, 4 ]
[ 109, 36 ]
python
en
['en', 'en', 'en']
True
DecisionEvent.__getstate__
(self)
Return pickleable dictionary. NOTE: this class do not support unpickle
Return pickleable dictionary.
def __getstate__(self): """Return pickleable dictionary. NOTE: this class do not support unpickle""" return { "tick": self.tick, "port_idx": self.port_idx, "vessel_idx": self.vessel_idx, "action_scope": self.action_scope, "early_discharge": self.early_discharge }
[ "def", "__getstate__", "(", "self", ")", ":", "return", "{", "\"tick\"", ":", "self", ".", "tick", ",", "\"port_idx\"", ":", "self", ".", "port_idx", ",", "\"vessel_idx\"", ":", "self", ".", "vessel_idx", ",", "\"action_scope\"", ":", "self", ".", "action_scope", ",", "\"early_discharge\"", ":", "self", ".", "early_discharge", "}" ]
[ 111, 4 ]
[ 121, 9 ]
python
en
['it', 'en', 'en']
True
device_reg
(hass)
Return an empty, loaded, registry.
Return an empty, loaded, registry.
def device_reg(hass): """Return an empty, loaded, registry.""" return mock_device_registry(hass)
[ "def", "device_reg", "(", "hass", ")", ":", "return", "mock_device_registry", "(", "hass", ")" ]
[ 22, 0 ]
[ 24, 37 ]
python
en
['en', 'fy', 'en']
True
entity_reg
(hass)
Return an empty, loaded, registry.
Return an empty, loaded, registry.
def entity_reg(hass): """Return an empty, loaded, registry.""" return mock_registry(hass)
[ "def", "entity_reg", "(", "hass", ")", ":", "return", "mock_registry", "(", "hass", ")" ]
[ 28, 0 ]
[ 30, 30 ]
python
en
['en', 'fy', 'en']
True
calls
(hass)
Track calls to a mock service.
Track calls to a mock service.
def calls(hass): """Track calls to a mock service.""" return async_mock_service(hass, "test", "automation")
[ "def", "calls", "(", "hass", ")", ":", "return", "async_mock_service", "(", "hass", ",", "\"test\"", ",", "\"automation\"", ")" ]
[ 34, 0 ]
[ 36, 57 ]
python
en
['en', 'en', 'en']
True
test_get_conditions
(hass, device_reg, entity_reg)
Test we get the expected conditions from a sensor.
Test we get the expected conditions from a sensor.
async def test_get_conditions(hass, device_reg, entity_reg): """Test we get the expected conditions from a sensor.""" platform = getattr(hass.components, f"test.{DOMAIN}") platform.init() config_entry = MockConfigEntry(domain="test", data={}) config_entry.add_to_hass(hass) device_entry = device_reg.async_get_or_create( config_entry_id=config_entry.entry_id, connections={(device_registry.CONNECTION_NETWORK_MAC, "12:34:56:AB:CD:EF")}, ) for device_class in DEVICE_CLASSES: entity_reg.async_get_or_create( DOMAIN, "test", platform.ENTITIES[device_class].unique_id, device_id=device_entry.id, ) assert await async_setup_component(hass, DOMAIN, {DOMAIN: {CONF_PLATFORM: "test"}}) await hass.async_block_till_done() expected_conditions = [ { "condition": "device", "domain": DOMAIN, "type": condition["type"], "device_id": device_entry.id, "entity_id": platform.ENTITIES[device_class].entity_id, } for device_class in DEVICE_CLASSES for condition in ENTITY_CONDITIONS[device_class] if device_class != "none" ] conditions = await async_get_device_automations(hass, "condition", device_entry.id) assert conditions == expected_conditions
[ "async", "def", "test_get_conditions", "(", "hass", ",", "device_reg", ",", "entity_reg", ")", ":", "platform", "=", "getattr", "(", "hass", ".", "components", ",", "f\"test.{DOMAIN}\"", ")", "platform", ".", "init", "(", ")", "config_entry", "=", "MockConfigEntry", "(", "domain", "=", "\"test\"", ",", "data", "=", "{", "}", ")", "config_entry", ".", "add_to_hass", "(", "hass", ")", "device_entry", "=", "device_reg", ".", "async_get_or_create", "(", "config_entry_id", "=", "config_entry", ".", "entry_id", ",", "connections", "=", "{", "(", "device_registry", ".", "CONNECTION_NETWORK_MAC", ",", "\"12:34:56:AB:CD:EF\"", ")", "}", ",", ")", "for", "device_class", "in", "DEVICE_CLASSES", ":", "entity_reg", ".", "async_get_or_create", "(", "DOMAIN", ",", "\"test\"", ",", "platform", ".", "ENTITIES", "[", "device_class", "]", ".", "unique_id", ",", "device_id", "=", "device_entry", ".", "id", ",", ")", "assert", "await", "async_setup_component", "(", "hass", ",", "DOMAIN", ",", "{", "DOMAIN", ":", "{", "CONF_PLATFORM", ":", "\"test\"", "}", "}", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "expected_conditions", "=", "[", "{", "\"condition\"", ":", "\"device\"", ",", "\"domain\"", ":", "DOMAIN", ",", "\"type\"", ":", "condition", "[", "\"type\"", "]", ",", "\"device_id\"", ":", "device_entry", ".", "id", ",", "\"entity_id\"", ":", "platform", ".", "ENTITIES", "[", "device_class", "]", ".", "entity_id", ",", "}", "for", "device_class", "in", "DEVICE_CLASSES", "for", "condition", "in", "ENTITY_CONDITIONS", "[", "device_class", "]", "if", "device_class", "!=", "\"none\"", "]", "conditions", "=", "await", "async_get_device_automations", "(", "hass", ",", "\"condition\"", ",", "device_entry", ".", "id", ")", "assert", "conditions", "==", "expected_conditions" ]
[ 39, 0 ]
[ 74, 44 ]
python
en
['en', 'en', 'en']
True
test_get_condition_capabilities
(hass, device_reg, entity_reg)
Test we get the expected capabilities from a sensor condition.
Test we get the expected capabilities from a sensor condition.
async def test_get_condition_capabilities(hass, device_reg, entity_reg): """Test we get the expected capabilities from a sensor condition.""" platform = getattr(hass.components, f"test.{DOMAIN}") platform.init() config_entry = MockConfigEntry(domain="test", data={}) config_entry.add_to_hass(hass) device_entry = device_reg.async_get_or_create( config_entry_id=config_entry.entry_id, connections={(device_registry.CONNECTION_NETWORK_MAC, "12:34:56:AB:CD:EF")}, ) entity_reg.async_get_or_create( DOMAIN, "test", platform.ENTITIES["battery"].unique_id, device_id=device_entry.id, ) assert await async_setup_component(hass, DOMAIN, {DOMAIN: {CONF_PLATFORM: "test"}}) await hass.async_block_till_done() expected_capabilities = { "extra_fields": [ { "description": {"suffix": PERCENTAGE}, "name": "above", "optional": True, "type": "float", }, { "description": {"suffix": PERCENTAGE}, "name": "below", "optional": True, "type": "float", }, ] } conditions = await async_get_device_automations(hass, "condition", device_entry.id) assert len(conditions) == 1 for condition in conditions: capabilities = await async_get_device_automation_capabilities( hass, "condition", condition ) assert capabilities == expected_capabilities
[ "async", "def", "test_get_condition_capabilities", "(", "hass", ",", "device_reg", ",", "entity_reg", ")", ":", "platform", "=", "getattr", "(", "hass", ".", "components", ",", "f\"test.{DOMAIN}\"", ")", "platform", ".", "init", "(", ")", "config_entry", "=", "MockConfigEntry", "(", "domain", "=", "\"test\"", ",", "data", "=", "{", "}", ")", "config_entry", ".", "add_to_hass", "(", "hass", ")", "device_entry", "=", "device_reg", ".", "async_get_or_create", "(", "config_entry_id", "=", "config_entry", ".", "entry_id", ",", "connections", "=", "{", "(", "device_registry", ".", "CONNECTION_NETWORK_MAC", ",", "\"12:34:56:AB:CD:EF\"", ")", "}", ",", ")", "entity_reg", ".", "async_get_or_create", "(", "DOMAIN", ",", "\"test\"", ",", "platform", ".", "ENTITIES", "[", "\"battery\"", "]", ".", "unique_id", ",", "device_id", "=", "device_entry", ".", "id", ",", ")", "assert", "await", "async_setup_component", "(", "hass", ",", "DOMAIN", ",", "{", "DOMAIN", ":", "{", "CONF_PLATFORM", ":", "\"test\"", "}", "}", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "expected_capabilities", "=", "{", "\"extra_fields\"", ":", "[", "{", "\"description\"", ":", "{", "\"suffix\"", ":", "PERCENTAGE", "}", ",", "\"name\"", ":", "\"above\"", ",", "\"optional\"", ":", "True", ",", "\"type\"", ":", "\"float\"", ",", "}", ",", "{", "\"description\"", ":", "{", "\"suffix\"", ":", "PERCENTAGE", "}", ",", "\"name\"", ":", "\"below\"", ",", "\"optional\"", ":", "True", ",", "\"type\"", ":", "\"float\"", ",", "}", ",", "]", "}", "conditions", "=", "await", "async_get_device_automations", "(", "hass", ",", "\"condition\"", ",", "device_entry", ".", "id", ")", "assert", "len", "(", "conditions", ")", "==", "1", "for", "condition", "in", "conditions", ":", "capabilities", "=", "await", "async_get_device_automation_capabilities", "(", "hass", ",", "\"condition\"", ",", "condition", ")", "assert", "capabilities", "==", "expected_capabilities" ]
[ 77, 0 ]
[ 120, 52 ]
python
en
['en', 'en', 'en']
True
test_get_condition_capabilities_none
(hass, device_reg, entity_reg)
Test we get the expected capabilities from a sensor condition.
Test we get the expected capabilities from a sensor condition.
async def test_get_condition_capabilities_none(hass, device_reg, entity_reg): """Test we get the expected capabilities from a sensor condition.""" platform = getattr(hass.components, f"test.{DOMAIN}") platform.init() config_entry = MockConfigEntry(domain="test", data={}) config_entry.add_to_hass(hass) assert await async_setup_component(hass, DOMAIN, {DOMAIN: {CONF_PLATFORM: "test"}}) await hass.async_block_till_done() conditions = [ { "condition": "device", "device_id": "8770c43885354d5fa27604db6817f63f", "domain": "sensor", "entity_id": "sensor.beer", "type": "is_battery_level", }, { "condition": "device", "device_id": "8770c43885354d5fa27604db6817f63f", "domain": "sensor", "entity_id": platform.ENTITIES["none"].entity_id, "type": "is_battery_level", }, ] expected_capabilities = {} for condition in conditions: capabilities = await async_get_device_automation_capabilities( hass, "condition", condition ) assert capabilities == expected_capabilities
[ "async", "def", "test_get_condition_capabilities_none", "(", "hass", ",", "device_reg", ",", "entity_reg", ")", ":", "platform", "=", "getattr", "(", "hass", ".", "components", ",", "f\"test.{DOMAIN}\"", ")", "platform", ".", "init", "(", ")", "config_entry", "=", "MockConfigEntry", "(", "domain", "=", "\"test\"", ",", "data", "=", "{", "}", ")", "config_entry", ".", "add_to_hass", "(", "hass", ")", "assert", "await", "async_setup_component", "(", "hass", ",", "DOMAIN", ",", "{", "DOMAIN", ":", "{", "CONF_PLATFORM", ":", "\"test\"", "}", "}", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "conditions", "=", "[", "{", "\"condition\"", ":", "\"device\"", ",", "\"device_id\"", ":", "\"8770c43885354d5fa27604db6817f63f\"", ",", "\"domain\"", ":", "\"sensor\"", ",", "\"entity_id\"", ":", "\"sensor.beer\"", ",", "\"type\"", ":", "\"is_battery_level\"", ",", "}", ",", "{", "\"condition\"", ":", "\"device\"", ",", "\"device_id\"", ":", "\"8770c43885354d5fa27604db6817f63f\"", ",", "\"domain\"", ":", "\"sensor\"", ",", "\"entity_id\"", ":", "platform", ".", "ENTITIES", "[", "\"none\"", "]", ".", "entity_id", ",", "\"type\"", ":", "\"is_battery_level\"", ",", "}", ",", "]", "expected_capabilities", "=", "{", "}", "for", "condition", "in", "conditions", ":", "capabilities", "=", "await", "async_get_device_automation_capabilities", "(", "hass", ",", "\"condition\"", ",", "condition", ")", "assert", "capabilities", "==", "expected_capabilities" ]
[ 123, 0 ]
[ 156, 52 ]
python
en
['en', 'en', 'en']
True
test_if_state_not_above_below
(hass, calls, caplog)
Test for bad value conditions.
Test for bad value conditions.
async def test_if_state_not_above_below(hass, calls, caplog): """Test for bad value conditions.""" platform = getattr(hass.components, f"test.{DOMAIN}") platform.init() assert await async_setup_component(hass, DOMAIN, {DOMAIN: {CONF_PLATFORM: "test"}}) await hass.async_block_till_done() sensor1 = platform.ENTITIES["battery"] assert await async_setup_component( hass, automation.DOMAIN, { automation.DOMAIN: [ { "trigger": {"platform": "event", "event_type": "test_event1"}, "condition": [ { "condition": "device", "domain": DOMAIN, "device_id": "", "entity_id": sensor1.entity_id, "type": "is_battery_level", } ], "action": {"service": "test.automation"}, } ] }, ) assert "must contain at least one of below, above" in caplog.text
[ "async", "def", "test_if_state_not_above_below", "(", "hass", ",", "calls", ",", "caplog", ")", ":", "platform", "=", "getattr", "(", "hass", ".", "components", ",", "f\"test.{DOMAIN}\"", ")", "platform", ".", "init", "(", ")", "assert", "await", "async_setup_component", "(", "hass", ",", "DOMAIN", ",", "{", "DOMAIN", ":", "{", "CONF_PLATFORM", ":", "\"test\"", "}", "}", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "sensor1", "=", "platform", ".", "ENTITIES", "[", "\"battery\"", "]", "assert", "await", "async_setup_component", "(", "hass", ",", "automation", ".", "DOMAIN", ",", "{", "automation", ".", "DOMAIN", ":", "[", "{", "\"trigger\"", ":", "{", "\"platform\"", ":", "\"event\"", ",", "\"event_type\"", ":", "\"test_event1\"", "}", ",", "\"condition\"", ":", "[", "{", "\"condition\"", ":", "\"device\"", ",", "\"domain\"", ":", "DOMAIN", ",", "\"device_id\"", ":", "\"\"", ",", "\"entity_id\"", ":", "sensor1", ".", "entity_id", ",", "\"type\"", ":", "\"is_battery_level\"", ",", "}", "]", ",", "\"action\"", ":", "{", "\"service\"", ":", "\"test.automation\"", "}", ",", "}", "]", "}", ",", ")", "assert", "\"must contain at least one of below, above\"", "in", "caplog", ".", "text" ]
[ 159, 0 ]
[ 190, 69 ]
python
en
['en', 'en', 'en']
True
test_if_state_above
(hass, calls)
Test for value conditions.
Test for value conditions.
async def test_if_state_above(hass, calls): """Test for value conditions.""" platform = getattr(hass.components, f"test.{DOMAIN}") platform.init() assert await async_setup_component(hass, DOMAIN, {DOMAIN: {CONF_PLATFORM: "test"}}) await hass.async_block_till_done() sensor1 = platform.ENTITIES["battery"] assert await async_setup_component( hass, automation.DOMAIN, { automation.DOMAIN: [ { "trigger": {"platform": "event", "event_type": "test_event1"}, "condition": [ { "condition": "device", "domain": DOMAIN, "device_id": "", "entity_id": sensor1.entity_id, "type": "is_battery_level", "above": 10, } ], "action": { "service": "test.automation", "data_template": { "some": "{{ trigger.%s }}" % "}} - {{ trigger.".join(("platform", "event.event_type")) }, }, } ] }, ) await hass.async_block_till_done() assert hass.states.get(sensor1.entity_id).state == STATE_UNKNOWN assert len(calls) == 0 hass.bus.async_fire("test_event1") await hass.async_block_till_done() assert len(calls) == 0 hass.states.async_set(sensor1.entity_id, 9) hass.bus.async_fire("test_event1") await hass.async_block_till_done() assert len(calls) == 0 hass.states.async_set(sensor1.entity_id, 11) hass.bus.async_fire("test_event1") await hass.async_block_till_done() assert len(calls) == 1 assert calls[0].data["some"] == "event - test_event1"
[ "async", "def", "test_if_state_above", "(", "hass", ",", "calls", ")", ":", "platform", "=", "getattr", "(", "hass", ".", "components", ",", "f\"test.{DOMAIN}\"", ")", "platform", ".", "init", "(", ")", "assert", "await", "async_setup_component", "(", "hass", ",", "DOMAIN", ",", "{", "DOMAIN", ":", "{", "CONF_PLATFORM", ":", "\"test\"", "}", "}", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "sensor1", "=", "platform", ".", "ENTITIES", "[", "\"battery\"", "]", "assert", "await", "async_setup_component", "(", "hass", ",", "automation", ".", "DOMAIN", ",", "{", "automation", ".", "DOMAIN", ":", "[", "{", "\"trigger\"", ":", "{", "\"platform\"", ":", "\"event\"", ",", "\"event_type\"", ":", "\"test_event1\"", "}", ",", "\"condition\"", ":", "[", "{", "\"condition\"", ":", "\"device\"", ",", "\"domain\"", ":", "DOMAIN", ",", "\"device_id\"", ":", "\"\"", ",", "\"entity_id\"", ":", "sensor1", ".", "entity_id", ",", "\"type\"", ":", "\"is_battery_level\"", ",", "\"above\"", ":", "10", ",", "}", "]", ",", "\"action\"", ":", "{", "\"service\"", ":", "\"test.automation\"", ",", "\"data_template\"", ":", "{", "\"some\"", ":", "\"{{ trigger.%s }}\"", "%", "\"}} - {{ trigger.\"", ".", "join", "(", "(", "\"platform\"", ",", "\"event.event_type\"", ")", ")", "}", ",", "}", ",", "}", "]", "}", ",", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "hass", ".", "states", ".", "get", "(", "sensor1", ".", "entity_id", ")", ".", "state", "==", "STATE_UNKNOWN", "assert", "len", "(", "calls", ")", "==", "0", "hass", ".", "bus", ".", "async_fire", "(", "\"test_event1\"", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "len", "(", "calls", ")", "==", "0", "hass", ".", "states", ".", "async_set", "(", "sensor1", ".", "entity_id", ",", "9", ")", "hass", ".", "bus", ".", "async_fire", "(", "\"test_event1\"", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "len", "(", "calls", ")", "==", "0", "hass", ".", "states", ".", "async_set", "(", "sensor1", ".", "entity_id", ",", "11", ")", "hass", ".", "bus", ".", "async_fire", "(", "\"test_event1\"", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "len", "(", "calls", ")", "==", "1", "assert", "calls", "[", "0", "]", ".", "data", "[", "\"some\"", "]", "==", "\"event - test_event1\"" ]
[ 193, 0 ]
[ 248, 57 ]
python
en
['en', 'en', 'en']
True
test_if_state_below
(hass, calls)
Test for value conditions.
Test for value conditions.
async def test_if_state_below(hass, calls): """Test for value conditions.""" platform = getattr(hass.components, f"test.{DOMAIN}") platform.init() assert await async_setup_component(hass, DOMAIN, {DOMAIN: {CONF_PLATFORM: "test"}}) await hass.async_block_till_done() sensor1 = platform.ENTITIES["battery"] assert await async_setup_component( hass, automation.DOMAIN, { automation.DOMAIN: [ { "trigger": {"platform": "event", "event_type": "test_event1"}, "condition": [ { "condition": "device", "domain": DOMAIN, "device_id": "", "entity_id": sensor1.entity_id, "type": "is_battery_level", "below": 10, } ], "action": { "service": "test.automation", "data_template": { "some": "{{ trigger.%s }}" % "}} - {{ trigger.".join(("platform", "event.event_type")) }, }, } ] }, ) await hass.async_block_till_done() assert hass.states.get(sensor1.entity_id).state == STATE_UNKNOWN assert len(calls) == 0 hass.bus.async_fire("test_event1") await hass.async_block_till_done() assert len(calls) == 0 hass.states.async_set(sensor1.entity_id, 11) hass.bus.async_fire("test_event1") await hass.async_block_till_done() assert len(calls) == 0 hass.states.async_set(sensor1.entity_id, 9) hass.bus.async_fire("test_event1") await hass.async_block_till_done() assert len(calls) == 1 assert calls[0].data["some"] == "event - test_event1"
[ "async", "def", "test_if_state_below", "(", "hass", ",", "calls", ")", ":", "platform", "=", "getattr", "(", "hass", ".", "components", ",", "f\"test.{DOMAIN}\"", ")", "platform", ".", "init", "(", ")", "assert", "await", "async_setup_component", "(", "hass", ",", "DOMAIN", ",", "{", "DOMAIN", ":", "{", "CONF_PLATFORM", ":", "\"test\"", "}", "}", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "sensor1", "=", "platform", ".", "ENTITIES", "[", "\"battery\"", "]", "assert", "await", "async_setup_component", "(", "hass", ",", "automation", ".", "DOMAIN", ",", "{", "automation", ".", "DOMAIN", ":", "[", "{", "\"trigger\"", ":", "{", "\"platform\"", ":", "\"event\"", ",", "\"event_type\"", ":", "\"test_event1\"", "}", ",", "\"condition\"", ":", "[", "{", "\"condition\"", ":", "\"device\"", ",", "\"domain\"", ":", "DOMAIN", ",", "\"device_id\"", ":", "\"\"", ",", "\"entity_id\"", ":", "sensor1", ".", "entity_id", ",", "\"type\"", ":", "\"is_battery_level\"", ",", "\"below\"", ":", "10", ",", "}", "]", ",", "\"action\"", ":", "{", "\"service\"", ":", "\"test.automation\"", ",", "\"data_template\"", ":", "{", "\"some\"", ":", "\"{{ trigger.%s }}\"", "%", "\"}} - {{ trigger.\"", ".", "join", "(", "(", "\"platform\"", ",", "\"event.event_type\"", ")", ")", "}", ",", "}", ",", "}", "]", "}", ",", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "hass", ".", "states", ".", "get", "(", "sensor1", ".", "entity_id", ")", ".", "state", "==", "STATE_UNKNOWN", "assert", "len", "(", "calls", ")", "==", "0", "hass", ".", "bus", ".", "async_fire", "(", "\"test_event1\"", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "len", "(", "calls", ")", "==", "0", "hass", ".", "states", ".", "async_set", "(", "sensor1", ".", "entity_id", ",", "11", ")", "hass", ".", "bus", ".", "async_fire", "(", "\"test_event1\"", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "len", "(", "calls", ")", "==", "0", "hass", ".", "states", ".", "async_set", "(", "sensor1", ".", "entity_id", ",", "9", ")", "hass", ".", "bus", ".", "async_fire", "(", "\"test_event1\"", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "len", "(", "calls", ")", "==", "1", "assert", "calls", "[", "0", "]", ".", "data", "[", "\"some\"", "]", "==", "\"event - test_event1\"" ]
[ 251, 0 ]
[ 306, 57 ]
python
en
['en', 'en', 'en']
True
test_if_state_between
(hass, calls)
Test for value conditions.
Test for value conditions.
async def test_if_state_between(hass, calls): """Test for value conditions.""" platform = getattr(hass.components, f"test.{DOMAIN}") platform.init() assert await async_setup_component(hass, DOMAIN, {DOMAIN: {CONF_PLATFORM: "test"}}) await hass.async_block_till_done() sensor1 = platform.ENTITIES["battery"] assert await async_setup_component( hass, automation.DOMAIN, { automation.DOMAIN: [ { "trigger": {"platform": "event", "event_type": "test_event1"}, "condition": [ { "condition": "device", "domain": DOMAIN, "device_id": "", "entity_id": sensor1.entity_id, "type": "is_battery_level", "above": 10, "below": 20, } ], "action": { "service": "test.automation", "data_template": { "some": "{{ trigger.%s }}" % "}} - {{ trigger.".join(("platform", "event.event_type")) }, }, } ] }, ) await hass.async_block_till_done() assert hass.states.get(sensor1.entity_id).state == STATE_UNKNOWN assert len(calls) == 0 hass.bus.async_fire("test_event1") await hass.async_block_till_done() assert len(calls) == 0 hass.states.async_set(sensor1.entity_id, 9) hass.bus.async_fire("test_event1") await hass.async_block_till_done() assert len(calls) == 0 hass.states.async_set(sensor1.entity_id, 11) hass.bus.async_fire("test_event1") await hass.async_block_till_done() assert len(calls) == 1 assert calls[0].data["some"] == "event - test_event1" hass.states.async_set(sensor1.entity_id, 21) hass.bus.async_fire("test_event1") await hass.async_block_till_done() assert len(calls) == 1 hass.states.async_set(sensor1.entity_id, 19) hass.bus.async_fire("test_event1") await hass.async_block_till_done() assert len(calls) == 2 assert calls[1].data["some"] == "event - test_event1"
[ "async", "def", "test_if_state_between", "(", "hass", ",", "calls", ")", ":", "platform", "=", "getattr", "(", "hass", ".", "components", ",", "f\"test.{DOMAIN}\"", ")", "platform", ".", "init", "(", ")", "assert", "await", "async_setup_component", "(", "hass", ",", "DOMAIN", ",", "{", "DOMAIN", ":", "{", "CONF_PLATFORM", ":", "\"test\"", "}", "}", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "sensor1", "=", "platform", ".", "ENTITIES", "[", "\"battery\"", "]", "assert", "await", "async_setup_component", "(", "hass", ",", "automation", ".", "DOMAIN", ",", "{", "automation", ".", "DOMAIN", ":", "[", "{", "\"trigger\"", ":", "{", "\"platform\"", ":", "\"event\"", ",", "\"event_type\"", ":", "\"test_event1\"", "}", ",", "\"condition\"", ":", "[", "{", "\"condition\"", ":", "\"device\"", ",", "\"domain\"", ":", "DOMAIN", ",", "\"device_id\"", ":", "\"\"", ",", "\"entity_id\"", ":", "sensor1", ".", "entity_id", ",", "\"type\"", ":", "\"is_battery_level\"", ",", "\"above\"", ":", "10", ",", "\"below\"", ":", "20", ",", "}", "]", ",", "\"action\"", ":", "{", "\"service\"", ":", "\"test.automation\"", ",", "\"data_template\"", ":", "{", "\"some\"", ":", "\"{{ trigger.%s }}\"", "%", "\"}} - {{ trigger.\"", ".", "join", "(", "(", "\"platform\"", ",", "\"event.event_type\"", ")", ")", "}", ",", "}", ",", "}", "]", "}", ",", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "hass", ".", "states", ".", "get", "(", "sensor1", ".", "entity_id", ")", ".", "state", "==", "STATE_UNKNOWN", "assert", "len", "(", "calls", ")", "==", "0", "hass", ".", "bus", ".", "async_fire", "(", "\"test_event1\"", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "len", "(", "calls", ")", "==", "0", "hass", ".", "states", ".", "async_set", "(", "sensor1", ".", "entity_id", ",", "9", ")", "hass", ".", "bus", ".", "async_fire", "(", "\"test_event1\"", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "len", "(", "calls", ")", "==", "0", "hass", ".", "states", ".", "async_set", "(", "sensor1", ".", "entity_id", ",", "11", ")", "hass", ".", "bus", ".", "async_fire", "(", "\"test_event1\"", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "len", "(", "calls", ")", "==", "1", "assert", "calls", "[", "0", "]", ".", "data", "[", "\"some\"", "]", "==", "\"event - test_event1\"", "hass", ".", "states", ".", "async_set", "(", "sensor1", ".", "entity_id", ",", "21", ")", "hass", ".", "bus", ".", "async_fire", "(", "\"test_event1\"", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "len", "(", "calls", ")", "==", "1", "hass", ".", "states", ".", "async_set", "(", "sensor1", ".", "entity_id", ",", "19", ")", "hass", ".", "bus", ".", "async_fire", "(", "\"test_event1\"", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "len", "(", "calls", ")", "==", "2", "assert", "calls", "[", "1", "]", ".", "data", "[", "\"some\"", "]", "==", "\"event - test_event1\"" ]
[ 309, 0 ]
[ 376, 57 ]
python
en
['en', 'en', 'en']
True
list_image_files
()
List the image files in the cluster. Returns: None.
List the image files in the cluster.
def list_image_files(): """List the image files in the cluster. Returns: None. """ master_details = redis_controller.get_master_details() return list(master_details["image_files"].values())
[ "def", "list_image_files", "(", ")", ":", "master_details", "=", "redis_controller", ".", "get_master_details", "(", ")", "return", "list", "(", "master_details", "[", "\"image_files\"", "]", ".", "values", "(", ")", ")" ]
[ 20, 0 ]
[ 28, 55 ]
python
en
['en', 'en', 'en']
True