<commit_before>"""
Core components of Home Assistant.

Home Assistant is a Home Automation framework for observing the state
of entities and react to changes.
"""

import os
import time
import logging
import signal
import threading
import enum
import functools as ft
from collections import namedtuple

from homeassistant.const import (
    __version__, EVENT_HOMEASSISTANT_START, EVENT_HOMEASSISTANT_STOP,
    SERVICE_HOMEASSISTANT_STOP, SERVICE_HOMEASSISTANT_RESTART,
    EVENT_TIME_CHANGED, EVENT_STATE_CHANGED,
    EVENT_CALL_SERVICE, ATTR_NOW, ATTR_DOMAIN, ATTR_SERVICE, MATCH_ALL,
    EVENT_SERVICE_EXECUTED, ATTR_SERVICE_CALL_ID, EVENT_SERVICE_REGISTERED,
    TEMP_CELCIUS, TEMP_FAHRENHEIT, ATTR_FRIENDLY_NAME)
from homeassistant.exceptions import (
    HomeAssistantError, InvalidEntityFormatError)
import homeassistant.util as util
import homeassistant.util.dt as dt_util
import homeassistant.util.location as location
from homeassistant.helpers.entity import valid_entity_id, split_entity_id
import homeassistant.helpers.temperature as temp_helper
from homeassistant.config import get_default_config_dir

DOMAIN = "homeassistant"

# How often time_changed event should fire
TIMER_INTERVAL = 1  # seconds

# How long we wait for the result of a service call
SERVICE_CALL_LIMIT = 10  # seconds

# Define number of MINIMUM worker threads.
# During bootstrap of HA (see bootstrap._setup_component()) worker threads
# will be added for each component that polls devices.
MIN_WORKER_THREAD = 2

_LOGGER = logging.getLogger(__name__)

# Temporary to support deprecated methods
_MockHA = namedtuple("MockHomeAssistant", ['bus'])


class HomeAssistant(object):
    """Root object of the Home Assistant home automation."""

    def __init__(self):
        """Initialize new Home Assistant object."""
        self.pool = pool = create_worker_pool()
        self.bus = EventBus(pool)
        self.services = ServiceRegistry(self.bus, pool)
        self.states = StateMachine(self.bus)
        self.config = Config()

    def start(self):
        """Start home assistant."""
        _LOGGER.info(
            "Starting Home Assistant (%d threads)", self.pool.worker_count)

        create_timer(self)
        self.bus.fire(EVENT_HOMEASSISTANT_START)

    def block_till_stopped(self):
        """Register service homeassistant/stop and will block until called."""
        request_shutdown = threading.Event()
        request_restart = threading.Event()

        def stop_homeassistant(*args):
            """Stop Home Assistant."""
            request_shutdown.set()

        def restart_homeassistant(*args):
            """Reset Home Assistant."""
            request_restart.set()
            request_shutdown.set()

        self.services.register(
            DOMAIN, SERVICE_HOMEASSISTANT_STOP, stop_homeassistant)
        self.services.register(
            DOMAIN, SERVICE_HOMEASSISTANT_RESTART, restart_homeassistant)

        if os.name != "nt":
            try:
                signal.signal(signal.SIGTERM, stop_homeassistant)
            except ValueError:
                _LOGGER.warning(
                    'Could not bind to SIGQUIT. Are you running in a thread?')

        while not request_shutdown.isSet():
            try:
                time.sleep(1)
            except KeyboardInterrupt:
                break

        self.stop()
        return request_restart.isSet()

    def stop(self):
        """Stop Home Assistant and shuts down all threads."""
        _LOGGER.info("Stopping")

        self.bus.fire(EVENT_HOMEASSISTANT_STOP)

        # Wait till all responses to homeassistant_stop are done
        self.pool.block_till_done()<commit_msg>Cleaned up block_till_stop in core.py<commit_after>"""
Core components of Home Assistant.

Home Assistant is a Home Automation framework for observing the state
of entities and react to changes.
"""

