text:
"""Service calling related helpers."""
from __future__ import annotations

import asyncio
from collections.abc import Awaitable, Callable, Iterable
import dataclasses
from functools import partial, wraps
import logging
from typing import TYPE_CHECKING, Any, TypedDict, TypeVar

from typing_extensions import TypeGuard
import voluptuous as vol

from homeassistant.auth.permissions.const import CAT_ENTITIES, POLICY_CONTROL
from homeassistant.const import (
    ATTR_AREA_ID,
    ATTR_DEVICE_ID,
    ATTR_ENTITY_ID,
    CONF_ENTITY_ID,
    CONF_SERVICE,
    CONF_SERVICE_DATA,
    CONF_SERVICE_DATA_TEMPLATE,
    CONF_SERVICE_TEMPLATE,
    CONF_TARGET,
    ENTITY_MATCH_ALL,
    ENTITY_MATCH_NONE,
)
from homeassistant.core import Context, HomeAssistant, ServiceCall, callback
from homeassistant.exceptions import (
    HomeAssistantError,
    TemplateError,
    Unauthorized,
    UnknownUser,
)
from homeassistant.loader import Integration, async_get_integrations, bind_hass
from homeassistant.util.yaml import load_yaml
from homeassistant.util.yaml.loader import JSON_TYPE

from . import (
    area_registry,
    config_validation as cv,
    device_registry,
    entity_registry,
    template,
)
from .typing import ConfigType, TemplateVarsType

if TYPE_CHECKING:
    from .entity import Entity
    from .entity_platform import EntityPlatform

    _EntityT = TypeVar("_EntityT", bound=Entity)

CONF_SERVICE_ENTITY_ID = "entity_id"

_LOGGER = logging.getLogger(__name__)

SERVICE_DESCRIPTION_CACHE = "service_description_cache"

class ServiceParams(TypedDict):
    """Type for service call parameters."""

    domain: str
    service: str
    service_data: dict[str, Any]
    target: dict | None

class ServiceTargetSelector:
    """Class to hold a target selector for a service."""

    def __init__(self, service_call: ServiceCall) -> None:
        """Extract ids from service call data."""
        entity_ids: str | list | None = service_call.data.get(ATTR_ENTITY_ID)
        device_ids: str | list | None = service_call.data.get(ATTR_DEVICE_ID)
        area_ids: str | list | None = service_call.data.get(ATTR_AREA_ID)

        self.entity_ids = (
            set(cv.ensure_list(entity_ids)) if _has_match(entity_ids) else set()
        )
        self.device_ids = (
            set(cv.ensure_list(device_ids)) if _has_match(device_ids) else set()
        )
        self.area_ids = set(cv.ensure_list(area_ids)) if _has_match(area_ids) else set()

    @property
    def has_any_selector(self) -> bool:
        """Determine if any selectors are present."""
        return bool(self.entity_ids or self.device_ids or self.area_ids)

@dataclasses.dataclass
class SelectedEntities:
    """Class to hold the selected entities."""

    # Entities that were explicitly mentioned.
    referenced: set[str] = dataclasses.field(default_factory=set)

    # Entities that were referenced via device/area ID.
    # Should not trigger a warning when they don't exist.
    indirectly_referenced: set[str] = dataclasses.field(default_factory=set)

    # Referenced items that could not be found.
    missing_devices: set[str] = dataclasses.field(default_factory=set)
    missing_areas: set[str] = dataclasses.field(default_factory=set)

    # Referenced devices
    referenced_devices: set[str] = dataclasses.field(default_factory=set)

    def log_missing(self, missing_entities: set[str]) -> None:
        """Log about missing items."""
        parts = []
        for label, items in (
            ("areas", self.missing_areas),
            ("devices", self.missing_devices),
            ("entities", missing_entities),
        ):
            if items:
                parts.append(f"{label} {', '.join(sorted(items))}")

        if not parts:
            return

        _LOGGER.warning(
            "Unable to find referenced %s or it is/they are currently not available",
            ", ".join(parts),
        )

@bind_hass
def call_from_config(
    hass: HomeAssistant,
    config: ConfigType,
    blocking: bool = False,
    variables: TemplateVarsType = None,
    validate_config: bool = True,
) -> None:
    """Call a service based on a config hash."""
    asyncio.run_coroutine_threadsafe(
        async_call_from_config(hass, config, blocking, variables, validate_config),
        hass.loop,
    ).result()

@bind_hass
async def async_call_from_config(
    hass: HomeAssistant,
    config: ConfigType,
    blocking: bool = False,
    variables: TemplateVarsType = None,
    validate_config: bool = True,
    context: Context | None = None,
) -> None:
    """Call a service based on a config hash."""
    try:
        params = async_prepare_call_from_config(
            hass, config, variables, validate_config
        )
    except HomeAssistantError as ex:
        if blocking:
            raise
        _LOGGER.error(ex)
    else:
        await hass.services.async_call(**params, blocking=blocking, context=context)

@callback
@bind_hass
def async_prepare_call_from_config(
    hass: HomeAssistant,
    config: ConfigType,
    variables: TemplateVarsType = None,
    validate_config: bool = False,
) -> ServiceParams:
    """Prepare to call a service based on a config hash."""
    if validate_config:
        try:
            config = cv.SERVICE_SCHEMA(config)
        except vol.Invalid as ex:
            raise HomeAssistantError(
                f"Invalid config for calling service: {ex}"
            ) from ex

    if CONF_SERVICE in config:
        domain_service = config[CONF_SERVICE]
    else:
        domain_service = config[CONF_SERVICE_TEMPLATE]

    if isinstance(domain_service, template.Template):
        try:
            domain_service.hass = hass
            domain_service = domain_service.async_render(variables)
            domain_service = cv.service(domain_service)
        except TemplateError as ex:
            raise HomeAssistantError(
                f"Error rendering service name template: {ex}"
            ) from ex
        except vol.Invalid as ex:
            raise HomeAssistantError(
                f"Template rendered invalid service: {domain_service}"
            ) from ex

    domain, service = domain_service.split(".", 1)

    target = {}
    if CONF_TARGET in config:
        conf = config[CONF_TARGET]
        try:
            if isinstance(conf, template.Template):
                conf.hass = hass
                target.update(conf.async_render(variables))
            else:
                template.attach(hass, conf)
                target.update(template.render_complex(conf, variables))

            if CONF_ENTITY_ID in target:
                registry = entity_registry.async_get(hass)
                entity_ids = cv.comp_entity_ids_or_uuids(target[CONF_ENTITY_ID])
                if entity_ids not in (ENTITY_MATCH_ALL, ENTITY_MATCH_NONE):
                    entity_ids = entity_registry.async_validate_entity_ids(
                        registry, entity_ids
                    )
                target[CONF_ENTITY_ID] = entity_ids
        except TemplateError as ex:
            raise HomeAssistantError(
                f"Error rendering service target template: {ex}"
            ) from ex
        except vol.Invalid as ex:
            raise HomeAssistantError(
                f"Template rendered invalid entity IDs: {target[CONF_ENTITY_ID]}"
            ) from ex

    service_data = {}

    for conf in (CONF_SERVICE_DATA, CONF_SERVICE_DATA_TEMPLATE):
        if conf not in config:
            continue
        try:
            template.attach(hass, config[conf])
            render = template.render_complex(config[conf], variables)
            if not isinstance(render, dict):
                raise HomeAssistantError(
                    "Error rendering data template: Result is not a Dictionary"
                )
            service_data.update(render)
        except TemplateError as ex:
            raise HomeAssistantError(f"Error rendering data template: {ex}") from ex

    if CONF_SERVICE_ENTITY_ID in config:
        if target:
            target[ATTR_ENTITY_ID] = config[CONF_SERVICE_ENTITY_ID]
        else:
            target = {ATTR_ENTITY_ID: config[CONF_SERVICE_ENTITY_ID]}

    return {
        "domain": domain,
        "service": service,
        "service_data": service_data,
        "target": target,
    }

@bind_hass
def extract_entity_ids(
    hass: HomeAssistant, service_call: ServiceCall, expand_group: bool = True
) -> set[str]:
    """Extract a list of entity ids from a service call.

    Will convert group entity ids to the entity ids it represents.
    """
    return asyncio.run_coroutine_threadsafe(
        async_extract_entity_ids(hass, service_call, expand_group), hass.loop
    ).result()

@bind_hass
async def async_extract_entities(
    hass: HomeAssistant,
    entities: Iterable[_EntityT],
    service_call: ServiceCall,
    expand_group: bool = True,
) -> list[_EntityT]:
    """Extract a list of entity objects from a service call.

    Will convert group entity ids to the entity ids it represents.
    """
    data_ent_id = service_call.data.get(ATTR_ENTITY_ID)

    if data_ent_id == ENTITY_MATCH_ALL:
        return [entity for entity in entities if entity.available]

    referenced = async_extract_referenced_entity_ids(hass, service_call, expand_group)
    combined = referenced.referenced | referenced.indirectly_referenced

    found = []

    for entity in entities:
        if entity.entity_id not in combined:
            continue

        combined.remove(entity.entity_id)

        if not entity.available:
            continue

        found.append(entity)

    referenced.log_missing(referenced.referenced & combined)

    return found

@bind_hass
async def async_extract_entity_ids(
    hass: HomeAssistant, service_call: ServiceCall, expand_group: bool = True
) -> set[str]:
    """Extract a set of entity ids from a service call.

    Will convert group entity ids to the entity ids it represents.
    """
    referenced = async_extract_referenced_entity_ids(hass, service_call, expand_group)
    return referenced.referenced | referenced.indirectly_referenced

def _has_match(ids: str | list[str] | None) -> TypeGuard[str | list[str]]:
    """Check if ids can match anything."""
    return ids not in (None, ENTITY_MATCH_NONE)

@bind_hass
def async_extract_referenced_entity_ids(
    hass: HomeAssistant, service_call: ServiceCall, expand_group: bool = True
) -> SelectedEntities:
    """Extract referenced entity IDs from a service call."""
    selector = ServiceTargetSelector(service_call)
    selected = SelectedEntities()

    if not selector.has_any_selector:
        return selected

    entity_ids = selector.entity_ids
    if expand_group:
        entity_ids = hass.components.group.expand_entity_ids(entity_ids)

    selected.referenced.update(entity_ids)

    if not selector.device_ids and not selector.area_ids:
        return selected

    ent_reg = entity_registry.async_get(hass)
    dev_reg = device_registry.async_get(hass)
    area_reg = area_registry.async_get(hass)

    for device_id in selector.device_ids:
        if device_id not in dev_reg.devices:
            selected.missing_devices.add(device_id)

    for area_id in selector.area_ids:
        if area_id not in area_reg.areas:
            selected.missing_areas.add(area_id)

    # Find devices for targeted areas
    selected.referenced_devices.update(selector.device_ids)
    for device_entry in dev_reg.devices.values():
        if device_entry.area_id in selector.area_ids:
            selected.referenced_devices.add(device_entry.id)

    if not selector.area_ids and not selected.referenced_devices:
        return selected

    for ent_entry in ent_reg.entities.values():
        # Do not add entities which are hidden or which are config or diagnostic entities
        if ent_entry.entity_category is not None or ent_entry.hidden_by is not None:
            continue

        if (
            # The entity's area matches a targeted area
            ent_entry.area_id in selector.area_ids
            # The entity's device matches a device referenced by an area and the entity
            # has no explicitly set area
            or (
                not ent_entry.area_id
                and ent_entry.device_id in selected.referenced_devices
            )
            # The entity's device matches a targeted device
            or ent_entry.device_id in selector.device_ids
        ):
            selected.indirectly_referenced.add(ent_entry.entity_id)

    return selected

@bind_hass
async def async_extract_config_entry_ids(
    hass: HomeAssistant, service_call: ServiceCall, expand_group: bool = True
) -> set:
    """Extract referenced config entry ids from a service call."""
    referenced = async_extract_referenced_entity_ids(hass, service_call, expand_group)
    ent_reg = entity_registry.async_get(hass)
    dev_reg = device_registry.async_get(hass)
    config_entry_ids: set[str] = set()

    # Some devices may have no entities
    for device_id in referenced.referenced_devices:
        if (
            device_id in dev_reg.devices
            and (device := dev_reg.async_get(device_id)) is not None
        ):
            config_entry_ids.update(device.config_entries)

    for entity_id in referenced.referenced | referenced.indirectly_referenced:
        entry = ent_reg.async_get(entity_id)
        if entry is not None and entry.config_entry_id is not None:
            config_entry_ids.add(entry.config_entry_id)

    return config_entry_ids

def _load_services_file(hass: HomeAssistant, integration: Integration) -> JSON_TYPE:
    """Load services file for an integration."""
    try:
        return load_yaml(str(integration.file_path / "services.yaml"))
    except FileNotFoundError:
        _LOGGER.warning(
            "Unable to find services.yaml for the %s integration", integration.domain
        )
        return {}
    except HomeAssistantError:
        _LOGGER.warning(
            "Unable to parse services.yaml for the %s integration", integration.domain
        )
        return {}

def _load_services_files(
    hass: HomeAssistant, integrations: Iterable[Integration]
) -> list[JSON_TYPE]:
    """Load service files for multiple intergrations."""
    return [_load_services_file(hass, integration) for integration in integrations]

@bind_hass
async def async_get_all_descriptions(
    hass: HomeAssistant,
) -> dict[str, dict[str, Any]]:
    """Return descriptions (i.e. user documentation) for all service calls."""
    descriptions_cache = hass.data.setdefault(SERVICE_DESCRIPTION_CACHE, {})
    format_cache_key = "{}.{}".format
    services = hass.services.async_services()

    # See if there are new services not seen before.
    # Any service that we saw before already has an entry in description_cache.
    missing = set()
    for domain in services:
        for service in services[domain]:
            if format_cache_key(domain, service) not in descriptions_cache:
                missing.add(domain)
                break

    # Files we loaded for missing descriptions
    loaded = {}

    if missing:
        ints_or_excs = await async_get_integrations(hass, missing)
        integrations = [
            int_or_exc
            for int_or_exc in ints_or_excs.values()
            if isinstance(int_or_exc, Integration)
        ]

        contents = await hass.async_add_executor_job(
            _load_services_files, hass, integrations
        )

        for domain, content in zip(missing, contents):
            loaded[domain] = content

    # Build response
    descriptions: dict[str, dict[str, Any]] = {}
    for domain in services:
        descriptions[domain] = {}

        for service in services[domain]:
            cache_key = format_cache_key(domain, service)
            description = descriptions_cache.get(cache_key)

            # Cache missing descriptions
            if description is None:
                domain_yaml = loaded[domain]
                yaml_description = domain_yaml.get(service, {})  # type: ignore[union-attr]

                # Don't warn for missing services, because it triggers false
                # positives for things like scripts, that register as a service

                description = {
                    "name": yaml_description.get("name", ""),
                    "description": yaml_description.get("description", ""),
                    "fields": yaml_description.get("fields", {}),
                }

                if "target" in yaml_description:
                    description["target"] = yaml_description["target"]

                descriptions_cache[cache_key] = description

            descriptions[domain][service] = description

    return descriptions

@callback
@bind_hass
def async_set_service_schema(
    hass: HomeAssistant, domain: str, service: str, schema: dict[str, Any]
) -> None:
    """Register a description for a service."""
    hass.data.setdefault(SERVICE_DESCRIPTION_CACHE, {})

    description = {
        "name": schema.get("name", ""),
        "description": schema.get("description", ""),
        "fields": schema.get("fields", {}),
    }

    if "target" in schema:
        description["target"] = schema["target"]

    hass.data[SERVICE_DESCRIPTION_CACHE][f"{domain}.{service}"] = description

@bind_hass
async def entity_service_call(  # noqa: C901
    hass: HomeAssistant,
    platforms: Iterable[EntityPlatform],
    func: str | Callable[..., Any],
    call: ServiceCall,
    required_features: Iterable[int] | None = None,
) -> None:
    """Handle an entity service call.

    Calls all platforms simultaneously.
    """
    if call.context.user_id:
        user = await hass.auth.async_get_user(call.context.user_id)
        if user is None:
            raise UnknownUser(context=call.context)
        entity_perms: None | (
            Callable[[str, str], bool]
        ) = user.permissions.check_entity
    else:
        entity_perms = None

    target_all_entities = call.data.get(ATTR_ENTITY_ID) == ENTITY_MATCH_ALL

    if target_all_entities:
        referenced: SelectedEntities | None = None
        all_referenced: set[str] | None = None
    else:
        # A set of entities we're trying to target.
        referenced = async_extract_referenced_entity_ids(hass, call, True)
        all_referenced = referenced.referenced | referenced.indirectly_referenced

    # If the service function is a string, we'll pass it the service call data
    if isinstance(func, str):
        data: dict | ServiceCall = {
            key: val
            for key, val in call.data.items()
            if key not in cv.ENTITY_SERVICE_FIELDS
        }
    # If the service function is not a string, we pass the service call
    else:
        data = call

    # Check the permissions

    # A list with entities to call the service on.
    entity_candidates: list[Entity] = []

    if entity_perms is None:
        for platform in platforms:
            if target_all_entities:
                entity_candidates.extend(platform.entities.values())
            else:
                assert all_referenced is not None
                entity_candidates.extend(
                    [
                        entity
                        for entity in platform.entities.values()
                        if entity.entity_id in all_referenced
                    ]
                )

    elif target_all_entities:
        # If we target all entities, we will select all entities the user
        # is allowed to control.
        for platform in platforms:
            entity_candidates.extend(
                [
                    entity
                    for entity in platform.entities.values()
                    if entity_perms(entity.entity_id, POLICY_CONTROL)
                ]
            )

    else:
        assert all_referenced is not None

        for platform in platforms:
            platform_entities = []
            for entity in platform.entities.values():

                if entity.entity_id not in all_referenced:
                    continue

                if not entity_perms(entity.entity_id, POLICY_CONTROL):
                    raise Unauthorized(
                        context=call.context,
                        entity_id=entity.entity_id,
                        permission=POLICY_CONTROL,
                    )

                platform_entities.append(entity)

            entity_candidates.extend(platform_entities)

    if not target_all_entities:
        assert referenced is not None

        # Only report on explicit referenced entities
        missing = set(referenced.referenced)

        for entity in entity_candidates:
            missing.discard(entity.entity_id)

        referenced.log_missing(missing)

    entities = []

    for entity in entity_candidates:
        if not entity.available:
            continue

        # Skip entities that don't have the required feature.
        if required_features is not None and (
            entity.supported_features is None
            or not any(
                entity.supported_features & feature_set == feature_set
                for feature_set in required_features
            )
        ):
            # If entity explicitly referenced, raise an error
            if referenced is not None and entity.entity_id in referenced.referenced:
                raise HomeAssistantError(
                    f"Entity {entity.entity_id} does not support this service."
                )

            continue

        entities.append(entity)

    if not entities:
        return

    done, pending = await asyncio.wait(
        [
            asyncio.create_task(
                entity.async_request_call(
                    _handle_entity_call(hass, entity, func, data, call.context)
                )
            )
            for entity in entities
        ]
    )
    assert not pending
    for future in done:
        future.result()  # pop exception if have

    tasks = []

    for entity in entities:
        if not entity.should_poll:
            continue

        # Context expires if the turn on commands took a long time.
        # Set context again so it's there when we update
        entity.async_set_context(call.context)
        tasks.append(asyncio.create_task(entity.async_update_ha_state(True)))

    if tasks:
        done, pending = await asyncio.wait(tasks)
        assert not pending
        for future in done:
            future.result()  # pop exception if have

async def _handle_entity_call(
    hass: HomeAssistant,
    entity: Entity,
    func: str | Callable[..., Any],
    data: dict | ServiceCall,
    context: Context,
) -> None:
    """Handle calling service method."""
    entity.async_set_context(context)

    if isinstance(func, str):
        result = hass.async_run_job(partial(getattr(entity, func), **data))  # type: ignore[arg-type]
    else:
        result = hass.async_run_job(func, entity, data)

    # Guard because callback functions do not return a task when passed to async_run_job.
    if result is not None:
        await result

    if asyncio.iscoroutine(result):
        _LOGGER.error(
            "Service %s for %s incorrectly returns a coroutine object. Await result instead in service handler. Report bug to integration author",
            func,
            entity.entity_id,
        )
        await result

@bind_hass
@callback
def async_register_admin_service(
    hass: HomeAssistant,
    domain: str,
    service: str,
    service_func: Callable[[ServiceCall], Awaitable[None] | None],
    schema: vol.Schema = vol.Schema({}, extra=vol.PREVENT_EXTRA),
) -> None:
    """Register a service that requires admin access."""

    @wraps(service_func)
    async def admin_handler(call: ServiceCall) -> None:
        if call.context.user_id:
            user = await hass.auth.async_get_user(call.context.user_id)
            if user is None:
                raise UnknownUser(context=call.context)
            if not user.is_admin:
                raise Unauthorized(context=call.context)

        result = hass.async_run_job(service_func, call)
        if result is not None:
            await result

    hass.services.async_register(domain, service, admin_handler, schema)

@bind_hass
@callback
def verify_domain_control(
    hass: HomeAssistant, domain: str
) -> Callable[[Callable[[ServiceCall], Any]], Callable[[ServiceCall], Any]]:
    """Ensure permission to access any entity under domain in service call."""

    def decorator(
        service_handler: Callable[[ServiceCall], Any]
    ) -> Callable[[ServiceCall], Any]:
        """Decorate."""
        if not asyncio.iscoroutinefunction(service_handler):
            raise HomeAssistantError("Can only decorate async functions.")

        async def check_permissions(call: ServiceCall) -> Any:
            """Check user permission and raise before call if unauthorized."""
            if not call.context.user_id:
                return await service_handler(call)

            user = await hass.auth.async_get_user(call.context.user_id)

            if user is None:
                raise UnknownUser(
                    context=call.context,
                    permission=POLICY_CONTROL,
                    user_id=call.context.user_id,
                )

            reg = entity_registry.async_get(hass)

            authorized = False

            for entity in reg.entities.values():
                if entity.platform != domain:
                    continue

                if user.permissions.check_entity(entity.entity_id, POLICY_CONTROL):
                    authorized = True
                    break

            if not authorized:
                raise Unauthorized(
                    context=call.context,
                    permission=POLICY_CONTROL,
                    user_id=call.context.user_id,
                    perm_category=CAT_ENTITIES,
                )

            return await service_handler(call)

        return check_permissions

    return decorator