import os
import time
import logging
import signal
import threading
import enum
import functools as ft
from collections import namedtuple

from homeassistant.const import (
    __version__, EVENT_HOMEASSISTANT_START, EVENT_HOMEASSISTANT_STOP,
    SERVICE_HOMEASSISTANT_STOP, SERVICE_HOMEASSISTANT_RESTART,
    EVENT_TIME_CHANGED, EVENT_STATE_CHANGED,
    EVENT_CALL_SERVICE, ATTR_NOW, ATTR_DOMAIN, ATTR_SERVICE, MATCH_ALL,
    EVENT_SERVICE_EXECUTED, ATTR_SERVICE_CALL_ID, EVENT_SERVICE_REGISTERED,
    TEMP_CELCIUS, TEMP_FAHRENHEIT, ATTR_FRIENDLY_NAME)
from homeassistant.exceptions import (
    HomeAssistantError, InvalidEntityFormatError)
import homeassistant.util as util
import homeassistant.util.dt as dt_util
import homeassistant.util.location as location
from homeassistant.helpers.entity import valid_entity_id, split_entity_id
import homeassistant.helpers.temperature as temp_helper
from homeassistant.config import get_default_config_dir

DOMAIN = "homeassistant"

# How often time_changed event should fire
TIMER_INTERVAL = 1  # seconds

# How long we wait for the result of a service call
SERVICE_CALL_LIMIT = 10  # seconds

# Define number of MINIMUM worker threads.
# During bootstrap of HA (see bootstrap._setup_component()) worker threads
# will be added for each component that polls devices.
MIN_WORKER_THREAD = 2

_LOGGER = logging.getLogger(__name__)

# Temporary to support deprecated methods
_MockHA = namedtuple("MockHomeAssistant", ['bus'])

# The exit code to send to request a restart
RESTART_EXIT_CODE = 100


class HomeAssistant(object):
    """Root object of the Home Assistant home automation."""

    def __init__(self):
        """Initialize new Home Assistant object."""
        self.pool = pool = create_worker_pool()
        self.bus = EventBus(pool)
        self.services = ServiceRegistry(self.bus, pool)
        self.states = StateMachine(self.bus)
        self.config = Config()

    def start(self):
        """Start home assistant."""
        _LOGGER.info(
            "Starting Home Assistant (%d threads)", self.pool.worker_count)

        create_timer(self)
        self.bus.fire(EVENT_HOMEASSISTANT_START)

    def block_till_stopped(self):
        """Register service homeassistant/stop and will block until called."""
        request_shutdown = threading.Event()
        request_restart = threading.Event()

        def stop_homeassistant(*args):
            """Stop Home Assistant."""
            request_shutdown.set()

        def restart_homeassistant(*args):
            """Reset Home Assistant."""
            request_restart.set()
            request_shutdown.set()

        self.services.register(
            DOMAIN, SERVICE_HOMEASSISTANT_STOP, stop_homeassistant)
        self.services.register(
            DOMAIN, SERVICE_HOMEASSISTANT_RESTART, restart_homeassistant)

        try:
            signal.signal(signal.SIGTERM, stop_homeassistant)
        except ValueError:
            _LOGGER.warning(
                'Could not bind to SIGTERM. Are you running in a thread?')

        while not request_shutdown.isSet():
            time.sleep(1)

        self.stop()
        return RESTART_EXIT_CODE if request_restart.isSet() else 0

    def stop(self):
        """Stop Home Assistant and shuts down all threads."""
        _LOGGER.info("Stopping")

        self.bus.fire(EVENT_HOMEASSISTANT_STOP)

        # Wait till all responses to homeassistant_stop are done
        self.pool.block_till_done()
{'fraction_non_alphanumeric': 0.07381634602264975, 'fraction_numerical': 0.0019102196752626551, 'mean_word_length': 3.2991202346041058, 'pattern_counts': {'":': 1, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4080885', 'n_tokens_mistral': 2106, 'n_tokens_neox': 2089, 'n_words': 579}