class ReloadServiceHelper:
    """Helper for reload services to minimize unnecessary reloads."""

    def __init__(self, service_func: Callable[[ServiceCall], Awaitable]) -> None:
        """Initialize ReloadServiceHelper."""
        self._service_func = service_func
        self._service_running = False
        self._service_condition = asyncio.Condition()

    async def execute_service(self, service_call: ServiceCall) -> None:
        """Execute the service.

        If a previous reload task if currently in progress, wait for it to finish first.
        Once the previous reload task has finished, one of the waiting tasks will be
        assigned to execute the reload, the others will wait for the reload to finish.
        """

        do_reload = False
        async with self._service_condition:
            if self._service_running:
                # A previous reload task is already in progress, wait for it to finish
                await self._service_condition.wait()

        async with self._service_condition:
            if not self._service_running:
                # This task will do the reload
                self._service_running = True
                do_reload = True
            else:
                # Another task will perform the reload, wait for it to finish
                await self._service_condition.wait()

        if do_reload:
            # Reload, then notify other tasks
            await self._service_func(service_call)
            async with self._service_condition:
                self._service_running = False
                self._service_condition.notify_all()


text:
module TestCustom(testCustom) where

import Control.Concurrent.Extra
import Control.Monad
import System.IO.Extra
import Data.IORef
import TestUtil

testCustom :: IO ()
testCustom = do
    testRaw "withTempFile" $ do
        xs <- replicateM 4 $ onceFork $ do
            replicateM_ 100 $ withTempFile (const $ return ())
            putChar '.'
        sequence_ xs
        putStrLn "done"

    testRaw "withTempDir" $ do
        xs <- replicateM 4 $ onceFork $ do
            replicateM_ 100 $ withTempDir (const $ return ())
            putChar '.'
        sequence_ xs
        putStrLn "done"

    testGen "retry" $ do
        ref <- newIORef 2
        retry 5 $ do modifyIORef ref pred; whenM ((/=) 0 <$> readIORef ref) $ fail "die"
        (==== 0) <$> readIORef ref

redpajama_set_name: RedPajamaGithub


text:
<link rel="import" href="../../../toolkit-ui/elements/g-icon.html"/>

<polymer-element name="pi-items-view" attributes="layout view items selected slow">
  <template>
    <link rel="stylesheet" href="../../../projects/pica/components/css/pi-items-view.css" />
    <link rel="stylesheet" href="../../../projects/pica/components/css/pi-layout-flex.css" />
    <link rel="stylesheet" href="../../../projects/pica/components/css/pi-layout.css" />

      <template repeat="{{viewItems}}">

{{title}}
                {{unread}}

{{desc}}

{{dummyText}}

                {{source}}
                  {{since}}

      </template>

        <g-icon src="../../projects/pica/images/refresh_lightreg.png"></g-icon>
          Load more articles

  </template>

</polymer-element>


text:
package com.ontraport.app.pages;

import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.How;
import org.openqa.selenium.support.PageFactory;

import com.ontraport.app.tools.AbstractPage;

public class MessageTemplate_ListAll extends AbstractPage
{

    protected String   url = "/#!/message_template";

    @FindBy(how = How.XPATH, using = "//body")
    private WebElement body;

    public MessageTemplate_ListAll sample () throws Exception
    {
        return PageFactory.initElements(driver, MessageTemplate_ListAll.class);
    }

}


text:
package com.dancingqueen.walladog.aws.downloader;

import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.util.Log;

import com.dancingqueen.walladog.aws.downloader.query.DownloadQueueProvider;
import com.dancingqueen.walladog.aws.downloader.query.DownloadState;
import com.dancingqueen.walladog.aws.downloader.query.QueryHelper;
import com.dancingqueen.walladog.aws.downloader.service.DownloadService;

import java.util.ArrayList;
import java.util.List;

public class HttpDownloadObserver {
    private final Context context;

    /** Log tag. */
    private static final String LOG_TAG = HttpDownloadObserver.class.getSimpleName();

    /** The download Id. */
    private long id;

    /** Bytes transferred so far. */
    private long bytesTransferred;

    /** File size of the download in bytes. */
    private long totalBytes;

    /** Destination file location. */
    private String fileLocation;

    /** Download url. */
    private String downloadUrl;

    /** The state of the download the last time this object was refreshed. */
    private DownloadState downloadState;

    /** The time at which this download was created. */
    private long creationTimestamp;

    /** Mime type. */
    private String mimeType;

    /** Title. */
    private String title;

    /** Map of listeners registered to this download observer. */
    /* package */ HttpDownloadListener downloadListener;

    /***
     * This enum of column indexes of the fields of the request to the data source.
     */
    private enum ColumnType {
        /** ID. */
        COL_ID(DownloadQueueProvider.COLUMN_DOWNLOAD_ID),
        /** Download url. */
        COL_URL(DownloadQueueProvider.COLUMN_DOWNLOAD_URL),
        /** File location. */
        COL_FILE_LOCATION(DownloadQueueProvider.COLUMN_DOWNLOAD_FILE_LOCATION),
        /**  Mime type. */
        COL_MIME_TYPE(DownloadQueueProvider.COLUMN_DOWNLOAD_MIME_TYPE),
        /** Bytes Transferred. */
        COL_BYTES_TRANSFERRED(DownloadQueueProvider.COLUMN_DOWNLOAD_CURRENT_SIZE),
        /** Total file size. */
        COL_FILE_SIZE(DownloadQueueProvider.COLUMN_DOWNLOAD_TOTAL_SIZE),
        /** Creation Time Stamp. */
        COL_CREATION_TIME_STAMP(DownloadQueueProvider.COLUMN_DOWNLOAD_CREATE_TIMESTAMP),
        /** Download State. */
        COL_DOWNLOAD_STATE(DownloadQueueProvider.COLUMN_DOWNLOAD_STATUS),
        /** Intent. */
        COL_INTENT_URI(DownloadQueueProvider.COLUMN_DOWNLOAD_INTENT_URI),
        /** Title. */
        COL_TITLE(DownloadQueueProvider.COLUMN_DOWNLOAD_TITLE);

        /** name of the column. */
        private final String columnName;

        /**
         * Set column name.
         * @param s the column name.
         */
        private ColumnType(final String s) {
            columnName = s;
        }

        /** Array of column names for the db query. */
        private static final String[] COLUMNS;
        static {
            COLUMNS = new String[ColumnType.values().length];
            for (ColumnType columnType : ColumnType.values()) {
                COLUMNS[columnType.ordinal()] = columnType.columnName;
            }
        };

        /**
         * @return column names.
         */
        public static String[] getColumnNames() {
            return COLUMNS;
        }
    }

    private HttpDownloadObserver(final Context context, final long downloadId, final Cursor row) {
        this.context = context.getApplicationContext();
        id = downloadId;
        setFromCursor(row);
        downloadListener = null;
    }

    public void setDownloadListener(final HttpDownloadListener listener) {
        if (listener == null) {
            if (downloadListener != null) {
                cleanDownloadListener();
            }
            return;
        }
        HttpDownloadUtility.getInstance(context)
            .addDownloadListener(fileLocation, listener);
        downloadListener = listener;
    }

    public void cleanDownloadListener() {
        if (downloadListener != null) {
            HttpDownloadUtility.getInstance(context)
                .removeDownloadListener(fileLocation, downloadListener);
            downloadListener = null;
        }
    }

    public void setFromCursor(final Cursor row) {
        downloadUrl = row.getString(ColumnType.COL_URL.ordinal());
        fileLocation = row.getString(ColumnType.COL_FILE_LOCATION.ordinal());
        bytesTransferred = row.getLong(ColumnType.COL_BYTES_TRANSFERRED.ordinal());
        totalBytes = row.getLong(ColumnType.COL_FILE_SIZE.ordinal());
        downloadState = DownloadState.valueOf(row.getString(ColumnType.COL_DOWNLOAD_STATE.ordinal()));
        mimeType = row.getString(ColumnType.COL_MIME_TYPE.ordinal());
        long startTime;
        try {
            startTime = row.getLong(ColumnType.COL_CREATION_TIME_STAMP.ordinal());
        } catch (Exception e) {
            Log.e(LOG_TAG, "Failed to parse download start time.", e);
            // mark user flags invalid (all false)
            startTime = 0L;
        }
        creationTimestamp = startTime;
        title = row.getString(ColumnType.COL_TITLE.ordinal());
    }

    private static Cursor queryForDownloadById(final Context context, final long id) {
        // run the database query
        final Cursor row = QueryHelper.runQueryForDownloadId(Long.toString(id),
            context, ColumnType.getColumnNames());
        return row;
    }

    /* package */ static HttpDownloadObserver getDownloadById(final Context context, final long id) {
        final Cursor row = queryForDownloadById(context, id);
        if (row == null) {
            return null;
        }
        try {
            return new HttpDownloadObserver(context, id, row);
        } finally {
            row.close();
        }
    }

    /* package */ static List<HttpDownloadObserver> getAllDownloadsByDownloadState(
                            final Context context, final DownloadState... downloadStates) {
        // build up the request and query for all downloads with in the specified states.
        return null;

    }

    /* package */ static List<HttpDownloadObserver> getAllDownloads(final Context context) {
        final ContentResolver resolver = context.getContentResolver();

        List<HttpDownloadObserver> downloadObservers = new ArrayList<>();

        final Cursor row = resolver.query(
            DownloadQueueProvider.getDownloadContentUri(context),
            ColumnType.getColumnNames(),
            null,
            null,
            null
        );

        if (row != null) {
            try {
                row.moveToFirst();
                while (!row.isAfterLast()) {
                    final long id = row.getLong(ColumnType.COL_ID.ordinal());
                    downloadObservers.add(new HttpDownloadObserver(context, id, row));
                    row.moveToNext();
                }
            } finally {
                row.close();
            }
        }

        return downloadObservers;
    }

    /**
     * Refresh fields from the database.
     */
    public boolean refresh() {
        final Cursor row;
        if (id != DownloadService.INVALID_ID) {
            row = queryForDownloadById(context, id);
            if (row == null) {
                return false;
            }
        } else {
            // query for download by file location.
            final String selectionCause = DownloadQueueProvider.COLUMN_DOWNLOAD_FILE_LOCATION + " = ?";
            final String[] selectionArgs = {fileLocation};
            row = QueryHelper.runQueryForDownloadRow(selectionCause, selectionArgs,
                context, ColumnType.getColumnNames());
            if (row == null) {
                return false;
            }
        }
        try {
            setFromCursor(row);
        } finally {
            row.close();
        }
        return true;
    }

    /**
     * @return The download id.
     */
    public long getId() {
        return id;
    }

    /**
     * @return The total bytes of the file being download.
     */
    public long getBytesTotal() {
        return totalBytes;
    }

    /**
     * @return The absolute path of the file transferred.
     */
    public String getAbsoluteFilePath() {
        return fileLocation;
    }

    public String getDownloadUrl() {
        return downloadUrl;
    }

    /**
     * @return The number of bytes currently downloaded.
     */
    public long getBytesTransferred() {
        return bytesTransferred;
    }

    /**
     * @return The state of the download.
     */
    public DownloadState getState() {
        return downloadState;
    }

    /**
     * @return The mime type of the download.
     */
    public String getMimeType() {
        return mimeType;
    }

    /**
     * @return The creation time stamp for download.
     */
    public long getCreationTimestamp() {
        return creationTimestamp;
    }

    /**
     * @return The title of the download.
     */
    public String getTitle() {
        return title;
    }
}


text:
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Xen2D;
using XenAspects;
using XenGameBase;

namespace Demo_ComplexElement2D
{
    public class ComplexElement : ComplexElement2D<ComplexElement>
    {
        RenderParams _renderParamsTemplate = RenderParams.Default;

        private StaticSprite _coloredRect = StaticSprite.Acquire( Textures.Get( TexId.ColoredRect ) );
        private StaticSprite _grayRect = StaticSprite.Acquire( Textures.Get( TexId.GrayRect ) );
        private CircularExtent _collisionExtent = CircularExtent.Acquire( new Vector2( 85, 85 ), 25 );
        private KeyboardMoveBehavior _moveBehavior;

        StaticSprite _markerAnchor_Blue;
        StaticSprite _markerTopLeft_Red;
        StaticSprite _markerCompositeAnchor_Green;

        public override IExtent CollisionExtent { get { return _collisionExtent; } }

        public ComplexElement()
        {
            _moveBehavior = KeyboardMoveBehavior.Acquire( this, 5.0f );

            _renderParamsTemplate.Mode = RenderMode.TraceBoundingBox | RenderMode.TraceLogicalExtent | RenderMode.TraceRenderingExtent;

            _markerAnchor_Blue = StaticSprite.Acquire( Textures.Get( TexId.Marker_Blue ), new Vector2( 4, 4 ) );
            _markerAnchor_Blue.LayerDepth = 0;
            _renderParamsTemplate.GetTexture_MarkCenter = new Getter<ISprite>( () => { return _markerAnchor_Blue; } );

            _markerTopLeft_Red = StaticSprite.Acquire( Textures.Get( TexId.Marker_Red ), new Vector2( 4, 4 ) );
            _markerTopLeft_Red.LayerDepth = 0;
            _renderParamsTemplate.GetTexture_MarkOrigin = new Getter<ISprite>( () => { return _markerTopLeft_Red; } );

            _markerCompositeAnchor_Green = StaticSprite.Acquire( Textures.Get( TexId.Marker_Green ), new Vector2( 4, 4 ) );
            _markerCompositeAnchor_Green.LayerDepth = 0;
            _renderParamsTemplate.GetTexture_MarkTopLeft = new Getter<ISprite>( () => { return _markerCompositeAnchor_Green; } );
        }

        public override void Reset()
        {
            base.Reset();
            Behaviors.Add( _moveBehavior );
            VisualComponents.AddExtent( _collisionExtent );
            VisualComponents.Add( _coloredRect );
            _grayRect.RenderingExtent.Anchor += new Vector2( 200, 200 );
            VisualComponents.Add( _grayRect );
        }

        protected override void DrawInternal( SpriteBatch spriteBatch, Matrix transformFromWorldToCamera )
        {
            //_spriteBatch.DrawSprite( _child1, worldToCamera, _renderParamsTemplate );
            //_spriteBatch.DrawSprite( _child2, worldToCamera, _renderParamsTemplate );
            //_spriteBatch.DrawPolygonExtent( _compositeExtent, worldToCamera, _renderParamsTemplate );
            base.DrawInternal( spriteBatch, transformFromWorldToCamera );
            spriteBatch.DrawExtent( CollisionExtent, Color.LimeGreen, transformFromWorldToCamera );
            spriteBatch.DrawPolygonExtent( _grayRect.RenderingExtent, transformFromWorldToCamera, _renderParamsTemplate );
            spriteBatch.DrawPolygonExtent( _coloredRect.RenderingExtent, transformFromWorldToCamera, _renderParamsTemplate );
        }
    }
}


text:
Documentation for Imspector
===========================

[![Documentation Status](https://readthedocs.org/projects/imspectordocs/badge/?version=latest)](http://imspectordocs.readthedocs.io/en/latest/?badge=latest)

What is Imspector
-----------------
Imspector is a software for image acquisition and analysis in high resolution microscopy. It is developed at the
Max Planck Institute of Biophysical Chemistry at the department of NanoBiophotonics and at the Abberior Instruments
GmbH.

Development Environment for this documentation
----------------------------------------------

1. have Python installed
1. have this repository cloned into `ImspectorDocs`
1. create and activate a python virtual environment
1. `pip install -U -r ImspectorDocs/requirements.txt`

After this you should be able to build the documentation:

1. `cd ImspectorDocs/docs/`
1. `make html` or `.\make.bat html`
1. now `ImspectorDocs\docs\_build\html` will contain the built docs

The documentation is built after each push. Read the latest version at
[ReadTheDocs.org](https://imspectordocs.readthedocs.io/).


text:
import whitespace from "./whitespace";
import * as parens from "./parentheses";
import each from "lodash/collection/each";
import some from "lodash/collection/some";
import isArray from "lodash/lang/isArray";
import * as t from "../../types";

/**
 * Test if node matches a set of type-matcher pairs.
 * @example
 * find({
 *   VariableDeclaration(node, parent) {
 *     return true;
 *   }
 * }, node, parent);
 */

var find = function (obj, node, parent) {
  if (!obj) return;
  var result;

  var types = Object.keys(obj);
  for (var i = 0; i < types.length; i++) {
    var type = types[i];

    if (t.is(type, node)) {
      var fn = obj[type];
      result = fn(node, parent);
      if (result != null) break;
    }
  }

  return result;
};

/**
 * Whitespace and Parenthesis related methods for nodes.
 */

export default class Node {
  constructor(node, parent) {
    this.parent = parent;
    this.node   = node;
  }

  /**
   * Test if `node` can have whitespace set by the user.
   */

  static isUserWhitespacable(node) {
    return t.isUserWhitespacable(node);
  }

  /**
   * Test if a `node` requires whitespace.
   */

  static needsWhitespace(node, parent, type) {
    if (!node) return 0;

    if (t.isExpressionStatement(node)) {
      node = node.expression;
    }

    var linesInfo = find(whitespace.nodes, node, parent);

    if (!linesInfo) {
      var items = find(whitespace.list, node, parent);
      if (items) {
        for (var i = 0; i < items.length; i++) {
          linesInfo = Node.needsWhitespace(items[i], node, type);
          if (linesInfo) break;
        }
      }
    }

    return (linesInfo && linesInfo[type]) || 0;
  }

  /**
   * Test if a `node` requires whitespace before it.
   */

  static needsWhitespaceBefore(node, parent) {
    return Node.needsWhitespace(node, parent, "before");
  }

  /**
   * Test if a `note` requires whitespace after it.
   */

  static needsWhitespaceAfter(node, parent) {
    return Node.needsWhitespace(node, parent, "after");
  }

  /**
   * Test if a `node` needs parentheses around it.
   */

  static needsParens(node, parent) {
    if (!parent) return false;

    if (t.isNewExpression(parent) && parent.callee === node) {
      if (t.isCallExpression(node)) return true;

      var hasCall = some(node, function (val) {
        return t.isCallExpression(val);
      });
      if (hasCall) return true;
    }

    return find(parens, node, parent);
  }

  static generateParens(node, parent) {
    let needsParens = Node.needsParens(node, parent);
    if (needsParens || node.parenthesizedExpression) {
      return 1;
    }
    return 0;
  }

  static nextSiblingMatches(node, parent, type) {
    if (!parent.body) {}
  }
}

/**
 * Add all static methods from `Node` to `Node.prototype`.
 */

each(Node, function (fn, key) {
  Node.prototype[key] = function () {
    // Avoid leaking arguments to prevent deoptimization
    var args = new Array(arguments.length + 2);

    args[0] = this.node;
    args[1] = this.parent;

    for (var i = 0; i < args.length; i++) {
      args[i + 2] = arguments[i];
    }

    return Node[key].apply(null, args);
  };
});


text:
package org.apache.hadoop.hive.metastore.datasource;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hive.metastore.conf.MetastoreConf;

/**
 * Create a DataSourceProvider for a connectionPool configured in a hadoop
 * Configuration object.
 */
public abstract  class DataSourceProviderFactory {
  private static final ImmutableList<DataSourceProvider> FACTORIES = ImmutableList.of(
    new HikariCPDataSourceProvider(),
    new BoneCPDataSourceProvider(),
    new DbCPDataSourceProvider());

  /**
   * The data source providers declare if they are supported or not based on the config.
   * This function looks through all the data source providers and picks the first one which is
   * supported. If no data source provider is found, returns a null.
   *
   * @param hdpConfig hadoop configuration
   * @return factory for the configured datanucleus.connectionPoolingType or null if no supported
   *         data source providers are found.
   */
  public static DataSourceProvider tryGetDataSourceProviderOrNull(Configuration hdpConfig) {
    final String configuredPoolingType = MetastoreConf.getVar(hdpConfig,
        MetastoreConf.ConfVars.CONNECTION_POOLING_TYPE);
    return Iterables.tryFind(FACTORIES, factory -> {
      String poolingType = factory.getPoolingType();
      return poolingType != null && poolingType.equalsIgnoreCase(configuredPoolingType);
    }).orNull();
  }
}


text:
require 'rails_helper'

module Integral
  module Backend
    describe BaseController do
      routes { Integral::Engine.routes }

      controller do
        def after_sign_in_path_for(resource)
          super resource
        end

        def index
          raise Pundit::NotAuthorizedError
        end
      end

      let(:user) { create(:user) }

      describe "after sigin-in" do
        it "redirects to user dashboard" do
          expect(controller.after_sign_in_path_for(user)).to eq Engine.routes.url_helpers.backend_dashboard_path
        end
      end

      describe "layout_by_resource" do
        context 'when devise controller' do
          before do
            allow(subject).to receive(:devise_controller?).and_return true
          end

          it 'renders custom devise layout' do
            expect(controller.send(controller.class.send(:_layout))).to eq 'integral/login'
          end
        end

        context 'when not devise controller' do
          it 'renders standard layout' do
            expect(controller.send(controller.class.send(:_layout))).to eq 'integral/backend'
          end
        end
      end
    end
  end
end


text:
module Ivory.BSP.STM32F427.ATIM18
  ( ATIM(..)
  , tim1
  , tim8
  , module Ivory.BSP.STM32.Peripheral.ATIM18.Regs
  , module Ivory.BSP.STM32.Peripheral.ATIM18.RegTypes
  ) where

import Ivory.BSP.STM32.Peripheral.ATIM18.Peripheral
import Ivory.BSP.STM32.Peripheral.ATIM18.Regs
import Ivory.BSP.STM32.Peripheral.ATIM18.RegTypes

import Ivory.Language
import Ivory.HW

import Ivory.BSP.STM32F427.RCC
import Ivory.BSP.STM32F427.MemoryMap

tim1 :: ATIM
tim1 = mkATIM tim1_periph_base
          (rccEnable rcc_apb2en_tim1)
          (rccDisable rcc_apb2en_tim1)
          "tim1"

tim8 :: ATIM
tim8 = mkATIM tim8_periph_base
          (rccEnable rcc_apb2en_tim8)
          (rccDisable rcc_apb2en_tim8)
          "tim8"

-- TIM1 and TIM8 are in APB2
rccEnable :: BitDataField RCC_APB2ENR Bit -> Ivory eff ()
rccEnable f = modifyReg regRCC_APB2ENR $ setBit f
rccDisable :: BitDataField RCC_APB2ENR Bit -> Ivory eff ()
rccDisable f = modifyReg regRCC_APB2ENR $ clearBit f


text:
package net.nitram509.gateways.api;

public class Gateway implements Comparable<Gateway> {

  private final GatewayId gatewayId;
  private UserId owner;
  private String suffix;
  private int activity;

  public Gateway(GatewayId gatewayId) {
    this.gatewayId = gatewayId;
  }

  public GatewayId getId() {
    return gatewayId;
  }

  public UserId getOwner() {
    return owner;
  }

  public void setOwner(UserId owner) {
    this.owner = owner;
  }

  public int getActivity() {
    return activity;
  }

  public void setActivity(int activity) {
    this.activity = activity;
  }

  public String getSuffix() {
    return suffix;
  }

  public void setSuffix(String suffix) {
    this.suffix = suffix;
  }

  @Override
  public int compareTo(Gateway o) {
    return this.gatewayId.getId().compareTo(o.gatewayId.getId());
  }
}


text:
/* eslint-disable */

'use strict';

/*::
import type { Fragment, ReaderFragment } from 'relay-runtime';
import type { FragmentType } from "relay-runtime";
declare export opaque type preloadQueryDEPRECATEDTest_ProvidedVarFragment$fragmentType: FragmentType;
export type preloadQueryDEPRECATEDTest_ProvidedVarFragment$data = {|
  +name?: ?string,
  +firstName?: ?string,
  +lastName?: ?string,
  +username?: ?string,
  +$fragmentType: preloadQueryDEPRECATEDTest_ProvidedVarFragment$fragmentType,
|};
export type preloadQueryDEPRECATEDTest_ProvidedVarFragment$key = {
  +$data?: preloadQueryDEPRECATEDTest_ProvidedVarFragment$data,
  +$fragmentSpreads: preloadQueryDEPRECATEDTest_ProvidedVarFragment$fragmentType,
  ...
};
*/

var node/*: ReaderFragment*/ = (function(){
var v0 = {
  "kind": "RootArgument",
  "name": "__relay_internal__pv__RelayProvider_returnsFalse"
},
v1 = {
  "kind": "RootArgument",
  "name": "__relay_internal__pv__RelayProvider_returnsTrue"
};
return {
  "argumentDefinitions": [
    (v0/*: any*/),
    (v0/*: any*/),
    (v1/*: any*/),
    (v1/*: any*/)
  ],
  "kind": "Fragment",
  "metadata": null,
  "name": "preloadQueryDEPRECATEDTest_ProvidedVarFragment",
  "selections": [
    {
      "condition": "__relay_internal__pv__RelayProvider_returnsTrue",
      "kind": "Condition",
      "passingValue": true,
      "selections": [
        {
          "alias": null,
          "args": null,
          "kind": "ScalarField",
          "name": "name",
          "storageKey": null
        }
      ]
    },
    {
      "condition": "__relay_internal__pv__RelayProvider_returnsFalse",
      "kind": "Condition",
      "passingValue": true,
      "selections": [
        {
          "alias": null,
          "args": null,
          "kind": "ScalarField",
          "name": "firstName",
          "storageKey": null
        }
      ]
    },
    {
      "condition": "__relay_internal__pv__RelayProvider_returnsFalse",
      "kind": "Condition",
      "passingValue": false,
      "selections": [
        {
          "alias": null,
          "args": null,
          "kind": "ScalarField",
          "name": "lastName",
          "storageKey": null
        }
      ]
    },
    {
      "condition": "__relay_internal__pv__RelayProvider_returnsTrue",
      "kind": "Condition",
      "passingValue": false,
      "selections": [
        {
          "alias": null,
          "args": null,
          "kind": "ScalarField",
          "name": "username",
          "storageKey": null
        }
      ]
    }
  ],
  "type": "User",
  "abstractKey": null
};
})();

if (__DEV__) {
  (node/*: any*/).hash = "6ccd0faa2d0e7e65107135efa23e2de2";
}

module.exports = ((node/*: any*/)/*: Fragment<
  preloadQueryDEPRECATEDTest_ProvidedVarFragment$fragmentType,
  preloadQueryDEPRECATEDTest_ProvidedVarFragment$data,
>*/);


text:
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type

import base64
import inspect
import os
import re
import shlex
import traceback
import json

HAVE_KERBEROS = False
try:
    import kerberos
    HAVE_KERBEROS = True
except ImportError:
    pass

from ansible.compat.six import string_types
from ansible.compat.six.moves.urllib.parse import urlunsplit
from ansible.errors import AnsibleError, AnsibleConnectionFailure
from ansible.errors import AnsibleFileNotFound
from ansible.module_utils._text import to_bytes, to_native, to_text
from ansible.plugins.connection import ConnectionBase
from ansible.utils.hashing import secure_hash
from ansible.utils.path import makedirs_safe

try:
    import winrm
    from winrm import Response
    from winrm.protocol import Protocol
except ImportError:
    raise AnsibleError("winrm is not installed")

try:
    import xmltodict
except ImportError:
    raise AnsibleError("xmltodict is not installed")

try:
    from __main__ import display
except ImportError:
    from ansible.utils.display import Display
    display = Display()

class Connection(ConnectionBase):
    '''WinRM connections over HTTP/HTTPS.'''

    transport = 'winrm'
    module_implementation_preferences = ('.ps1', '.exe', '')
    become_methods = []
    allow_executable = False

    def __init__(self,  *args, **kwargs):

        self.has_pipelining   = False
        self.protocol         = None
        self.shell_id         = None
        self.delegate         = None
        self._shell_type      = 'powershell'

        # FUTURE: Add runas support

        super(Connection, self).__init__(*args, **kwargs)

    def set_host_overrides(self, host, hostvars=None):
        '''
        Override WinRM-specific options from host variables.
        '''
        self._winrm_host = self._play_context.remote_addr
        self._winrm_port = int(self._play_context.port or 5986)
        self._winrm_scheme = hostvars.get('ansible_winrm_scheme', 'http' if self._winrm_port == 5985 else 'https')
        self._winrm_path = hostvars.get('ansible_winrm_path', '/wsman')
        self._winrm_user = self._play_context.remote_user
        self._winrm_pass = self._play_context.password

        if hasattr(winrm, 'FEATURE_SUPPORTED_AUTHTYPES'):
            self._winrm_supported_authtypes = set(winrm.FEATURE_SUPPORTED_AUTHTYPES)
        else:
            # for legacy versions of pywinrm, use the values we know are supported
            self._winrm_supported_authtypes = set(['plaintext','ssl','kerberos'])

        # TODO: figure out what we want to do with auto-transport selection in the face of NTLM/Kerb/CredSSP/Cert/Basic
        transport_selector = 'ssl' if self._winrm_scheme == 'https' else 'plaintext'

        if HAVE_KERBEROS and ((self._winrm_user and '@' in self._winrm_user)):
            self._winrm_transport = 'kerberos,%s' % transport_selector
        else:
            self._winrm_transport = transport_selector
        self._winrm_transport = hostvars.get('ansible_winrm_transport', self._winrm_transport)
        if isinstance(self._winrm_transport, string_types):
            self._winrm_transport = [x.strip() for x in self._winrm_transport.split(',') if x.strip()]

        unsupported_transports = set(self._winrm_transport).difference(self._winrm_supported_authtypes)

        if unsupported_transports:
            raise AnsibleError('The installed version of WinRM does not support transport(s) %s' % list(unsupported_transports))

        # arg names we're going passing directly
        internal_kwarg_mask = set(['self', 'endpoint', 'transport', 'username', 'password', 'scheme', 'path'])

        self._winrm_kwargs = dict(username=self._winrm_user, password=self._winrm_pass)
        argspec = inspect.getargspec(Protocol.__init__)
        supported_winrm_args = set(argspec.args)
        supported_winrm_args.update(internal_kwarg_mask)
        passed_winrm_args = set([v.replace('ansible_winrm_', '') for v in hostvars if v.startswith('ansible_winrm_')])
        unsupported_args = passed_winrm_args.difference(supported_winrm_args)

        # warn for kwargs unsupported by the installed version of pywinrm
        for arg in unsupported_args:
            display.warning("ansible_winrm_{0} unsupported by pywinrm (is an up-to-date version of pywinrm installed?)".format(arg))

        # pass through matching kwargs, excluding the list we want to treat specially
        for arg in passed_winrm_args.difference(internal_kwarg_mask).intersection(supported_winrm_args):
            self._winrm_kwargs[arg] = hostvars['ansible_winrm_%s' % arg]

    def _winrm_connect(self):
        '''
        Establish a WinRM connection over HTTP/HTTPS.
        '''
        display.vvv("ESTABLISH WINRM CONNECTION FOR USER: %s on PORT %s TO %s" %
            (self._winrm_user, self._winrm_port, self._winrm_host), host=self._winrm_host)
        netloc = '%s:%d' % (self._winrm_host, self._winrm_port)
        endpoint = urlunsplit((self._winrm_scheme, netloc, self._winrm_path, '', ''))
        errors = []
        for transport in self._winrm_transport:
            if transport == 'kerberos' and not HAVE_KERBEROS:
                errors.append('kerberos: the python kerberos library is not installed')
                continue
            display.vvvvv('WINRM CONNECT: transport=%s endpoint=%s' % (transport, endpoint), host=self._winrm_host)
            try:
                protocol = Protocol(endpoint, transport=transport, **self._winrm_kwargs)

                # open the shell from connect so we know we're able to talk to the server
                if not self.shell_id:
                    self.shell_id = protocol.open_shell(codepage=65001)  # UTF-8
                    display.vvvvv('WINRM OPEN SHELL: %s' % self.shell_id, host=self._winrm_host)

                return protocol
            except Exception as e:
                err_msg = to_text(e).strip()
                if re.search(to_text(r'Operation\s+?timed\s+?out'), err_msg, re.I):
                    raise AnsibleError('the connection attempt timed out')
                m = re.search(to_text(r'Code\s+?(\d{3})'), err_msg)
                if m:
                    code = int(m.groups()[0])
                    if code == 401:
                        err_msg = 'the specified credentials were rejected by the server'
                    elif code == 411:
                        return protocol
                errors.append(u'%s: %s' % (transport, err_msg))
                display.vvvvv(u'WINRM CONNECTION ERROR: %s\n%s' % (err_msg, to_text(traceback.format_exc())), host=self._winrm_host)
        if errors:
            raise AnsibleConnectionFailure(', '.join(map(to_native, errors)))
        else:
            raise AnsibleError('No transport found for WinRM connection')

    def _winrm_send_input(self, protocol, shell_id, command_id, stdin, eof=False):
        rq = {'env:Envelope': protocol._get_soap_header(
            resource_uri='http://schemas.microsoft.com/wbem/wsman/1/windows/shell/cmd',
            action='http://schemas.microsoft.com/wbem/wsman/1/windows/shell/Send',
            shell_id=shell_id)}
        stream = rq['env:Envelope'].setdefault('env:Body', {}).setdefault('rsp:Send', {})\
            .setdefault('rsp:Stream', {})
        stream['@Name'] = 'stdin'
        stream['@CommandId'] = command_id
        stream['#text'] = base64.b64encode(to_bytes(stdin))
        if eof:
            stream['@End'] = 'true'
        protocol.send_message(xmltodict.unparse(rq))

    def _winrm_exec(self, command, args=(), from_exec=False, stdin_iterator=None):
        if not self.protocol:
            self.protocol = self._winrm_connect()
            self._connected = True
        if from_exec:
            display.vvvvv("WINRM EXEC %r %r" % (command, args), host=self._winrm_host)
        else:
            display.vvvvvv("WINRM EXEC %r %r" % (command, args), host=self._winrm_host)
        command_id = None
        try:
            stdin_push_failed = False
            command_id = self.protocol.run_command(self.shell_id, to_bytes(command), map(to_bytes, args), console_mode_stdin=(stdin_iterator is None))

            # TODO: try/except around this, so we can get/return the command result on a broken pipe or other failure (probably more useful than the 500 that comes from this)
            try:
                if stdin_iterator:
                    for (data, is_last) in stdin_iterator:
                        self._winrm_send_input(self.protocol, self.shell_id, command_id, data, eof=is_last)

            except Exception as ex:
                from traceback import format_exc
                display.warning("FATAL ERROR DURING FILE TRANSFER: %s" % format_exc(ex))
                stdin_push_failed = True

            if stdin_push_failed:
                raise AnsibleError('winrm send_input failed')

            # NB: this can hang if the receiver is still running (eg, network failed a Send request but the server's still happy).
            # FUTURE: Consider adding pywinrm status check/abort operations to see if the target is still running after a failure.
            response = Response(self.protocol.get_command_output(self.shell_id, command_id))

            # TODO: check result from response and set stdin_push_failed if we have nonzero
            if from_exec:
                display.vvvvv('WINRM RESULT %r' % to_text(response), host=self._winrm_host)
            else:
                display.vvvvvv('WINRM RESULT %r' % to_text(response), host=self._winrm_host)

            display.vvvvvv('WINRM STDOUT %s' % to_text(response.std_out), host=self._winrm_host)
            display.vvvvvv('WINRM STDERR %s' % to_text(response.std_err), host=self._winrm_host)

            if stdin_push_failed:
                raise AnsibleError('winrm send_input failed; \nstdout: %s\nstderr %s' % (response.std_out, response.std_err))

            return response
        finally:
            if command_id:
                self.protocol.cleanup_command(self.shell_id, command_id)

    def _connect(self):
        super(Connection, self)._connect()
        if not self.protocol:
            self.protocol = self._winrm_connect()
            self._connected = True
        return self

    def _reset(self):  # used by win_reboot (and any other action that might need to bounce the state)
        self.protocol = None
        self.shell_id = None
        self._connect()

    def exec_command(self, cmd, in_data=None, sudoable=True):
        super(Connection, self).exec_command(cmd, in_data=in_data, sudoable=sudoable)
        cmd_parts = shlex.split(to_bytes(cmd), posix=False)
        cmd_parts = map(to_text, cmd_parts)
        script = None
        cmd_ext = cmd_parts and self._shell._unquote(cmd_parts[0]).lower()[-4:] or ''
        # Support running .ps1 files (via script/raw).
        if cmd_ext == '.ps1':
            script = '& %s' % cmd
        # Support running .bat/.cmd files; change back to the default system encoding instead of UTF-8.
        elif cmd_ext in ('.bat', '.cmd'):
            script = '[System.Console]::OutputEncoding = [System.Text.Encoding]::Default; & %s' % cmd
        # Encode the command if not already encoded; supports running simple PowerShell commands via raw.
        elif '-EncodedCommand' not in cmd_parts:
            script = cmd
        if script:
            cmd_parts = self._shell._encode_script(script, as_list=True, strict_mode=False)
        if '-EncodedCommand' in cmd_parts:
            encoded_cmd = cmd_parts[cmd_parts.index('-EncodedCommand') + 1]
            decoded_cmd = to_text(base64.b64decode(encoded_cmd).decode('utf-16-le'))
            display.vvv("EXEC %s" % decoded_cmd, host=self._winrm_host)
        else:
            display.vvv("EXEC %s" % cmd, host=self._winrm_host)
        try:
            result = self._winrm_exec(cmd_parts[0], cmd_parts[1:], from_exec=True)
        except Exception:
            traceback.print_exc()
            raise AnsibleConnectionFailure("failed to exec cmd %s" % cmd)
        result.std_out = to_bytes(result.std_out)
        result.std_err = to_bytes(result.std_err)

        # parse just stderr from CLIXML output
        if self.is_clixml(result.std_err):
            try:
                result.std_err = self.parse_clixml_stream(result.std_err)
            except:
                # unsure if we're guaranteed a valid xml doc- use raw output in case of error
                pass

        return (result.status_code, result.std_out, result.std_err)

    def is_clixml(self, value):
        return value.startswith("#< CLIXML")

    # hacky way to get just stdout- not always sure of doc framing here, so use with care
    def parse_clixml_stream(self, clixml_doc, stream_name='Error'):
        clear_xml = clixml_doc.replace('#< CLIXML\r\n', '')
        doc = xmltodict.parse(clear_xml)
        lines = [l.get('#text', '').replace('_x000D__x000A_', '') for l in doc.get('Objs', {}).get('S', {}) if l.get('@S') == stream_name]
        return '\r\n'.join(lines)

    # FUTURE: determine buffer size at runtime via remote winrm config?
    def _put_file_stdin_iterator(self, in_path, out_path, buffer_size=250000):
        in_size = os.path.getsize(to_bytes(in_path, errors='surrogate_or_strict'))
        offset = 0
        with open(to_bytes(in_path, errors='surrogate_or_strict'), 'rb') as in_file:
            for out_data in iter((lambda:in_file.read(buffer_size)), ''):
                offset += len(out_data)
                self._display.vvvvv('WINRM PUT "%s" to "%s" (offset=%d size=%d)' % (in_path, out_path, offset, len(out_data)), host=self._winrm_host)
                # yes, we're double-encoding over the wire in this case- we want to ensure that the data shipped to the end PS pipeline is still b64-encoded
                b64_data = base64.b64encode(out_data) + '\r\n'
                # cough up the data, as well as an indicator if this is the last chunk so winrm_send knows to set the End signal
                yield b64_data, (in_file.tell() == in_size)

            if offset == 0:  # empty file, return an empty buffer + eof to close it
                yield "", True

    def put_file(self, in_path, out_path):
        super(Connection, self).put_file(in_path, out_path)
        out_path = self._shell._unquote(out_path)
        display.vvv('PUT "%s" TO "%s"' % (in_path, out_path), host=self._winrm_host)
        if not os.path.exists(to_bytes(in_path, errors='surrogate_or_strict')):
            raise AnsibleFileNotFound('file or module does not exist: "%s"' % in_path)

        script_template = u'''
            begin {{
                $path = '{0}'

                $DebugPreference = "Continue"
                $ErrorActionPreference = "Stop"
                Set-StrictMode -Version 2

                $fd = [System.IO.File]::Create($path)

                $sha1 = [System.Security.Cryptography.SHA1CryptoServiceProvider]::Create()

                $bytes = @() #initialize for empty file case
            }}
            process {{
               $bytes = [System.Convert]::FromBase64String($input)
               $sha1.TransformBlock($bytes, 0, $bytes.Length, $bytes, 0) | Out-Null
               $fd.Write($bytes, 0, $bytes.Length)
            }}
            end {{
                $sha1.TransformFinalBlock($bytes, 0, 0) | Out-Null

                $hash = [System.BitConverter]::ToString($sha1.Hash).Replace("-", "").ToLowerInvariant()

                $fd.Close()

                Write-Output "{{""sha1"":""$hash""}}"
            }}
        '''

        script = script_template.format(self._shell._escape(out_path))
        cmd_parts = self._shell._encode_script(script, as_list=True, strict_mode=False)

        result = self._winrm_exec(cmd_parts[0], cmd_parts[1:], stdin_iterator=self._put_file_stdin_iterator(in_path, out_path))
        # TODO: improve error handling
        if result.status_code != 0:
            raise AnsibleError(to_native(result.std_err))

        put_output = json.loads(result.std_out)
        remote_sha1 = put_output.get("sha1")

        if not remote_sha1:
            raise AnsibleError("Remote sha1 was not returned")

        local_sha1 = secure_hash(in_path)

        if not remote_sha1 == local_sha1:
            raise AnsibleError("Remote sha1 hash {0} does not match local hash {1}".format(to_native(remote_sha1), to_native(local_sha1)))

    def fetch_file(self, in_path, out_path):
        super(Connection, self).fetch_file(in_path, out_path)
        in_path = self._shell._unquote(in_path)
        out_path = out_path.replace('\\', '/')
        display.vvv('FETCH "%s" TO "%s"' % (in_path, out_path), host=self._winrm_host)
        buffer_size = 2**19  # 0.5MB chunks
        makedirs_safe(os.path.dirname(out_path))
        out_file = None
        try:
            offset = 0
            while True:
                try:
                    script = '''
                        If (Test-Path -PathType Leaf "%(path)s")
                        {
                            $stream = [System.IO.File]::OpenRead("%(path)s");
                            $stream.Seek(%(offset)d, [System.IO.SeekOrigin]::Begin) | Out-Null;
                            $buffer = New-Object Byte[] %(buffer_size)d;
                            $bytesRead = $stream.Read($buffer, 0, %(buffer_size)d);
                            $bytes = $buffer[0..($bytesRead-1)];
                            [System.Convert]::ToBase64String($bytes);
                            $stream.Close() | Out-Null;
                        }
                        ElseIf (Test-Path -PathType Container "%(path)s")
                        {
                            Write-Host "[DIR]";
                        }
                        Else
                        {
                            Write-Error "%(path)s does not exist";
                            Exit 1;
                        }
                    ''' % dict(buffer_size=buffer_size, path=self._shell._escape(in_path), offset=offset)
                    display.vvvvv('WINRM FETCH "%s" to "%s" (offset=%d)' % (in_path, out_path, offset), host=self._winrm_host)
                    cmd_parts = self._shell._encode_script(script, as_list=True)
                    result = self._winrm_exec(cmd_parts[0], cmd_parts[1:])
                    if result.status_code != 0:
                        raise IOError(to_native(result.std_err))
                    if result.std_out.strip() == '[DIR]':
                        data = None
                    else:
                        data = base64.b64decode(result.std_out.strip())
                    if data is None:
                        makedirs_safe(out_path)
                        break
                    else:
                        if not out_file:
                            # If out_path is a directory and we're expecting a file, bail out now.
                            if os.path.isdir(to_bytes(out_path, errors='surrogate_or_strict')):
                                break
                            out_file = open(to_bytes(out_path, errors='surrogate_or_strict'), 'wb')
                        out_file.write(data)
                        if len(data) < buffer_size:
                            break
                        offset += len(data)
                except Exception:
                    traceback.print_exc()
                    raise AnsibleError('failed to transfer file to "%s"' % out_path)
        finally:
            if out_file:
                out_file.close()

    def close(self):
        if self.protocol and self.shell_id:
            display.vvvvv('WINRM CLOSE SHELL: %s' % self.shell_id, host=self._winrm_host)
            self.protocol.close_shell(self.shell_id)
        self.shell_id = None
        self.protocol = None
        self._connected = False


text:
<?php

namespace MailSo\Net\Exceptions;

/**
 * @category MailSo
 * @package Net
 * @subpackage Exceptions
 */
class ConnectionException extends \MailSo\Net\Exceptions\Exception {}


text:
#include "config.h"
#include "modules/mediastream/RTCDataChannel.h"

#include "bindings/v8/ExceptionState.h"
#include "core/events/Event.h"
#include "core/dom/ExceptionCode.h"
#include "core/dom/ExecutionContext.h"
#include "core/events/MessageEvent.h"
#include "core/fileapi/Blob.h"
#include "core/platform/mediastream/RTCDataChannelHandler.h"
#include "core/platform/mediastream/RTCPeerConnectionHandler.h"
#include "wtf/ArrayBuffer.h"
#include "wtf/ArrayBufferView.h"

namespace WebCore {

static void throwNotOpenException(ExceptionState& exceptionState)
{
    exceptionState.throwDOMException(InvalidStateError, "RTCDataChannel.readyState is not 'open'");
}

static void throwCouldNotSendDataException(ExceptionState& exceptionState)
{
    exceptionState.throwDOMException(NetworkError, "Could not send data");
}

static void throwNoBlobSupportException(ExceptionState& exceptionState)
{
    exceptionState.throwDOMException(NotSupportedError, "Blob support not implemented yet");
}

PassRefPtr<RTCDataChannel> RTCDataChannel::create(ExecutionContext* context, PassOwnPtr<RTCDataChannelHandler> handler)
{
    ASSERT(handler);
    return adoptRef(new RTCDataChannel(context, handler));
}

PassRefPtr<RTCDataChannel> RTCDataChannel::create(ExecutionContext* context, RTCPeerConnectionHandler* peerConnectionHandler, const String& label, const blink::WebRTCDataChannelInit& init, ExceptionState& exceptionState)
{
    OwnPtr<RTCDataChannelHandler> handler = peerConnectionHandler->createDataChannel(label, init);
    if (!handler) {
        exceptionState.throwDOMException(NotSupportedError, "RTCDataChannel is not supported");
        return 0;
    }
    return adoptRef(new RTCDataChannel(context, handler.release()));
}

RTCDataChannel::RTCDataChannel(ExecutionContext* context, PassOwnPtr<RTCDataChannelHandler> handler)
    : m_executionContext(context)
    , m_handler(handler)
    , m_stopped(false)
    , m_readyState(ReadyStateConnecting)
    , m_binaryType(BinaryTypeArrayBuffer)
    , m_scheduledEventTimer(this, &RTCDataChannel::scheduledEventTimerFired)
{
    ScriptWrappable::init(this);
    m_handler->setClient(this);
}

RTCDataChannel::~RTCDataChannel()
{
}

String RTCDataChannel::label() const
{
    return m_handler->label();
}

bool RTCDataChannel::reliable() const
{
    return m_handler->isReliable();
}

bool RTCDataChannel::ordered() const
{
    return m_handler->ordered();
}

unsigned short RTCDataChannel::maxRetransmitTime() const
{
    return m_handler->maxRetransmitTime();
}

unsigned short RTCDataChannel::maxRetransmits() const
{
    return m_handler->maxRetransmits();
}

String RTCDataChannel::protocol() const
{
    return m_handler->protocol();
}

bool RTCDataChannel::negotiated() const
{
    return m_handler->negotiated();
}

unsigned short RTCDataChannel::id() const
{
    return m_handler->id();
}

String RTCDataChannel::readyState() const
{
    switch (m_readyState) {
    case ReadyStateConnecting:
        return "connecting";
    case ReadyStateOpen:
        return "open";
    case ReadyStateClosing:
        return "closing";
    case ReadyStateClosed:
        return "closed";
    }

    ASSERT_NOT_REACHED();
    return String();
}

unsigned long RTCDataChannel::bufferedAmount() const
{
    return m_handler->bufferedAmount();
}

String RTCDataChannel::binaryType() const
{
    switch (m_binaryType) {
    case BinaryTypeBlob:
        return "blob";
    case BinaryTypeArrayBuffer:
        return "arraybuffer";
    }
    ASSERT_NOT_REACHED();
    return String();
}

void RTCDataChannel::setBinaryType(const String& binaryType, ExceptionState& exceptionState)
{
    if (binaryType == "blob")
        throwNoBlobSupportException(exceptionState);
    else if (binaryType == "arraybuffer")
        m_binaryType = BinaryTypeArrayBuffer;
    else
        exceptionState.throwDOMException(TypeMismatchError, "Unknown binary type : " + binaryType);
}

void RTCDataChannel::send(const String& data, ExceptionState& exceptionState)
{
    if (m_readyState != ReadyStateOpen) {
        throwNotOpenException(exceptionState);
        return;
    }
    if (!m_handler->sendStringData(data)) {
        // FIXME: This should not throw an exception but instead forcefully close the data channel.
        throwCouldNotSendDataException(exceptionState);
    }
}

void RTCDataChannel::send(PassRefPtr<ArrayBuffer> prpData, ExceptionState& exceptionState)
{
    if (m_readyState != ReadyStateOpen) {
        throwNotOpenException(exceptionState);
        return;
    }

    RefPtr<ArrayBuffer> data = prpData;

    size_t dataLength = data->byteLength();
    if (!dataLength)
        return;

    const char* dataPointer = static_cast<const char*>(data->data());

    if (!m_handler->sendRawData(dataPointer, dataLength)) {
        // FIXME: This should not throw an exception but instead forcefully close the data channel.
        throwCouldNotSendDataException(exceptionState);
    }
}

void RTCDataChannel::send(PassRefPtr<ArrayBufferView> data, ExceptionState& exceptionState)
{
    RefPtr<ArrayBuffer> arrayBuffer(data->buffer());
    send(arrayBuffer.release(), exceptionState);
}

void RTCDataChannel::send(PassRefPtr<Blob> data, ExceptionState& exceptionState)
{
    // FIXME: implement
    throwNoBlobSupportException(exceptionState);
}

void RTCDataChannel::close()
{
    if (m_stopped)
        return;

    m_handler->close();
}

void RTCDataChannel::didChangeReadyState(ReadyState newState)
{
    if (m_stopped || m_readyState == ReadyStateClosed)
        return;

    m_readyState = newState;

    switch (m_readyState) {
    case ReadyStateOpen:
        scheduleDispatchEvent(Event::create(EventTypeNames::open));
        break;
    case ReadyStateClosed:
        scheduleDispatchEvent(Event::create(EventTypeNames::close));
        break;
    default:
        break;
    }
}

void RTCDataChannel::didReceiveStringData(const String& text)
{
    if (m_stopped)
        return;

    scheduleDispatchEvent(MessageEvent::create(text));
}

void RTCDataChannel::didReceiveRawData(const char* data, size_t dataLength)
{
    if (m_stopped)
        return;

    if (m_binaryType == BinaryTypeBlob) {
        // FIXME: Implement.
        return;
    }
    if (m_binaryType == BinaryTypeArrayBuffer) {
        RefPtr<ArrayBuffer> buffer = ArrayBuffer::create(data, dataLength);
        scheduleDispatchEvent(MessageEvent::create(buffer.release()));
        return;
    }
    ASSERT_NOT_REACHED();
}

void RTCDataChannel::didDetectError()
{
    if (m_stopped)
        return;

    scheduleDispatchEvent(Event::create(EventTypeNames::error));
}

const AtomicString& RTCDataChannel::interfaceName() const
{
    return EventTargetNames::RTCDataChannel;
}

ExecutionContext* RTCDataChannel::executionContext() const
{
    return m_executionContext;
}

void RTCDataChannel::stop()
{
    m_stopped = true;
    m_readyState = ReadyStateClosed;
    m_handler->setClient(0);
    m_executionContext = 0;
}

void RTCDataChannel::scheduleDispatchEvent(PassRefPtr<Event> event)
{
    m_scheduledEvents.append(event);

    if (!m_scheduledEventTimer.isActive())
        m_scheduledEventTimer.startOneShot(0);
}

void RTCDataChannel::scheduledEventTimerFired(Timer<RTCDataChannel>*)
{
    if (m_stopped)
        return;

    Vector<RefPtr<Event> > events;
    events.swap(m_scheduledEvents);

    Vector<RefPtr<Event> >::iterator it = events.begin();
    for (; it != events.end(); ++it)
        dispatchEvent((*it).release());

    events.clear();
}

} // namespace WebCore


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SlackAPI
{
    public class DirectMessageConversation
    {
        public string id;
        public string user;
        public DateTime created;
        public bool is_user_deleted;
        public bool is_open;
        public bool is_starred;
        public DateTime last_read;
        public Message latest;
        public int unread_count;
    }
}


text:
// The MIT License (MIT)
//
// Copyright (c) 2014 Tristan Reeves
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
//
using System;
using System.IO;
using SharpConfig.Config;

namespace SharpConfig
{
    class ProgramRunner
    {
        private readonly ProgramOptions m_Options;
        private readonly IConfigurationTopLevel m_ConfigurationTopLevel;

        private void Prepare(string inputFilename)
        {
            m_Options.CreateOutputDirectory(inputFilename);

            foreach (var environment in m_ConfigurationTopLevel.EnumerateEnvironments())
            {
                var outputFile = m_Options.GetOutputFileForInputFile(inputFilename, environment);
                File.Delete(outputFile);
            }
        }

        public ProgramRunner(ProgramOptions options, IConfigurationTopLevel configurationTopLevel)
        {
            m_Options = options;
            m_ConfigurationTopLevel = configurationTopLevel;
        }

        public void Execute(string inputFilename)
        {
            Prepare(inputFilename);
            var inputContents = File.ReadAllText(inputFilename);
            Action copybackContinuation = null;

            foreach (var environment in m_ConfigurationTopLevel.EnumerateEnvironments())
            {
                var config = m_ConfigurationTopLevel.GetEnvironment(environment);
                var transformed = config.TransformInput(inputContents);

                var outputFile = m_Options.GetOutputFileForInputFile(inputFilename, environment);
                File.WriteAllText(outputFile, transformed);

                if (copybackContinuation == null)
                {
                    var copybackFile = m_Options.GetCopybackOutputFileForInputFile(inputFilename);
                    copybackContinuation = GetCopyBackDefaultEnvironmentContinuationIfAppropriate(environment, outputFile, copybackFile);
                }
            }

            if (copybackContinuation != null) copybackContinuation();
        }

        private Action GetCopyBackDefaultEnvironmentContinuationIfAppropriate(string environment, string sourceFile, string targetFile)
        {
            if (m_Options.DefaultEnvironment.Trim().ToLower() != environment.Trim().ToLower()) return null;
            return () => File.Copy(sourceFile, targetFile, true);
        }
    }
}


text:
package org.gradoop.temporal.io.impl.csv.tuples;

import org.apache.flink.api.java.tuple.Tuple4;

/**
 * Tuple representing a temporal graph head in a CSV file.
 *

 * The tuple fields are:
 *

 *
the ID, as a String

 *
the label

 *
the properties, encoded as a String according to the meta data

 *
the temporal data (transaction- and valid-times)

 *

 */
public class TemporalCSVGraphHead extends Tuple4<String, String, String, String>
  implements TemporalCSVElement {

  @Override
  public String getId() {
    return f0;
  }

  @Override
  public void setId(String id) {
    f0 = id;
  }

  @Override
  public String getLabel() {
    return f1;
  }

  @Override
  public void setLabel(String label) {
    f1 = label;
  }

  @Override
  public String getProperties() {
    return f2;
  }

  @Override
  public void setProperties(String properties) {
    f2 = properties;
  }

  @Override
  public void setTemporalData(String temporalData) {
    f3 = temporalData;
  }
}


text:
<?php

namespace spec\GorkaLaucirica\HipchatAPIv2Client\Model;

use PhpSpec\ObjectBehavior;
use Prophecy\Argument;

class WebhookSpec extends ObjectBehavior
{
    function it_is_initializable()
    {
        $this->shouldHaveType('GorkaLaucirica\HipchatAPIv2Client\Model\Webhook');
    }

    function it_parses_full_json()
    {
        $json = array(
            'id' => '123556',
            'url' => 'http://example.com/webhook',
            'pattern' => '/phpspec/',
            'event' => 'room_message',
            'name' => 'phpspec-webhok',
            'links' => array('self' => 'http://example.com'),
        );
        $this->parseJson($json);
        $this->getId()->shouldReturn('123556');
    }

    function it_serializes_to_array()
    {
        $this->setId('123212')
            ->seturl('http://example.com/webhook')
            ->setPattern('/phpspec/')
            ->setEvent('room_message')
            ->setName('phpspec_serialize')
            ->setLinks(array('self' => 'http://example.com'));

        $this->toJson()->shouldHaveCount(6);
    }

    function its_id_is_mutable()
    {
        $this->setId('112233')->shouldReturn($this);
        $this->getId()->shouldReturn('112233');
    }

    function its_url_is_mutable()
    {
        $this->setUrl('http://example.com/webhook')->shouldReturn($this);
        $this->getUrl()->shouldReturn('http://example.com/webhook');
    }

    function its_pattern_is_mutable()
    {
        $this->setPattern('/phpspec/')->shouldReturn($this);
        $this->getPattern()->shouldReturn('/phpspec/');
    }

    function its_event_is_mutable()
    {
        $this->setEvent('room_enter')->shouldReturn($this);
        $this->getEvent()->shouldReturn('room_enter');
    }

    function its_name_is_mutable()
    {
        $this->setName('phpspec_test')->shouldReturn($this);
        $this->getName()->shouldReturn('phpspec_test');
    }

    function its_links_is_mutable()
    {
        $links = array('self' => 'http://example.com');
        $this->setLinks($links)->shouldReturn($this);
        $this->getLinks()->shouldReturn($links);
    }
}


text:
package com.reagroup.robot.exception.parse;

/**
 * This class represents a sub class of {@link ParseException}
 * which is related to all of the syntax parsing exceptions.
 * For example if the int value is required but it is provided in other format.
 *
 * @author Ali
 */

public class RequestParseException extends ParseException {
	public RequestParseException() {
		super();
	}

	public RequestParseException(String msg) {
		super(msg);
	}

	public RequestParseException(String msg, Exception e) {
		super(msg, e);
	}
}


text:
import * as actions from './../actions/actionConstants';

const initialState = {
  isFetching: false,
  error: '',
  reservations: null,
  lastUpdated: null
};

export default (state = initialState, action) => {
  switch (action.type) {
    case actions.GET_ALL_RESERVATIONS:
      return {
        ...state,
        isFetching: true
      }

    case actions.GET_ALL_RESERVATIONS_SUCCESS:
     return {
       ...state,
       isFetching: false,
       reservations: action.reservations,
       lastUpdate: new Date()
     }

    case actions.GET_ALL_RESERVATIONS_ERROR:
      return {
        ...state,
        isFetching: false,
        error: action.error
      }

    default:
      return state;
  }
};


text:
echo '<?xml version="1.0" encoding="UTF-8" standalone="no"?><!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>
  <entry key="com.bigdata.rdf.sail.namespace">knowledge</entry>
  <entry key="com.bigdata.rdf.store.AbstractTripleStore.quads">true</entry>
  <entry key="com.bigdata.rdf.sail.truthMaintenance">false</entry>
  <entry key="com.bigdata.rdf.store.AbstractTripleStore.textIndex">true</entry>
</properties>
' | curl -v -X POST --data-binary @- --header 'Content-Type:application/xml' http://localhost:9999/blazegraph/namespace


text:
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Text;

namespace NXLDownloader
{
    public class ProductEntry
    {
        [JsonProperty(PropertyName = "product_id")]
        public string ProductId;
        public string ip_block_status;
        public bool IsIpBlock;
        public string ProductLink;
    }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.9.1"/>
<title>libguac: guacamole/plugin.h File Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

libguac
    0.9.8

Main Page

Data Structures

Files

          <input type="text" id="MSearchField" value="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

File List

Globals

guacamole

Data Structures |
Functions

plugin.h File Reference

Provides functions and structures required for handling a client plugin.
More...

Go to the source code of this file.

Data Structures

struct  	guac_client_plugin

 	A handle to a client plugin, containing enough information about the plugin to complete the initial protocol handshake and instantiate a new client supporting the protocol provided by the client plugin.  More...

Functions

guac_client_plugin * 	guac_client_plugin_open (const char *protocol)

 	Open the plugin which provides support for the given protocol, if it exists.  More...

int 	guac_client_plugin_close (guac_client_plugin *plugin)

 	Close the given plugin, releasing all associated resources.  More...

int 	guac_client_plugin_init_client (guac_client_plugin *plugin, guac_client *client, int argc, char **argv)

 	Initializes the given guac_client using the initialization routine provided by the given guac_client_plugin.  More...

Detailed Description

Provides functions and structures required for handling a client plugin.

Function Documentation

          int guac_client_plugin_close
          (
          guac_client_plugin *
          plugin	)

Close the given plugin, releasing all associated resources.

This function must be called after use of a client plugin is finished.

Parameters

plugin	The client plugin to close.

Returns

Zero on success, non-zero if an error occurred while releasing the resources associated with the plugin.

          int guac_client_plugin_init_client
          (
          guac_client_plugin *
          plugin,

          guac_client *
          client,

          int
          argc,

          char **
          argv

          )

Initializes the given guac_client using the initialization routine provided by the given guac_client_plugin.

Parameters

plugin	The client plugin to use to initialize the new client.

client	The guac_client to initialize.

argc	The number of arguments being passed to the client.

argv	All arguments to be passed to the client.

Returns

Zero if initialization was successful, non-zero otherwise.

          guac_client_plugin* guac_client_plugin_open
          (
          const char *
          protocol	)

Open the plugin which provides support for the given protocol, if it exists.

Parameters

protocol	The name of the protocol to retrieve the client plugin for.

Returns

The client plugin supporting the given protocol, or NULL if an error occurs or no such plugin exists.

<address class="footer">
Generated on Tue Sep 8 2015 22:32:39 for libguac by

 1.8.9.1
</address>


text:
class C_BaseNetworkedPlayer : public C_BasePlayer {
public:
	DECLARE_CLASS(C_BaseNetworkedPlayer,C_BasePlayer);
	DECLARE_CLIENTCLASS();
	DECLARE_PREDICTABLE();
	C_BaseNetworkedPlayer();

	virtual void Respawn(); // Spawn() is called once, this is called every time

	void ReceiveMessage( int classID, bf_read &msg );

	// Implement multiplayer ragdolls
	virtual C_BaseAnimating* BecomeRagdollOnClient();
	virtual IRagdoll* GetRepresentativeRagdoll() const;

	virtual bool ShouldReceiveProjectedTextures( int flags ) { return true; }

	// Implement CMultiplayerAnimState
	virtual void DoAnimationEvent( PlayerAnimEvent_t event, int nData = 0 );
	virtual void UpdateClientSideAnimation();
	virtual void PostDataUpdate( DataUpdateType_t updateType );
	virtual const QAngle& EyeAngles();
	virtual const QAngle& GetRenderAngles();
protected:
	void MakeAnimState();
	CMultiPlayerAnimState* m_PlayerAnimState;

	QAngle	m_angEyeAngles;
	bool	m_bSpawnInterpCounter;
	bool	m_bSpawnInterpCounterCache;
	CInterpolatedVar<QAngle>	m_iv_angEyeAngles;
	EHANDLE	m_hRagdoll;
};

// -------------------------------------------------------------------------------- //
// Player animation event. Sent to the client when a player fires, jumps, reloads, etc..
// -------------------------------------------------------------------------------- //

class C_TEPlayerAnimEvent : public C_BaseTempEntity
{
public:
	DECLARE_CLASS( C_TEPlayerAnimEvent, C_BaseTempEntity );
	DECLARE_CLIENTCLASS();

	virtual void PostDataUpdate( DataUpdateType_t updateType );

public:
	CNetworkHandle( CBasePlayer, m_hPlayer );
	CNetworkVar( int, m_iEvent );
	//CNetworkVar( int, m_nData );
};