text:
<!DOCTYPE html>

<meta content="text/html;charset=utf-8" http-equiv="content-type"/>

<meta content="text/html; charset=utf-8" http-equiv="Content-Type"/>
<title>pymel.core.nodetypes.ColorManagementGlobals — PyMEL 1.0.7 documentation</title>
<link href="../../../_static/nature.css" rel="stylesheet" type="text/css"/>
<link href="../../../_static/pygments.css" rel="stylesheet" type="text/css"/>

<link href="../../../index-2.html" rel="top" title="PyMEL 1.0.7 documentation"/>
<link href="../../pymel.core.nodetypes.html" rel="up" title="pymel.core.nodetypes"/>
<link href="pymel.core.nodetypes.ColorProfile.html" rel="next" title="pymel.core.nodetypes.ColorProfile"/>
<link href="pymel.core.nodetypes.CollisionModel.html" rel="prev" title="pymel.core.nodetypes.CollisionModel"/>
<link href="../../../../style/adsk.cpm.css" rel="stylesheet" type="text/css"/><meta content="expert" name="experiencelevel"/><meta content="programmer" name="audience"/><meta content="enable" name="user-comments"/><meta content="ENU" name="language"/><meta content="MAYAUL" name="product"/><meta content="2016" name="release"/><meta content="Customization" name="book"/><meta content="Maya-Tech-Docs" name="component"/><meta content="/view/MAYAUL/2016/ENU/" name="helpsystempath"/><meta content="04/03/2015" name="created"/><meta content="04/03/2015" name="modified"/><meta content="Navigation

 index

 modules |

 next |

 previous |
 PyMEL 1.0.7 documentation »
 pymel.core.nodetypes »

 pymel.core.nodetypes.ColorManagementGlobals ¶

 class ColorManagementGlobals ( *args , **kwargs ) ¶

 MAttrClass = Enum( EnumValue('MAttrClass', 1, 'localDynamicAttr'), EnumValue('MAttrClass', 2, 'normalAttr'), EnumValue('MAttrClass', 3, 'extensionAttr'), EnumValue('MAttrClass', 4, 'invalidAttr')) ¶..." name="description"/><meta content="__PyMel_generated_classes_pymel_core_nodetypes_pymel_core_nodetypes_ColorManagementGlobals_html" name="topicid"/>

Navigation

index

modules |

next |

previous |

PyMEL 1.0.7 documentation »

pymel.core.nodetypes »

pymel.core.nodetypes.ColorManagementGlobals¶

<map id="inheritance5ab74348ef" name="inheritance5ab74348ef">
<area alt="" coords="5,121,151,145" href="#pymel.core.nodetypes.ColorManagementGlobals" id="node1" shape="rect" title="ColorManagementGlobals"></area>
<area alt="" coords="36,83,120,107" href="pymel.core.nodetypes.DependNode.html#pymel.core.nodetypes.DependNode" id="node2" shape="rect" title="DependNode"></area>
<area alt="" coords="42,44,114,68" href="../pymel.core.general/pymel.core.general.PyNode.html#pymel.core.general.PyNode" id="node3" shape="rect" title="Abstract class that is base for all pymel nodes classes."></area>
<area alt="" coords="34,5,122,29" href="../pymel.util.utilitytypes/pymel.util.utilitytypes.ProxyUnicode.html#pymel.util.utilitytypes.ProxyUnicode" id="node4" shape="rect" title="ProxyUnicode"></area>
</map>

class <tt class="descname">ColorManagementGlobals</tt><big>(</big>*args, **kwargs<big>)</big>¶

<tt class="descname">MAttrClass</tt> = Enum( EnumValue('MAttrClass', 1, 'localDynamicAttr'), EnumValue('MAttrClass', 2, 'normalAttr'), EnumValue('MAttrClass', 3, 'extensionAttr'), EnumValue('MAttrClass', 4, 'invalidAttr'))¶

<tt class="descname">MdgTimerMetric</tt> = Enum( EnumValue('MdgTimerMetric', 0, 'metric_callback'), EnumValue('MdgTimerMetric', 1, 'metric_compute'), EnumValue('MdgTimerMetric', 2, 'metric_dirty'), EnumValue('MdgTimerMetric', 3, 'metric_draw'), EnumValue('MdgTimerMetric', 4, 'metric_fetch'), EnumValue('MdgTimerMetric', 5, 'metric_callbackViaAPI'), EnumValue('MdgTimerMetric', 6, 'metric_callbackNotViaAPI'), EnumValue('MdgTimerMetric', 7, 'metric_computeDuringCallback'), EnumValue('MdgTimerMetric', 8, 'metric_computeNotDuringCallback'), EnumValue('MdgTimerMetric', 9, 'metrics'))¶

<tt class="descname">MdgTimerState</tt> = Enum( EnumValue('MdgTimerState', 0, 'off'), EnumValue('MdgTimerState', 1, 'on'), EnumValue('MdgTimerState', 2, 'uninitialized'), EnumValue('MdgTimerState', 3, 'invalidState'))¶

<tt class="descname">MdgTimerType</tt> = Enum( EnumValue('MdgTimerType', 0, 'type_self'), EnumValue('MdgTimerType', 1, 'type_inclusive'), EnumValue('MdgTimerType', 2, 'type_count'), EnumValue('MdgTimerType', 3, 'types'))¶

Previous topic

pymel.core.nodetypes.CollisionModel

Next topic

pymel.core.nodetypes.ColorProfile

Core Modules

<tt class="xref">animation</tt>

<tt class="xref">effects</tt>

<tt class="xref">general</tt>

<tt class="xref">language</tt>

<tt class="xref">modeling</tt>

<tt class="xref">rendering</tt>

<tt class="xref">system</tt>

<tt class="xref">windows</tt>

Type Modules

<tt class="xref">datatypes</tt>

<tt class="xref">nodetypes</tt>

<tt class="xref">uitypes</tt>

Other Modules

<tt class="xref">plugins</tt>

<tt class="xref">mayautils</tt>

<tt class="xref">util</tt>

<tt class="xref">versions</tt>

<tt class="xref">tools</tt>

This Page

Show Source

Quick search

<form action="http://help.autodesk.com/cloudhelp/2016/ENU/Maya-Tech-Docs/PyMel/search.html" class="search" method="get"></form>
<input name="q" type="text"/>
<input type="submit" value="Go"/>
<input name="check_keywords" type="hidden" value="yes"/>
<input name="area" type="hidden" value="default"/>

    Enter search terms or a module, class or function name.

Navigation

index

modules |

next |

previous |

PyMEL 1.0.7 documentation »

pymel.core.nodetypes »

        © Copyright 2009, Chad Dombrova.
      Created using Sphinx 1.2.3.


text:
package kafka.api

import java.nio._
import kafka.api.ApiUtils._
import kafka.network.{BoundedByteBufferSend, RequestChannel, InvalidRequestException}
import kafka.common.ErrorMapping
import kafka.network.RequestChannel.Response
import kafka.utils.Logging

object StopReplicaRequest extends Logging {
  val CurrentVersion = 0.shortValue
  val DefaultClientId = ""
  val DefaultAckTimeout = 100

  def readFrom(buffer: ByteBuffer): StopReplicaRequest = {
    val versionId = buffer.getShort
    val correlationId = buffer.getInt
    val clientId = readShortString(buffer)
    val ackTimeoutMs = buffer.getInt
    val controllerId = buffer.getInt
    val controllerEpoch = buffer.getInt
    val deletePartitions = buffer.get match {
      case 1 => true
      case 0 => false
      case x =>
        throw new InvalidRequestException("Invalid byte %d in delete partitions field. (Assuming false.)".format(x))
    }
    val topicPartitionPairCount = buffer.getInt
    val topicPartitionPairSet = new collection.mutable.HashSet[(String, Int)]()
    (1 to topicPartitionPairCount) foreach { _ =>
      topicPartitionPairSet.add(readShortString(buffer), buffer.getInt)
    }
    StopReplicaRequest(versionId, correlationId, clientId, ackTimeoutMs, controllerId, controllerEpoch,
                       deletePartitions, topicPartitionPairSet.toSet)
  }
}

case class StopReplicaRequest(versionId: Short,
                              override val correlationId: Int,
                              clientId: String,
                              ackTimeoutMs: Int,
                              controllerId: Int,
                              controllerEpoch: Int,
                              deletePartitions: Boolean,
                              partitions: Set[(String, Int)])
        extends RequestOrResponse(Some(RequestKeys.StopReplicaKey), correlationId) {

  def this(deletePartitions: Boolean, partitions: Set[(String, Int)], controllerId: Int, controllerEpoch: Int, correlationId: Int) = {
    this(StopReplicaRequest.CurrentVersion, correlationId, StopReplicaRequest.DefaultClientId, StopReplicaRequest.DefaultAckTimeout,
         controllerId, controllerEpoch, deletePartitions, partitions)
  }

  def writeTo(buffer: ByteBuffer) {
    buffer.putShort(versionId)
    buffer.putInt(correlationId)
    writeShortString(buffer, clientId)
    buffer.putInt(ackTimeoutMs)
    buffer.putInt(controllerId)
    buffer.putInt(controllerEpoch)
    buffer.put(if (deletePartitions) 1.toByte else 0.toByte)
    buffer.putInt(partitions.size)
    for ((topic, partitionId) <- partitions){
      writeShortString(buffer, topic)
      buffer.putInt(partitionId)
    }
  }

  def sizeInBytes(): Int = {
    var size =
      2 + /* versionId */
      4 + /* correlation id */
      ApiUtils.shortStringLength(clientId) +
      4 + /* ackTimeoutMs */
      4 + /* controller id*/
      4 + /* controller epoch */
      1 + /* deletePartitions */
      4 /* partition count */
    for ((topic, partitionId) <- partitions){
      size += (ApiUtils.shortStringLength(topic)) +
              4 /* partition id */
    }
    size
  }

  override def toString(): String = {
    val stopReplicaRequest = new StringBuilder
    stopReplicaRequest.append("Name: " + this.getClass.getSimpleName)
    stopReplicaRequest.append("; Version: " + versionId)
    stopReplicaRequest.append("; CorrelationId: " + correlationId)
    stopReplicaRequest.append("; ClientId: " + clientId)
    stopReplicaRequest.append("; AckTimeoutMs: " + ackTimeoutMs + " ms")
    stopReplicaRequest.append("; DeletePartitions: " + deletePartitions)
    stopReplicaRequest.append("; ControllerId: " + controllerId)
    stopReplicaRequest.append("; ControllerEpoch: " + controllerEpoch)
    stopReplicaRequest.append("; Partitions: " + partitions.mkString(","))
    stopReplicaRequest.toString()
  }

  override  def handleError(e: Throwable, requestChannel: RequestChannel, request: RequestChannel.Request): Unit = {
    val responseMap = partitions.map {
      case topicAndPartition => (topicAndPartition, ErrorMapping.codeFor(e.getClass.asInstanceOf[Class[Throwable]]))
    }.toMap
    val errorResponse = StopReplicaResponse(correlationId, responseMap)
    requestChannel.sendResponse(new Response(request, new BoundedByteBufferSend(errorResponse)))
  }
}

redpajama_set_name: RedPajamaGithub


text:
Date: 08/03/2016

## Status

Accepted

## Context

We started with waiting code spread throughout the different layers of the DockerComposition stack:
 * DockerComposition
 * Container
 * DockerPort

This makes our custom waits depend on specific functionality rather than general functionality that external devs can also use. Now we're making all `waitForService` calls go through just a couple of API calls with flexible Healthchecks this is going to bite us.

## Decision

Wait code (for the purposes of powering `waitForService`) does not go in the Composition stack. Instead, waits depend on external observations of this stack.

## Consequences

The composition stack only talks about it's current state at any given point


text:
"""Accesses the google.monitoring.v3 NotificationChannelService API."""

import functools
import pkg_resources
import warnings

from google.oauth2 import service_account
import google.api_core.gapic_v1.client_info
import google.api_core.gapic_v1.config
import google.api_core.gapic_v1.method
import google.api_core.grpc_helpers
import google.api_core.page_iterator
import google.api_core.path_template
import grpc

from google.api import metric_pb2 as api_metric_pb2
from google.api import monitored_resource_pb2
from google.cloud.monitoring_v3.gapic import enums
from google.cloud.monitoring_v3.gapic import notification_channel_service_client_config
from google.cloud.monitoring_v3.gapic.transports import notification_channel_service_grpc_transport
from google.cloud.monitoring_v3.proto import alert_pb2
from google.cloud.monitoring_v3.proto import alert_service_pb2
from google.cloud.monitoring_v3.proto import alert_service_pb2_grpc
from google.cloud.monitoring_v3.proto import common_pb2
from google.cloud.monitoring_v3.proto import group_pb2
from google.cloud.monitoring_v3.proto import group_service_pb2
from google.cloud.monitoring_v3.proto import group_service_pb2_grpc
from google.cloud.monitoring_v3.proto import metric_pb2 as proto_metric_pb2
from google.cloud.monitoring_v3.proto import metric_service_pb2
from google.cloud.monitoring_v3.proto import metric_service_pb2_grpc
from google.cloud.monitoring_v3.proto import notification_pb2
from google.cloud.monitoring_v3.proto import notification_service_pb2
from google.cloud.monitoring_v3.proto import notification_service_pb2_grpc
from google.protobuf import empty_pb2
from google.protobuf import field_mask_pb2

_GAPIC_LIBRARY_VERSION = pkg_resources.get_distribution(
    'google-cloud-monitoring', ).version

class NotificationChannelServiceClient(object):
    """
    The Notification Channel API provides access to configuration that
    controls how messages related to incidents are sent.
    """

    SERVICE_ADDRESS = 'monitoring.googleapis.com:443'
    """The default address of the service."""

    # The name of the interface for this client. This is the key used to
    # find the method configuration in the client_config dictionary.
    _INTERFACE_NAME = 'google.monitoring.v3.NotificationChannelService'

    @classmethod
    def from_service_account_file(cls, filename, *args, **kwargs):
        """Creates an instance of this client using the provided credentials
        file.

        Args:
            filename (str): The path to the service account private key json
                file.
            args: Additional arguments to pass to the constructor.
            kwargs: Additional arguments to pass to the constructor.

        Returns:
            NotificationChannelServiceClient: The constructed client.
        """
        credentials = service_account.Credentials.from_service_account_file(
            filename)
        kwargs['credentials'] = credentials
        return cls(*args, **kwargs)

    from_service_account_json = from_service_account_file

    @classmethod
    def project_path(cls, project):
        """Return a fully-qualified project string."""
        return google.api_core.path_template.expand(
            'projects/{project}',
            project=project,
        )

    @classmethod
    def notification_channel_path(cls, project, notification_channel):
        """Return a fully-qualified notification_channel string."""
        return google.api_core.path_template.expand(
            'projects/{project}/notificationChannels/{notification_channel}',
            project=project,
            notification_channel=notification_channel,
        )

    @classmethod
    def notification_channel_descriptor_path(cls, project, channel_descriptor):
        """Return a fully-qualified notification_channel_descriptor string."""
        return google.api_core.path_template.expand(
            'projects/{project}/notificationChannelDescriptors/{channel_descriptor}',
            project=project,
            channel_descriptor=channel_descriptor,
        )

    def __init__(
            self,
            transport=None,
            channel=None,
            credentials=None,
            client_config=notification_channel_service_client_config.config,
            client_info=None):
        """Constructor.

        Args:
            transport (Union[~.NotificationChannelServiceGrpcTransport,
                    Callable[[~.Credentials, type], ~.NotificationChannelServiceGrpcTransport]): A transport
                instance, responsible for actually making the API calls.
                The default transport uses the gRPC protocol.
                This argument may also be a callable which returns a
                transport instance. Callables will be sent the credentials
                as the first argument and the default transport class as
                the second argument.
            channel (grpc.Channel): DEPRECATED. A ``Channel`` instance
                through which to make calls. This argument is mutually exclusive
                with ``credentials``; providing both will raise an exception.
            credentials (google.auth.credentials.Credentials): The
                authorization credentials to attach to requests. These
                credentials identify this application to the service. If none
                are specified, the client will attempt to ascertain the
                credentials from the environment.
                This argument is mutually exclusive with providing a
                transport instance to ``transport``; doing so will raise
                an exception.
            client_config (dict): DEPRECATED. A dictionary of call options for
                each method. If not specified, the default configuration is used.
            client_info (google.api_core.gapic_v1.client_info.ClientInfo):
                The client info used to send a user-agent string along with
                API requests. If ``None``, then default info will be used.
                Generally, you only need to set this if you're developing
                your own client library.
        """
        # Raise deprecation warnings for things we want to go away.
        if client_config:
            warnings.warn('The `client_config` argument is deprecated.',
                          PendingDeprecationWarning)
        if channel:
            warnings.warn(
                'The `channel` argument is deprecated; use '
                '`transport` instead.', PendingDeprecationWarning)

        # Instantiate the transport.
        # The transport is responsible for handling serialization and
        # deserialization and actually sending data to the service.
        if transport:
            if callable(transport):
                self.transport = transport(
                    credentials=credentials,
                    default_class=notification_channel_service_grpc_transport.
                    NotificationChannelServiceGrpcTransport,
                )
            else:
                if credentials:
                    raise ValueError(
                        'Received both a transport instance and '
                        'credentials; these are mutually exclusive.')
                self.transport = transport
        self.transport = notification_channel_service_grpc_transport.NotificationChannelServiceGrpcTransport(
            address=self.SERVICE_ADDRESS,
            channel=channel,
            credentials=credentials,
        )

        if client_info is None:
            client_info = (
                google.api_core.gapic_v1.client_info.DEFAULT_CLIENT_INFO)
        client_info.gapic_version = _GAPIC_LIBRARY_VERSION
        self._client_info = client_info

        # Parse out the default settings for retry and timeout for each RPC
        # from the client configuration.
        # (Ordinarily, these are the defaults specified in the `*_config.py`
        # file next to this one.)
        self._method_configs = google.api_core.gapic_v1.config.parse_method_configs(
            client_config['interfaces'][self._INTERFACE_NAME], )

        # Save a dictionary of cached API call functions.
        # These are the actual callables which invoke the proper
        # transport methods, wrapped with `wrap_method` to add retry,
        # timeout, and the like.
        self._inner_api_calls = {}

    # Service calls
    def list_notification_channel_descriptors(
            self,
            name,
            page_size=None,
            retry=google.api_core.gapic_v1.method.DEFAULT,
            timeout=google.api_core.gapic_v1.method.DEFAULT,
            metadata=None):
        """
        Lists the descriptors for supported channel types. The use of descriptors
        makes it possible for new channel types to be dynamically added.

        Example:
            >>> from google.cloud import monitoring_v3
            >>>
            >>> client = monitoring_v3.NotificationChannelServiceClient()
            >>>
            >>> name = client.project_path('[PROJECT]')
            >>>
            >>> # Iterate over all results
            >>> for element in client.list_notification_channel_descriptors(name):
            ...     # process element
            ...     pass
            >>>
            >>>
            >>> # Alternatively:
            >>>
            >>> # Iterate over results one page at a time
            >>> for page in client.list_notification_channel_descriptors(name, options=CallOptions(page_token=INITIAL_PAGE)):
            ...     for element in page:
            ...         # process element
            ...         pass

        Args:
            name (str): The REST resource name of the parent from which to retrieve
                the notification channel descriptors. The expected syntax is:

                ::

                    projects/[PROJECT_ID]

                Note that this names the parent container in which to look for the
                descriptors; to retrieve a single descriptor by name, use the
                ``GetNotificationChannelDescriptor``
                operation, instead.
            page_size (int): The maximum number of resources contained in the
                underlying API response. If page streaming is performed per-
                resource, this parameter does not affect the return value. If page
                streaming is performed per-page, this determines the maximum number
                of resources in a page.
            retry (Optional[google.api_core.retry.Retry]):  A retry object used
                to retry requests. If ``None`` is specified, requests will not
                be retried.
            timeout (Optional[float]): The amount of time, in seconds, to wait
                for the request to complete. Note that if ``retry`` is
                specified, the timeout applies to each individual attempt.
            metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata
                that is provided to the method.

        Returns:
            A :class:`~google.gax.PageIterator` instance. By default, this
            is an iterable of :class:`~google.cloud.monitoring_v3.types.NotificationChannelDescriptor` instances.
            This object can also be configured to iterate over the pages
            of the response through the `options` parameter.

        Raises:
            google.api_core.exceptions.GoogleAPICallError: If the request
                    failed for any reason.
            google.api_core.exceptions.RetryError: If the request failed due
                    to a retryable error and retry attempts failed.
            ValueError: If the parameters are invalid.
        """
        if metadata is None:
            metadata = []
        metadata = list(metadata)
        # Wrap the transport method to add retry and timeout logic.
        if 'list_notification_channel_descriptors' not in self._inner_api_calls:
            self._inner_api_calls[
                'list_notification_channel_descriptors'] = google.api_core.gapic_v1.method.wrap_method(
                    self.transport.list_notification_channel_descriptors,
                    default_retry=self._method_configs[
                        'ListNotificationChannelDescriptors'].retry,
                    default_timeout=self._method_configs[
                        'ListNotificationChannelDescriptors'].timeout,
                    client_info=self._client_info,
                )

        request = notification_service_pb2.ListNotificationChannelDescriptorsRequest(
            name=name,
            page_size=page_size,
        )
        iterator = google.api_core.page_iterator.GRPCIterator(
            client=None,
            method=functools.partial(
                self._inner_api_calls['list_notification_channel_descriptors'],
                retry=retry,
                timeout=timeout,
                metadata=metadata),
            request=request,
            items_field='channel_descriptors',
            request_token_field='page_token',
            response_token_field='next_page_token',
        )
        return iterator

    def get_notification_channel_descriptor(
            self,
            name,
            retry=google.api_core.gapic_v1.method.DEFAULT,
            timeout=google.api_core.gapic_v1.method.DEFAULT,
            metadata=None):
        """
        Gets a single channel descriptor. The descriptor indicates which fields
        are expected / permitted for a notification channel of the given type.

        Example:
            >>> from google.cloud import monitoring_v3
            >>>
            >>> client = monitoring_v3.NotificationChannelServiceClient()
            >>>
            >>> name = client.notification_channel_descriptor_path('[PROJECT]', '[CHANNEL_DESCRIPTOR]')
            >>>
            >>> response = client.get_notification_channel_descriptor(name)

        Args:
            name (str): The channel type for which to execute the request. The format is
                ``projects/[PROJECT_ID]/notificationChannelDescriptors/{channel_type}``.
            retry (Optional[google.api_core.retry.Retry]):  A retry object used
                to retry requests. If ``None`` is specified, requests will not
                be retried.
            timeout (Optional[float]): The amount of time, in seconds, to wait
                for the request to complete. Note that if ``retry`` is
                specified, the timeout applies to each individual attempt.
            metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata
                that is provided to the method.

        Returns:
            A :class:`~google.cloud.monitoring_v3.types.NotificationChannelDescriptor` instance.

        Raises:
            google.api_core.exceptions.GoogleAPICallError: If the request
                    failed for any reason.
            google.api_core.exceptions.RetryError: If the request failed due
                    to a retryable error and retry attempts failed.
            ValueError: If the parameters are invalid.
        """
        if metadata is None:
            metadata = []
        metadata = list(metadata)
        # Wrap the transport method to add retry and timeout logic.
        if 'get_notification_channel_descriptor' not in self._inner_api_calls:
            self._inner_api_calls[
                'get_notification_channel_descriptor'] = google.api_core.gapic_v1.method.wrap_method(
                    self.transport.get_notification_channel_descriptor,
                    default_retry=self._method_configs[
                        'GetNotificationChannelDescriptor'].retry,
                    default_timeout=self._method_configs[
                        'GetNotificationChannelDescriptor'].timeout,
                    client_info=self._client_info,
                )

        request = notification_service_pb2.GetNotificationChannelDescriptorRequest(
            name=name, )
        return self._inner_api_calls['get_notification_channel_descriptor'](
            request, retry=retry, timeout=timeout, metadata=metadata)

    def list_notification_channels(
            self,
            name,
            filter_=None,
            order_by=None,
            page_size=None,
            retry=google.api_core.gapic_v1.method.DEFAULT,
            timeout=google.api_core.gapic_v1.method.DEFAULT,
            metadata=None):
        """
        Lists the notification channels that have been created for the project.

        Example:
            >>> from google.cloud import monitoring_v3
            >>>
            >>> client = monitoring_v3.NotificationChannelServiceClient()
            >>>
            >>> name = client.project_path('[PROJECT]')
            >>>
            >>> # Iterate over all results
            >>> for element in client.list_notification_channels(name):
            ...     # process element
            ...     pass
            >>>
            >>>
            >>> # Alternatively:
            >>>
            >>> # Iterate over results one page at a time
            >>> for page in client.list_notification_channels(name, options=CallOptions(page_token=INITIAL_PAGE)):
            ...     for element in page:
            ...         # process element
            ...         pass

        Args:
            name (str): The project on which to execute the request. The format is
                ``projects/[PROJECT_ID]``. That is, this names the container
                in which to look for the notification channels; it does not name a
                specific channel. To query a specific channel by REST resource name, use
                the
                ````GetNotificationChannel```` operation.
            filter_ (str): If provided, this field specifies the criteria that must be met by
                notification channels to be included in the response.

                For more details, see [sorting and
                filtering](/monitoring/api/v3/sorting-and-filtering).
            order_by (str): A comma-separated list of fields by which to sort the result. Supports
                the same set of fields as in ``filter``. Entries can be prefixed with
                a minus sign to sort in descending rather than ascending order.

                For more details, see [sorting and
                filtering](/monitoring/api/v3/sorting-and-filtering).
            page_size (int): The maximum number of resources contained in the
                underlying API response. If page streaming is performed per-
                resource, this parameter does not affect the return value. If page
                streaming is performed per-page, this determines the maximum number
                of resources in a page.
            retry (Optional[google.api_core.retry.Retry]):  A retry object used
                to retry requests. If ``None`` is specified, requests will not
                be retried.
            timeout (Optional[float]): The amount of time, in seconds, to wait
                for the request to complete. Note that if ``retry`` is
                specified, the timeout applies to each individual attempt.
            metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata
                that is provided to the method.

        Returns:
            A :class:`~google.gax.PageIterator` instance. By default, this
            is an iterable of :class:`~google.cloud.monitoring_v3.types.NotificationChannel` instances.
            This object can also be configured to iterate over the pages
            of the response through the `options` parameter.

        Raises:
            google.api_core.exceptions.GoogleAPICallError: If the request
                    failed for any reason.
            google.api_core.exceptions.RetryError: If the request failed due
                    to a retryable error and retry attempts failed.
            ValueError: If the parameters are invalid.
        """
        if metadata is None:
            metadata = []
        metadata = list(metadata)
        # Wrap the transport method to add retry and timeout logic.
        if 'list_notification_channels' not in self._inner_api_calls:
            self._inner_api_calls[
                'list_notification_channels'] = google.api_core.gapic_v1.method.wrap_method(
                    self.transport.list_notification_channels,
                    default_retry=self._method_configs[
                        'ListNotificationChannels'].retry,
                    default_timeout=self._method_configs[
                        'ListNotificationChannels'].timeout,
                    client_info=self._client_info,
                )

        request = notification_service_pb2.ListNotificationChannelsRequest(
            name=name,
            filter=filter_,
            order_by=order_by,
            page_size=page_size,
        )
        iterator = google.api_core.page_iterator.GRPCIterator(
            client=None,
            method=functools.partial(
                self._inner_api_calls['list_notification_channels'],
                retry=retry,
                timeout=timeout,
                metadata=metadata),
            request=request,
            items_field='notification_channels',
            request_token_field='page_token',
            response_token_field='next_page_token',
        )
        return iterator

    def get_notification_channel(
            self,
            name,
            retry=google.api_core.gapic_v1.method.DEFAULT,
            timeout=google.api_core.gapic_v1.method.DEFAULT,
            metadata=None):
        """
        Gets a single notification channel. The channel includes the relevant
        configuration details with which the channel was created. However, the
        response may truncate or omit passwords, API keys, or other private key
        matter and thus the response may not be 100% identical to the information
        that was supplied in the call to the create method.

        Example:
            >>> from google.cloud import monitoring_v3
            >>>
            >>> client = monitoring_v3.NotificationChannelServiceClient()
            >>>
            >>> name = client.notification_channel_path('[PROJECT]', '[NOTIFICATION_CHANNEL]')
            >>>
            >>> response = client.get_notification_channel(name)

        Args:
            name (str): The channel for which to execute the request. The format is
                ``projects/[PROJECT_ID]/notificationChannels/[CHANNEL_ID]``.
            retry (Optional[google.api_core.retry.Retry]):  A retry object used
                to retry requests. If ``None`` is specified, requests will not
                be retried.
            timeout (Optional[float]): The amount of time, in seconds, to wait
                for the request to complete. Note that if ``retry`` is
                specified, the timeout applies to each individual attempt.
            metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata
                that is provided to the method.

        Returns:
            A :class:`~google.cloud.monitoring_v3.types.NotificationChannel` instance.

        Raises:
            google.api_core.exceptions.GoogleAPICallError: If the request
                    failed for any reason.
            google.api_core.exceptions.RetryError: If the request failed due
                    to a retryable error and retry attempts failed.
            ValueError: If the parameters are invalid.
        """
        if metadata is None:
            metadata = []
        metadata = list(metadata)
        # Wrap the transport method to add retry and timeout logic.
        if 'get_notification_channel' not in self._inner_api_calls:
            self._inner_api_calls[
                'get_notification_channel'] = google.api_core.gapic_v1.method.wrap_method(
                    self.transport.get_notification_channel,
                    default_retry=self._method_configs[
                        'GetNotificationChannel'].retry,
                    default_timeout=self._method_configs[
                        'GetNotificationChannel'].timeout,
                    client_info=self._client_info,
                )

        request = notification_service_pb2.GetNotificationChannelRequest(
            name=name, )
        return self._inner_api_calls['get_notification_channel'](
            request, retry=retry, timeout=timeout, metadata=metadata)

    def create_notification_channel(
            self,
            name,
            notification_channel,
            retry=google.api_core.gapic_v1.method.DEFAULT,
            timeout=google.api_core.gapic_v1.method.DEFAULT,
            metadata=None):
        """
        Creates a new notification channel, representing a single notification
        endpoint such as an email address, SMS number, or pagerduty service.

        Example:
            >>> from google.cloud import monitoring_v3
            >>>
            >>> client = monitoring_v3.NotificationChannelServiceClient()
            >>>
            >>> name = client.project_path('[PROJECT]')
            >>>
            >>> # TODO: Initialize ``notification_channel``:
            >>> notification_channel = {}
            >>>
            >>> response = client.create_notification_channel(name, notification_channel)

        Args:
            name (str): The project on which to execute the request. The format is:

                ::

                    projects/[PROJECT_ID]

                Note that this names the container into which the channel will be
                written. This does not name the newly created channel. The resulting
                channel's name will have a normalized version of this field as a prefix,
                but will add ``/notificationChannels/[CHANNEL_ID]`` to identify the channel.
            notification_channel (Union[dict, ~google.cloud.monitoring_v3.types.NotificationChannel]): The definition of the ``NotificationChannel`` to create.
                If a dict is provided, it must be of the same form as the protobuf
                message :class:`~google.cloud.monitoring_v3.types.NotificationChannel`
            retry (Optional[google.api_core.retry.Retry]):  A retry object used
                to retry requests. If ``None`` is specified, requests will not
                be retried.
            timeout (Optional[float]): The amount of time, in seconds, to wait
                for the request to complete. Note that if ``retry`` is
                specified, the timeout applies to each individual attempt.
            metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata
                that is provided to the method.

        Returns:
            A :class:`~google.cloud.monitoring_v3.types.NotificationChannel` instance.

        Raises:
            google.api_core.exceptions.GoogleAPICallError: If the request
                    failed for any reason.
            google.api_core.exceptions.RetryError: If the request failed due
                    to a retryable error and retry attempts failed.
            ValueError: If the parameters are invalid.
        """
        if metadata is None:
            metadata = []
        metadata = list(metadata)
        # Wrap the transport method to add retry and timeout logic.
        if 'create_notification_channel' not in self._inner_api_calls:
            self._inner_api_calls[
                'create_notification_channel'] = google.api_core.gapic_v1.method.wrap_method(
                    self.transport.create_notification_channel,
                    default_retry=self._method_configs[
                        'CreateNotificationChannel'].retry,
                    default_timeout=self._method_configs[
                        'CreateNotificationChannel'].timeout,
                    client_info=self._client_info,
                )

        request = notification_service_pb2.CreateNotificationChannelRequest(
            name=name,
            notification_channel=notification_channel,
        )
        return self._inner_api_calls['create_notification_channel'](
            request, retry=retry, timeout=timeout, metadata=metadata)

    def update_notification_channel(
            self,
            notification_channel,
            update_mask=None,
            retry=google.api_core.gapic_v1.method.DEFAULT,
            timeout=google.api_core.gapic_v1.method.DEFAULT,
            metadata=None):
        """
        Updates a notification channel. Fields not specified in the field mask
        remain unchanged.

        Example:
            >>> from google.cloud import monitoring_v3
            >>>
            >>> client = monitoring_v3.NotificationChannelServiceClient()
            >>>
            >>> # TODO: Initialize ``notification_channel``:
            >>> notification_channel = {}
            >>>
            >>> response = client.update_notification_channel(notification_channel)

        Args:
            notification_channel (Union[dict, ~google.cloud.monitoring_v3.types.NotificationChannel]): A description of the changes to be applied to the specified
                notification channel. The description must provide a definition for
                fields to be updated; the names of these fields should also be
                included in the ``update_mask``.
                If a dict is provided, it must be of the same form as the protobuf
                message :class:`~google.cloud.monitoring_v3.types.NotificationChannel`
            update_mask (Union[dict, ~google.cloud.monitoring_v3.types.FieldMask]): The fields to update.
                If a dict is provided, it must be of the same form as the protobuf
                message :class:`~google.cloud.monitoring_v3.types.FieldMask`
            retry (Optional[google.api_core.retry.Retry]):  A retry object used
                to retry requests. If ``None`` is specified, requests will not
                be retried.
            timeout (Optional[float]): The amount of time, in seconds, to wait
                for the request to complete. Note that if ``retry`` is
                specified, the timeout applies to each individual attempt.
            metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata
                that is provided to the method.

        Returns:
            A :class:`~google.cloud.monitoring_v3.types.NotificationChannel` instance.

        Raises:
            google.api_core.exceptions.GoogleAPICallError: If the request
                    failed for any reason.
            google.api_core.exceptions.RetryError: If the request failed due
                    to a retryable error and retry attempts failed.
            ValueError: If the parameters are invalid.
        """
        if metadata is None:
            metadata = []
        metadata = list(metadata)
        # Wrap the transport method to add retry and timeout logic.
        if 'update_notification_channel' not in self._inner_api_calls:
            self._inner_api_calls[
                'update_notification_channel'] = google.api_core.gapic_v1.method.wrap_method(
                    self.transport.update_notification_channel,
                    default_retry=self._method_configs[
                        'UpdateNotificationChannel'].retry,
                    default_timeout=self._method_configs[
                        'UpdateNotificationChannel'].timeout,
                    client_info=self._client_info,
                )

        request = notification_service_pb2.UpdateNotificationChannelRequest(
            notification_channel=notification_channel,
            update_mask=update_mask,
        )
        return self._inner_api_calls['update_notification_channel'](
            request, retry=retry, timeout=timeout, metadata=metadata)

    def delete_notification_channel(
            self,
            name,
            force=None,
            retry=google.api_core.gapic_v1.method.DEFAULT,
            timeout=google.api_core.gapic_v1.method.DEFAULT,
            metadata=None):
        """
        Deletes a notification channel.

        Example:
            >>> from google.cloud import monitoring_v3
            >>>
            >>> client = monitoring_v3.NotificationChannelServiceClient()
            >>>
            >>> name = client.notification_channel_path('[PROJECT]', '[NOTIFICATION_CHANNEL]')
            >>>
            >>> client.delete_notification_channel(name)

        Args:
            name (str): The channel for which to execute the request. The format is
                ``projects/[PROJECT_ID]/notificationChannels/[CHANNEL_ID]``.
            force (bool): If true, the notification channel will be deleted regardless of its
                use in alert policies (the policies will be updated to remove the
                channel). If false, channels that are still referenced by an existing
                alerting policy will fail to be deleted in a delete operation.
            retry (Optional[google.api_core.retry.Retry]):  A retry object used
                to retry requests. If ``None`` is specified, requests will not
                be retried.
            timeout (Optional[float]): The amount of time, in seconds, to wait
                for the request to complete. Note that if ``retry`` is
                specified, the timeout applies to each individual attempt.
            metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata
                that is provided to the method.

        Raises:
            google.api_core.exceptions.GoogleAPICallError: If the request
                    failed for any reason.
            google.api_core.exceptions.RetryError: If the request failed due
                    to a retryable error and retry attempts failed.
            ValueError: If the parameters are invalid.
        """
        if metadata is None:
            metadata = []
        metadata = list(metadata)
        # Wrap the transport method to add retry and timeout logic.
        if 'delete_notification_channel' not in self._inner_api_calls:
            self._inner_api_calls[
                'delete_notification_channel'] = google.api_core.gapic_v1.method.wrap_method(
                    self.transport.delete_notification_channel,
                    default_retry=self._method_configs[
                        'DeleteNotificationChannel'].retry,
                    default_timeout=self._method_configs[
                        'DeleteNotificationChannel'].timeout,
                    client_info=self._client_info,
                )

        request = notification_service_pb2.DeleteNotificationChannelRequest(
            name=name,
            force=force,
        )
        self._inner_api_calls['delete_notification_channel'](
            request, retry=retry, timeout=timeout, metadata=metadata)


text:
package jag.parser.comb;

import org.junit.Test;

import static org.junit.Assert.assertEquals;

public class PairTests {

    @Test
    public void test01() {
        final Pair<Integer,String> p = Pair.of(1, "abc");
        assertEquals(1, (int)p.getL());
        assertEquals("abc", p.getR());
    }

    @Test
    public void lmap01() {
        final Pair<Integer,String> p = Pair.of(1, "abc");
        assertEquals(2, (int)p.lmap(x -> x+1).getL());
        assertEquals("abc", p.getR());
    }

    @Test
    public void rmap01() {
        final Pair<Integer,String> p = Pair.of(1, "abc");
        assertEquals(1, (int)p.getL());
        assertEquals("abcdef", p.rmap(x -> x + "def").getR());
    }

    @Test
    public void bimap01() {
        final Pair<Integer,String> p = Pair.of(1, "abc").bimap(x -> x+1, x -> x + "def");
        assertEquals(2, (int)p.getL());
        assertEquals("abcdef", p.getR());
    }

    @Test
    public void flip01() {
        final Pair<String,Integer> p = Pair.of(1, "abc").flip();
        assertEquals("abc", p.getL());
        assertEquals(1, (int)p.getR());
    }

    @Test
    public void withBoth() {
        final Pair<Integer,String> p = Pair.of(1, "abc");
        assertEquals("1abc", p.withBoth((left,right) -> left + right));
    }
}


text:
<component name="libraryTable">
  <library name="Maven: org.onehippo.cms7:hippo-repository-connector:2.24.09">
    <CLASSES>
      <root url="jar://$MAVEN_REPOSITORY$/org/onehippo/cms7/hippo-repository-connector/2.24.09/hippo-repository-connector-2.24.09.jar!/" />
    </CLASSES>
    <JAVADOC>
      <root url="jar://$MAVEN_REPOSITORY$/org/onehippo/cms7/hippo-repository-connector/2.24.09/hippo-repository-connector-2.24.09-javadoc.jar!/" />
    </JAVADOC>
    <SOURCES>
      <root url="jar://$MAVEN_REPOSITORY$/org/onehippo/cms7/hippo-repository-connector/2.24.09/hippo-repository-connector-2.24.09-sources.jar!/" />
    </SOURCES>
  </library>
</component>


text:
package com.bitunified.ledconfig.configuration.parser.steps.types;

import com.bitunified.ledconfig.configuration.parser.steps.ParseStep;
import com.bitunified.ledconfig.domain.Model;
import com.bitunified.ledconfig.domain.modeltypes.RealModel;
import com.bitunified.ledconfig.domain.product.ModelResult;
import com.bitunified.ledconfig.parts.Part;

import java.util.Set;

public class ParserStepRealModel extends ParseStepBase implements ParseStep {

    private final Integer begin;
    private final Integer end;

    public ParserStepRealModel(Integer step,boolean mandatory,Integer begin, Integer end, Class<? extends Model> model, String regex, String errorMessage) {
        super(step,mandatory,model,regex,errorMessage);
        this.begin = begin;
        this.end = end;
    }

    public ModelResult create(String productcode, Set<Part> parts) {
        String code=null;
        try {
             code = parse(productcode);
        }catch(Exception e) {
            return new ModelResult(getErrorMessage());
        }
        for (Part part : parts) {
            if (checkModel(part)) {
                RealModel product = createPart(part);
                Model model = createPartModel(part);
                if (code != null) {
                    if (product!=null) {
                        if (code.equalsIgnoreCase(product.getCode())) {

                            return new ModelResult(product, part);
                        }
                    }
                    if (model!=null){
                        if (code.equalsIgnoreCase(model.getCode())) {

                            return new ModelResult(model, part);
                        }
                    }
                }
            }
        }

        setError(true);
        return new ModelResult(getErrorMessage());
    }

    private String parse(String productcode) {
        if ((begin==null || end==null)||(begin.equals(end))){
            return null;
        }
        if (begin>productcode.length() || end>productcode.length()){
            return parseReverse(productcode);
        }
        return       productcode.substring(begin,end);
    }
    private String parseReverse(String productcode) {

        int diff=end-begin;
        return
                productcode.substring(productcode.length()-diff,productcode.length());
    }

}


text: {{teamshort}}


text:
package co.cask.cdap.data2.dataset2.lib.table;

import co.cask.cdap.api.common.Bytes;
import com.google.common.collect.Lists;

import java.util.Collections;
import java.util.List;

/**
 * Provides handy methods for simple table splits calculation.
 *

 * This is copied from old data-fabric, could be improved.
 *

 * NOTE: there's also seem to be a bug: first split should have open start and last one open end... TODO: fix it
 */
public class SplitsUtil {
  // Simplest stateless getSplits method implementation (doesn't use the actual stored data)

  /**
   * If the number of splits is not given, and we have no hints from the table structure (that can be implemented in
   * overriding implementations, though), the primitive getSplits methos will return up to this many splits. Note that
   * we cannot read this number from configuration, because the current OVCTable(Handle) does not pass configuration
   * down into the tables anywhere. See ENG-2395 for the fix.
   */
  static final int DEFAULT_NUMBER_OF_SPLITS = 8;

  /**
   * Simplest possible implementation of getSplits. Takes the given start and end and divides the key space in
   * between into (almost) even partitions, using a long integer approximation of the keys.
   */
  static List<KeyRange> primitiveGetSplits(int numSplits, byte[] start, byte[] stop) {
    // if the range is empty, return no splits
    if (start != null && stop != null && Bytes.compareTo(start, stop) >= 0) {
      return Collections.emptyList();
    }
    if (numSplits <= 0) {
      numSplits = DEFAULT_NUMBER_OF_SPLITS;
    }
    // for simplicity, we construct a long from the begin and end, divide the resulting long range into approximately
    // even splits, and convert the boundaries back to nyte array keys.
    long begin = longForKey(start, false);
    long end = longForKey(stop, true);
    double splitSize = ((double) (end - begin)) / ((double) numSplits);

    // each range will start with the stop key of the previous range.
    // start key of the first range is either the given start, or the least possible key {0};
    List<KeyRange> ranges = Lists.newArrayListWithExpectedSize(numSplits);
    byte[] current = start == null ? new byte[] { 0x00 } : start;
    for (int i = 1; i < numSplits; i++) {
      long bound = begin + (long) (splitSize * i);
      byte[] next = keyForBound(bound);
      // due to rounding and truncation, we may get a bound that is the same as the previous (or if the previous is
      // the start key, less than that). We may also get a bound that exceeds the stop key. In both cases we want to
      // ignore this bound and continue.
      if (Bytes.compareTo(current, next) < 0 && (stop == null || Bytes.compareTo(next, stop) < 0)) {
        ranges.add(new KeyRange(current, next));
        current = next;
      }
    }
    // end of the last range is always the given stop of the range to cover
    ranges.add(new KeyRange(current, stop));

    return ranges;
  }

  // helper method to approximate a row key as a long value. Takes the first 7 bytes from the key and prepends a 0x0;
  // if the key is less than 7 bytes, pads it with zeros to the right.
  static long longForKey(byte[] key, boolean isStop) {
    if (key == null) {
      return isStop ? 0xffffffffffffffL : 0L;
    } else {
      // leading zero helps avoid negative long values for keys beginning with a byte > 0x80
      final byte[] leadingZero = { 0x00 };
      byte[] x;
      if (key.length >= Bytes.SIZEOF_LONG - 1) {
        x = Bytes.add(leadingZero, Bytes.head(key, Bytes.SIZEOF_LONG - 1));
      } else {
        x = Bytes.padTail(Bytes.add(leadingZero, key), Bytes.SIZEOF_LONG - 1 - key.length);
      }
      return Bytes.toLong(x);
    }
  }

  // helper method to convert a long approximation of a long key into a range bound.
  // the following invariant holds: keyForBound(longForKey(key)) == removeTrailingZeros(key).
  // removing the trailing zeros is ok in the context that this is used (only for split bounds)
  // this is called keyForBound on purpose, and not keyForLong.
  static byte[] keyForBound(long value) {
    byte[] bytes = Bytes.tail(Bytes.toBytes(value), Bytes.SIZEOF_LONG - 1);
    int lastNonZero = bytes.length - 1;
    while (lastNonZero > 0 && bytes[lastNonZero] == 0) {
      lastNonZero--;
    }
    return Bytes.head(bytes, lastNonZero + 1);
  }
}


text:
def md5(text):
  from hashlib import md5
  if (type(text) is unicode): text = text.encode('utf-8')
  return md5(text).hexdigest()

def to_unicode(text):
  """將 text 轉為 unicode"""

  if type(text) is unicode: return text

  charset_tbl = ['utf-8', 'cp950']

  for charset in charset_tbl:
    try:
      tmp = unicode(text, charset)
      return tmp
    except: continue

  raise Exception("Unknown Encoding")

def pack_string(input):
  """去除字串中對人閱讀無用的字符"""
  import re
  output = re.sub('\r', '\n', input)
  output = re.sub('\n+', '\n', output)
  output = re.sub('\s+', ' ', output)
  return output.strip()


text:
namespace System.ServiceModel.Discovery
{
    using System.Collections.ObjectModel;
    using System.Runtime;
    using System.ServiceModel.Description;
    using System.ServiceModel.Discovery.Version11;
    using System.ServiceModel.Discovery.VersionApril2005;
    using System.ServiceModel.Discovery.VersionCD1;

    class DiscoveryUtility
    {
        public static Collection<EndpointDiscoveryMetadata> ToEndpointDiscoveryMetadataCollection(
            Collection<EndpointDiscoveryMetadataApril2005> endpointDiscoveryMetadataApril2005Collection)
        {
            Collection<EndpointDiscoveryMetadata> endpointDiscoveryMetadataCollection = new Collection<EndpointDiscoveryMetadata>();
            foreach (EndpointDiscoveryMetadataApril2005 endpointDiscoveryMetadataApril2005 in endpointDiscoveryMetadataApril2005Collection)
            {
                endpointDiscoveryMetadataCollection.Add(endpointDiscoveryMetadataApril2005.ToEndpointDiscoveryMetadata());
            }
            return endpointDiscoveryMetadataCollection;
        }

        public static Collection<EndpointDiscoveryMetadata> ToEndpointDiscoveryMetadataCollection(
            Collection<EndpointDiscoveryMetadataCD1> endpointDiscoveryMetadataCD1Collection)
        {
            Collection<EndpointDiscoveryMetadata> endpointDiscoveryMetadataCollection = new Collection<EndpointDiscoveryMetadata>();
            foreach (EndpointDiscoveryMetadataCD1 endpointDiscoveryMetadataCD1 in endpointDiscoveryMetadataCD1Collection)
            {
                endpointDiscoveryMetadataCollection.Add(endpointDiscoveryMetadataCD1.ToEndpointDiscoveryMetadata());
            }
            return endpointDiscoveryMetadataCollection;
        }

        public static Collection<EndpointDiscoveryMetadata> ToEndpointDiscoveryMetadataCollection(
            Collection<EndpointDiscoveryMetadata11> endpointDiscoveryMetadata11Collection)
        {
            Collection<EndpointDiscoveryMetadata> endpointDiscoveryMetadataCollection = new Collection<EndpointDiscoveryMetadata>();
            foreach (EndpointDiscoveryMetadata11 endpointDiscoveryMetadata11 in endpointDiscoveryMetadata11Collection)
            {
                endpointDiscoveryMetadataCollection.Add(endpointDiscoveryMetadata11.ToEndpointDiscoveryMetadata());
            }
            return endpointDiscoveryMetadataCollection;
        }

        public static ContractDescription GetContract(Type contractType)
        {
            Fx.Assert(contractType != null, "The discoveryContractType attribute must not be null.");

            ContractDescription discoveryContract = ContractDescription.GetContract(contractType);
            OperationBehaviorAttribute operationBehaviorAttribute;
            foreach (OperationDescription operationDescription in discoveryContract.Operations)
            {
                operationBehaviorAttribute = operationDescription.Behaviors.Find<OperationBehaviorAttribute>();
                if (operationBehaviorAttribute == null)
                {
                    operationBehaviorAttribute = new OperationBehaviorAttribute();
                    operationDescription.Behaviors.Add(operationBehaviorAttribute);
                }

                operationBehaviorAttribute.PreferAsyncInvocation = true;
            }

            return discoveryContract;
        }

        public static DiscoveryMessageSequence ToDiscoveryMessageSequenceOrNull(DiscoveryMessageSequenceApril2005 messageSequence)
        {
            if (messageSequence == null)
            {
                return null;
            }
            else
            {
                return messageSequence.ToDiscoveryMessageSequence();
            }
        }

        public static DiscoveryMessageSequence ToDiscoveryMessageSequenceOrNull(DiscoveryMessageSequenceCD1 messageSequence)
        {
            if (messageSequence == null)
            {
                return null;
            }
            else
            {
                return messageSequence.ToDiscoveryMessageSequence();
            }
        }

        public static DiscoveryMessageSequence ToDiscoveryMessageSequenceOrNull(DiscoveryMessageSequence11 messageSequence)
        {
            if (messageSequence == null)
            {
                return null;
            }
            else
            {
                return messageSequence.ToDiscoveryMessageSequence();
            }
        }

        public static bool IsCompatible(OperationContext context, IContextChannel channel)
        {
            return ((context != null) &&
                (context.InternalServiceChannel != null) &&
                (object.ReferenceEquals(context.InternalServiceChannel.Proxy, channel)));
        }
    }
}


text:
import createStore from "..";
import { dispatch } from "../utils";
import { actionCreators, initialState, reducer } from "../message";

jest.useFakeTimers();

function getState(store): typeof initialState {
    return store.getState().message;
}

it("sets and clears a current message", () => {
    expect(initialState.message).toBe("");
    let state = reducer(initialState, actionCreators.sendMessage("Hello, world!"));
    expect(state.message).toBe("Hello, world!");
    state = reducer(state, actionCreators.clearMessage());
    expect(state.message).toBe("");
});

it("sends message", async () => {
    expect.assertions(2);

    const store = createStore();

    expect(initialState.message).toBe("");
    const promise = dispatch(store, actionCreators.sendMessage("Hello, world!"));
    jest.runAllTimers();
    await promise;
    expect(getState(store).message).toBe("");
});

it("sends a non-temporary message", async () => {
    expect.assertions(2);

    const store = createStore();

    expect(initialState.message).toBe("");
    const promise = dispatch(store, actionCreators.sendMessage("Hello, world!", { temporary: false }));
    jest.runAllTimers();
    await promise;
    expect(getState(store).message).toBe("Hello, world!");
});


text:
package org.mindframes.latestfm.lastfm.event;

import android.os.Bundle;

import org.mindframes.latestfm.lastfm.ApiResult;
import org.mindframes.latestfm.lastfm.vo.Result;

import retrofit.RetrofitError;
import retrofit.client.Response;

public class EventUserGetTopAlbums extends ApiResult {

    public EventUserGetTopAlbums(Result result, Response response, Bundle arguments) {
        super(result, response, arguments);
    }

    public EventUserGetTopAlbums(RetrofitError error, Bundle arguments) {
        super(error, arguments);
    }
}


text:
// ==========================================================================
//  Squidex Headless CMS
// ==========================================================================
//  Copyright (c) Squidex UG (haftungsbeschränkt)
//  All rights reserved. Licensed under the MIT license.
// ==========================================================================

using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Squidex.Areas.Api.Controllers.History.Models;
using Squidex.Domain.Apps.Entities.History.Repositories;
using Squidex.Infrastructure.Commands;
using Squidex.Pipeline;
using Squidex.Shared;

namespace Squidex.Areas.Api.Controllers.History
{
    /// <summary>
    /// Readonly API to get an event stream.
    /// </summary>
    [ApiExplorerSettings(GroupName = nameof(History))]
    public sealed class HistoryController : ApiController
    {
        private readonly IHistoryEventRepository historyEventRepository;

        public HistoryController(ICommandBus commandBus, IHistoryEventRepository historyEventRepository)
            : base(commandBus)
        {
            this.historyEventRepository = historyEventRepository;
        }

        /// <summary>
        /// Get the events from the history
        /// </summary>
        /// <param name="app">The name of the app.</param>
        /// <param name="channel">The name of the channel.</param>
        /// <returns>
        /// 200 => Events returned.
        /// 404 => App not found.
        /// </returns>
        [HttpGet]
        [Route("apps/{app}/history/")]
        [ProducesResponseType(typeof(HistoryEventDto), 200)]
        [ApiPermission(Permissions.AppCommon)]
        [ApiCosts(0.1)]
        public async Task<IActionResult> GetHistory(string app, string channel)
        {
            var entities = await historyEventRepository.QueryByChannelAsync(AppId, channel, 100);

            var response = entities.Select(HistoryEventDto.FromHistoryEvent).ToList();

            return Ok(response);
        }
    }
}


text:
/****************************************************************************/
/*  File:       AppendTest.java                                             */
/*  Author:     F. Georges                                                  */
/*  Company:    H2O Consulting                                              */
/*  Date:       2015-01-09                                                  */
/*  Tags:                                                                   */
/*      Copyright (c) 2015 Florent Georges (see end of file.)               */
/* ------------------------------------------------------------------------ */

package org.expath.file;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import static org.expath.file.TestTools.assertFileEquals;
import org.expath.tools.model.Element;
import org.expath.tools.model.Sequence;
import org.expath.tools.model.dom.DomElement;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

/**
 * Test for the `append*` functions in {@link Write}.
 *
 * @author Florent Georges
 * @date   2015-01-09
 * @see http://expath.org/spec/file#in-out
 * @see http://expath.org/spec/file/20131203#in-out
 */
public class AppendTest
{
    // TODO: Add more tests with more complex sequences.
    @Test
    public void appendSequence_simpleString()
            throws Exception
    {
        String xml = "<root>Second line.
</root>";
        Element elem = DomElement.parseString(xml);
        Sequence seq = elem.getContent();
        String file = APPEND_01.getAbsolutePath();
        Write sut = new Write();
        sut.append(file, seq);
        assertFileEquals(APPEND_01, "First line.\nSecond line.\n",
                "The content of the text file after append");
    }

    @Test
    public void appendBinary_simpleBinary()
            throws Exception
    {
        byte[] bytes = { 0b100, 0b101, 0b110, 0b111 };
        String file = APPEND_02.getAbsolutePath();
        Write sut = new Write();
        sut.appendBinary(file, bytes);
        byte[] expect = { 0b0, 0b1, 0b10, 0b11, 0b100, 0b101, 0b110, 0b111 };
        assertFileEquals(APPEND_02, expect, "The content of the binary file after append");
    }

    // TODO: Add tests with encoding.
    @Test
    public void appendText_simpleString()
            throws Exception
    {
        String str = "Second line.\n";
        String file = APPEND_03.getAbsolutePath();
        Write sut = new Write();
        sut.appendText(file, str);
        assertFileEquals(APPEND_03, "First line.\nSecond line.\n",
                "The content of the text file after appending text");
    }

    @Test
    public void appendTextLines_simpleStrings()
            throws Exception
    {
        List<String> lines = new ArrayList<>();
        lines.add("Second line.");
        lines.add("Third line.");
        String file = APPEND_04.getAbsolutePath();
        Write sut = new Write();
        sut.appendTextLines(file, lines);
        assertFileEquals(APPEND_04, "First line.\nSecond line.\nThird line.\n",
                "The content of the text file after appending text lines");
    }

    // ----------------------------------------------------------------------
    //   Test setup
    // ----------------------------------------------------------------------

    @BeforeClass
    public static void setUpClass()
            throws Exception
    {
        APPEND    = TestTools.initArea("append");
        APPEND_01 = new File(APPEND, "first.txt");
        APPEND_02 = new File(APPEND, "second.bin");
        APPEND_03 = new File(APPEND, "third.txt");
        APPEND_04 = new File(APPEND, "fourth.txt");
    }

    private static File APPEND    = null;
    private static File APPEND_01 = null;
    private static File APPEND_02 = null;
    private static File APPEND_03 = null;
    private static File APPEND_04 = null;
}

/* ------------------------------------------------------------------------ */
/*  DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS COMMENT.               */
/*                                                                          */
/*  The contents of this file are subject to the Mozilla Public License     */
/*  Version 1.0 (the "License"); you may not use this file except in        */
/*  compliance with the License. You may obtain a copy of the License at    */
/*  http://www.mozilla.org/MPL/.                                            */
/*                                                                          */
/*  Software distributed under the License is distributed on an "AS IS"     */
/*  basis, WITHOUT WARRANTY OF ANY KIND, either express or implied.  See    */
/*  the License for the specific language governing rights and limitations  */
/*  under the License.                                                      */
/*                                                                          */
/*  The Original Code is: all this file.                                    */
/*                                                                          */
/*  The Initial Developer of the Original Code is Florent Georges.          */
/*                                                                          */
/*  Contributor(s): none.                                                   */
/* ------------------------------------------------------------------------ */


text:
#ifndef GainNode_h
#define GainNode_h

#include "modules/webaudio/AudioNode.h"
#include "modules/webaudio/AudioParam.h"
#include "wtf/PassRefPtr.h"
#include "wtf/Threading.h"

namespace blink {

class AudioContext;

// GainNode is an AudioNode with one input and one output which applies a gain (volume) change to the audio signal.
// De-zippering (smoothing) is applied when the gain value is changed dynamically.

class GainNode FINAL : public AudioNode {
    DEFINE_WRAPPERTYPEINFO();
public:
    static GainNode* create(AudioContext* context, float sampleRate)
    {
        return adoptRefCountedGarbageCollectedWillBeNoop(new GainNode(context, sampleRate));
    }

    // AudioNode
    virtual void process(size_t framesToProcess) OVERRIDE;

    // Called in the main thread when the number of channels for the input may have changed.
    virtual void checkNumberOfChannelsForInput(AudioNodeInput*) OVERRIDE;

    // JavaScript interface
    AudioParam* gain() { return m_gain.get(); }

    virtual void trace(Visitor*) OVERRIDE;

private:
    virtual double tailTime() const OVERRIDE { return 0; }
    virtual double latencyTime() const OVERRIDE { return 0; }

    GainNode(AudioContext*, float sampleRate);

    float m_lastGain; // for de-zippering
    Member<AudioParam> m_gain;

    AudioFloatArray m_sampleAccurateGainValues;
};

} // namespace blink

#endif // GainNode_h


text:
package org.hibernate.cache.redis.hibernate5.regions;

import lombok.extern.slf4j.Slf4j;
import org.hibernate.cache.redis.client.RedisClient;
import org.hibernate.cache.redis.hibernate5.ConfigurableRedisRegionFactory;
import org.hibernate.cache.redis.hibernate5.strategy.RedisAccessStrategyFactory;
import org.hibernate.cache.spi.CacheKeysFactory;
import org.hibernate.cache.spi.QueryResultsRegion;

import java.util.Properties;

/**
 * RedisQueryResultsRegion
 *
 * @author sunghyouk.bae@gmail.com
 * @since 2015. 8. 27.
 */
@Slf4j
public class RedisQueryResultsRegion extends RedisGeneralDataRegion implements QueryResultsRegion {

  public RedisQueryResultsRegion(RedisAccessStrategyFactory accessStrategyFactory,
                                 RedisClient redis, ConfigurableRedisRegionFactory configurableRedisRegionFactory,
                                 String regionName,
                                 Properties props, CacheKeysFactory cacheKeysFactory) {
    super(accessStrategyFactory, redis, configurableRedisRegionFactory, regionName, props, cacheKeysFactory);
  }
}


text:
package com.lonelyplanet.akka.http.extensions.tracing

import java.util.UUID

import com.lonelyplanet.akka.http.extensions.TraceTokenHeader

trait MaybeTraceTokenHolder {
  def maybeTraceToken: Option[TraceToken]
}

trait TraceTokenHolder extends MaybeTraceTokenHolder {
  def traceToken: TraceToken
  override def maybeTraceToken: Option[TraceToken] = Some(traceToken)
}

case class TraceToken(value: String) extends AnyVal {
  def toHeader: TraceTokenHeader = {
    TraceTokenHeader(value)
  }

  override def toString: String = value
}

object TraceToken {
  val MDCKey = "tracetoken"
  def random: TraceToken = TraceToken(UUID.randomUUID().toString)
}


text:
using namespace gpdxl;

XERCES_CPP_NAMESPACE_USE

//---------------------------------------------------------------------------
//	@function:
//		CParseHandlerLogicalTVF::CParseHandlerLogicalTVF
//
//	@doc:
//		Ctor
//
//---------------------------------------------------------------------------
CParseHandlerLogicalTVF::CParseHandlerLogicalTVF
	(
	IMemoryPool *pmp,
	CParseHandlerManager *pphm,
	CParseHandlerBase *pphRoot
	)
	:
	CParseHandlerLogicalOp(pmp, pphm, pphRoot),
	m_pmdidFunc(NULL),
	m_pmdidRetType(NULL),
	m_pmdname(NULL)
{
}

//---------------------------------------------------------------------------
//	@function:
//		CParseHandlerLogicalTVF::StartElement
//
//	@doc:
//		Processes a Xerces start element event
//
//---------------------------------------------------------------------------
void
CParseHandlerLogicalTVF::StartElement
	(
	const XMLCh* const xmlszUri,
	const XMLCh* const xmlszLocalname,
	const XMLCh* const xmlszQname,
	const Attributes &attrs
	)
{
	if (0 == XMLString::compareString(CDXLTokens::XmlstrToken(EdxltokenLogicalTVF), xmlszLocalname))
	{
		// parse function id
		m_pmdidFunc = CDXLOperatorFactory::PmdidFromAttrs(m_pphm->Pmm(), attrs, EdxltokenFuncId, EdxltokenLogicalTVF);

		// parse function name
		const XMLCh *xmlszFuncName = CDXLOperatorFactory::XmlstrFromAttrs
																(
																attrs,
																EdxltokenName,
																EdxltokenLogicalTVF
																);

		CWStringDynamic *pstrFuncName = CDXLUtils::PstrFromXMLCh(m_pphm->Pmm(), xmlszFuncName);
		m_pmdname = GPOS_NEW(m_pmp) CMDName(m_pmp, pstrFuncName);
		GPOS_DELETE(pstrFuncName);

		// parse function return type
		m_pmdidRetType = CDXLOperatorFactory::PmdidFromAttrs(m_pphm->Pmm(), attrs, EdxltokenTypeId, EdxltokenLogicalTVF);

	}
	else if (0 == XMLString::compareString(CDXLTokens::XmlstrToken(EdxltokenColumns), xmlszLocalname))
	{
		// parse handler for columns
		CParseHandlerBase *pphColDescr = CParseHandlerFactory::Pph(m_pmp, CDXLTokens::XmlstrToken(EdxltokenColumns), m_pphm, this);
		m_pphm->ActivateParseHandler(pphColDescr);

		// store parse handlers
		this->Append(pphColDescr);

		pphColDescr->startElement(xmlszUri, xmlszLocalname, xmlszQname, attrs);
	}
	else
	{
		// parse scalar child
		CParseHandlerBase *pphChild = CParseHandlerFactory::Pph(m_pmp, CDXLTokens::XmlstrToken(EdxltokenScalar), m_pphm, this);
		m_pphm->ActivateParseHandler(pphChild);

		// store parse handlers
		this->Append(pphChild);

		pphChild->startElement(xmlszUri, xmlszLocalname, xmlszQname, attrs);
	}
}

//---------------------------------------------------------------------------
//	@function:
//		CParseHandlerLogicalTVF::EndElement
//
//	@doc:
//		Processes a Xerces end element event
//
//---------------------------------------------------------------------------
void
CParseHandlerLogicalTVF::EndElement
	(
	const XMLCh* const, // xmlszUri,
	const XMLCh* const xmlszLocalname,
	const XMLCh* const // xmlszQname
	)
{
	if (0 != XMLString::compareString(CDXLTokens::XmlstrToken(EdxltokenLogicalTVF), xmlszLocalname))
	{
		CWStringDynamic *pstr = CDXLUtils::PstrFromXMLCh(m_pphm->Pmm(), xmlszLocalname);
		GPOS_RAISE(gpdxl::ExmaDXL, gpdxl::ExmiDXLUnexpectedTag, pstr->Wsz());
	}

	CParseHandlerColDescr *pphColDescr = dynamic_cast<CParseHandlerColDescr *>((*this)[0]);

	GPOS_ASSERT(NULL != pphColDescr);

	// get column descriptors
	DrgPdxlcd *pdrgpdxlcd = pphColDescr->Pdrgpdxlcd();
	GPOS_ASSERT(NULL != pdrgpdxlcd);

	pdrgpdxlcd->AddRef();
	CDXLLogicalTVF *pdxlopTVF = GPOS_NEW(m_pmp) CDXLLogicalTVF(m_pmp, m_pmdidFunc, m_pmdidRetType, m_pmdname, pdrgpdxlcd);

	m_pdxln = GPOS_NEW(m_pmp) CDXLNode(m_pmp, pdxlopTVF);

	const ULONG ulLen = this->UlLength();
	// loop over arglist children and add them to this parsehandler
	for (ULONG ul = 1; ul < ulLen; ul++)
	{
		CParseHandlerScalarOp *pphChild = dynamic_cast<CParseHandlerScalarOp *>((*this)[ul]);
		AddChildFromParseHandler(pphChild);
	}

	// deactivate handler
	m_pphm->DeactivateHandler();
}

// EOF


text:
Bootstrap Multiselect is a JQuery based plugin to provide an intuitive user interface for using select inputs with the multiple attribute present. Instead of a select a bootstrap button will be shown as dropdown menu containing the single options as checkboxes.

Bootstrap 3 port by [Eduard Dudar](https://github.com/edudar).

## Documentation

Documentation, demonstrations and FAQ: [http://davidstutz.github.com/bootstrap-multiselect/](http://davidstutz.github.com/bootstrap-multiselect/).

**Note**: The demo page is based on JQuery 2 - so for IE 6,7 and 8 the plugin will not work properly. Nevertheless, the plugin should run as expected using the .x branch of jQuery.

## Contribute!

Every pull request is appreciated. To make it easier for me to merge fixes and new features have a look at the following guidelines:

* Include documentation for new options and features to avoid undocumented features.
* Add a thorough description to every pull request - so I am able to understand the purpose of the pull request.
* Have a look at the code as to keep the code as comprehensible and coherent as possible (concerning code style, indentation etc. ...).
* Add comments to your code - to help me understand the committed code.
* Add a single pull request per fix or feature you add.

## License

This project is dual licensed under the Apache License, Version 2.0 and the BSD 3-Clause license.

### Apache License, Version 2.0

Copyright 2012 - 2014 David Stutz

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

[http://www.apache.org/licenses/LICENSE-2.0](http://www.apache.org/licenses/LICENSE-2.0)

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

### BSD 3-Clause License

Copyright (c) 2012 - 2014 David Stutz
All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* Neither the name of the <ORGANIZATION> nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.


text:
require_relative "../base"

require "vagrant/util/platform"

describe VagrantPlugins::ProviderVirtualBox::Action::PrepareNFSSettings do
  include_context "unit"
  include_context "virtualbox"

  let(:iso_env) do
    # We have to create a Vagrantfile so there is a root path
    env = isolated_environment
    env.vagrantfile("")
    env.create_vagrant_env
  end

  let(:machine) do
    iso_env.machine(iso_env.machine_names[0], :dummy).tap do |m|
      allow(m.provider).to receive(:driver).and_return(driver)
    end
  end

  let(:env)    {{ machine: machine }}
  let(:app)    { lambda { |*args| }}
  let(:driver) { double("driver") }
  let(:host)   { double("host") }

  subject { described_class.new(app, env) }

  before do
    env[:test] = true
    allow(machine.env).to receive(:host) { host }
    allow(host).to receive(:capability?).with(:nfs_installed) { true }
    allow(host).to receive(:capability).with(:nfs_installed) { true }
    # We don't care about smb support so return not installed
    allow(host).to receive(:capability?).with(:smb_installed).and_return(false)
  end

  it "calls the next action in the chain" do
    allow(driver).to receive(:read_network_interfaces).and_return({2 => {type: :hostonly, hostonly: "vmnet2"}})
    allow(driver).to receive(:read_host_only_interfaces).and_return([{name: "vmnet2", ip: "1.2.3.4"}])
    allow(driver).to receive(:read_guest_ip).with(1).and_return("2.3.4.5")

    called = false
    app = lambda { |*args| called = true }

    action = described_class.new(app, env)
    action.call(env)

    expect(called).to eq(true)
  end

  context "with an nfs synced folder" do
    let(:host_only_interfaces) {
      [{name: "vmnet2", ip: "1.2.3.4"}]
    }

    before do
      # We can't be on Windows, because NFS gets disabled on Windows
      allow(Vagrant::Util::Platform).to receive(:windows?).and_return(false)

      env[:machine].config.vm.synced_folder("/host/path", "/guest/path", type: "nfs")
      env[:machine].config.finalize!

      # Stub out the stuff so it just works by default
      allow(driver).to receive(:read_network_interfaces).and_return({
        2 => {type: :hostonly, hostonly: "vmnet2"},
      })
      allow(driver).to receive(:read_host_only_interfaces).and_return(host_only_interfaces)
      allow(driver).to receive(:read_guest_ip).with(1).and_return("2.3.4.5")

      # override sleep to 0 so test does not take seconds
      retry_options = subject.retry_options
      allow(subject).to receive(:retry_options).and_return(retry_options.merge(sleep: 0))
    end

    context "with host interface netmask defined" do
      context "with machine IP included within host interface range" do
        let(:host_only_interfaces) {
          [{name: "vmnet2", ip: "2.3.4.1", netmask: "255.255.255.0"}]
        }

        it "sets nfs_host_ip and nfs_machine_ip properly" do
          subject.call(env)

          expect(env[:nfs_host_ip]).to eq("2.3.4.1")
          expect(env[:nfs_machine_ip]).to eq("2.3.4.5")
        end
      end
      context "with machine IP included within host interface range" do
        let(:host_only_interfaces) {
          [{name: "vmnet2", ip: "1.2.3.4", netmask: "255.255.255.0"}]
        }

        it "raises an error when the machine IP is not within host interface range" do
          expect{ subject.call(env) }.to raise_error(Vagrant::Errors::NFSNoHostonlyNetwork)
        end
      end
    end

    it "sets nfs_host_ip and nfs_machine_ip properly" do
      subject.call(env)

      expect(env[:nfs_host_ip]).to    eq("1.2.3.4")
      expect(env[:nfs_machine_ip]).to eq("2.3.4.5")
    end

    it "raises an error when no host only adapter is configured" do
      allow(driver).to receive(:read_network_interfaces) {{}}

      expect { subject.call(env) }.
        to raise_error(Vagrant::Errors::NFSNoHostonlyNetwork)
    end

    it "retries through guest property not found errors" do
      raise_then_return = [
        lambda { raise Vagrant::Errors::VirtualBoxGuestPropertyNotFound, guest_property: 'stub' },
        lambda { "2.3.4.5" }
      ]
      allow(driver).to receive(:read_guest_ip) { raise_then_return.shift.call }

      subject.call(env)

      expect(env[:nfs_host_ip]).to    eq("1.2.3.4")
      expect(env[:nfs_machine_ip]).to eq("2.3.4.5")
    end

    it "raises an error informing the user of a bug when the guest IP cannot be found" do
      allow(driver).to receive(:read_guest_ip) {
        raise Vagrant::Errors::VirtualBoxGuestPropertyNotFound, guest_property: 'stub'
      }

      expect { subject.call(env) }.
        to raise_error(Vagrant::Errors::NFSNoGuestIP)
    end

    it "allows statically configured guest IPs to work for NFS, even when guest property would fail" do
      env[:machine].config.vm.network :private_network, ip: "11.12.13.14"

      allow(driver).to receive(:read_guest_ip) {
        raise Vagrant::Errors::VirtualBoxGuestPropertyNotFound, guest_property: "stub"
      }

      subject.call(env)

      expect(env[:nfs_host_ip]).to    eq("1.2.3.4")
      expect(env[:nfs_machine_ip]).to eq(["11.12.13.14"])
    end

    it "allows statically configured guest IPs to co-exist with dynamic host only IPs for NFS" do
      env[:machine].config.vm.network :private_network, ip: "11.12.13.14"

      subject.call(env)

      expect(env[:nfs_host_ip]).to    eq("1.2.3.4")
      expect(env[:nfs_machine_ip]).to eq(["11.12.13.14", "2.3.4.5"])
    end

    it "allows the use of scoped hash overrides as options" do
      env[:machine].config.vm.network :private_network, virtualbox__ip: "11.12.13.14"

      subject.call(env)

      expect(env[:nfs_host_ip]).to    eq("1.2.3.4")
      expect(env[:nfs_machine_ip]).to eq(["11.12.13.14", "2.3.4.5"])
    end
  end
end


text:
<?php

namespace PHPExiftool\Driver\Tag\KDCIFD;

use JMS\Serializer\Annotation\ExclusionPolicy;
use PHPExiftool\Driver\AbstractTag;

/**
 * @ExclusionPolicy("all")
 */
class SerialNumber extends AbstractTag
{

    protected $Id = 64000;

    protected $Name = 'SerialNumber';

    protected $FullName = 'Kodak::KDC_IFD';

    protected $GroupName = 'KDC_IFD';

    protected $g0 = 'MakerNotes';

    protected $g1 = 'KDC_IFD';

    protected $g2 = 'Image';

    protected $Type = 'string';

    protected $Writable = true;

    protected $Description = 'Serial Number';

    protected $flag_Permanent = true;

}


text:
/* jslint node: true */
'use strict';

var gulp = require('gulp');
var bs = require('./browser_sync');
var sass = require('gulp-sass');
// var sourcemaps = require('gulp-sourcemaps');
var handleErrors = require('../util/handleErrors');
var config = require('../config').sass;
var autoprefixer = require('gulp-autoprefixer');

gulp.task('sass', function() {
    return gulp.src(config.src)
        // .pipe(sourcemaps.init())
        .pipe(sass(config.settings))
        .on('error', handleErrors)
        // .pipe(sourcemaps.write())
        .pipe(autoprefixer({ browsers: ['last 2 versions'] }))
        .pipe(gulp.dest(config.dest))
        .pipe(bs.stream());
});


text:
export declare class MdProgressBar {
    color: 'primary' | 'accent' | 'warn';
    private _value;
    value: number;
    private _bufferValue;
    bufferValue: number;
    mode: 'determinate' | 'indeterminate' | 'buffer' | 'query';
    _primaryTransform(): {
        transform: string;
    };
    _bufferTransform(): {
        transform: string;
    };
}


text:
package com.microsoft.azure.management.network.v2019_07_01;

import com.microsoft.azure.arm.model.HasInner;
import com.microsoft.azure.management.network.v2019_07_01.implementation.VpnSiteLinkConnectionInner;
import com.microsoft.azure.arm.resources.models.HasManager;
import com.microsoft.azure.management.network.v2019_07_01.implementation.NetworkManager;
import java.util.List;
import com.microsoft.azure.SubResource;

/**
 * Type representing VpnConnectionVpnGatewayVpnSiteLinkConnectionModel.
 */
public interface VpnConnectionVpnGatewayVpnSiteLinkConnectionModel extends HasInner<VpnSiteLinkConnectionInner>, HasManager<NetworkManager> {
    /**
     * @return the connectionBandwidth value.
     */
    Integer connectionBandwidth();

    /**
     * @return the connectionStatus value.
     */
    VpnConnectionStatus connectionStatus();

    /**
     * @return the egressBytesTransferred value.
     */
    Long egressBytesTransferred();

    /**
     * @return the enableBgp value.
     */
    Boolean enableBgp();

    /**
     * @return the enableRateLimiting value.
     */
    Boolean enableRateLimiting();

    /**
     * @return the etag value.
     */
    String etag();

    /**
     * @return the id value.
     */
    String id();

    /**
     * @return the ingressBytesTransferred value.
     */
    Long ingressBytesTransferred();

    /**
     * @return the ipsecPolicies value.
     */
    List<IpsecPolicy> ipsecPolicies();

    /**
     * @return the name value.
     */
    String name();

    /**
     * @return the provisioningState value.
     */
    ProvisioningState provisioningState();

    /**
     * @return the routingWeight value.
     */
    Integer routingWeight();

    /**
     * @return the sharedKey value.
     */
    String sharedKey();

    /**
     * @return the type value.
     */
    String type();

    /**
     * @return the useLocalAzureIpAddress value.
     */
    Boolean useLocalAzureIpAddress();

    /**
     * @return the usePolicyBasedTrafficSelectors value.
     */
    Boolean usePolicyBasedTrafficSelectors();

    /**
     * @return the vpnConnectionProtocolType value.
     */
    VirtualNetworkGatewayConnectionProtocol vpnConnectionProtocolType();

    /**
     * @return the vpnSiteLink value.
     */
    SubResource vpnSiteLink();

}


text:
package org.perfidix.meter;

/**
 * Simple meter to count given ticks. The ticks are not resetted afterwards, the
 *
 * @author Alexander Onea, neue Couch
 * @author Sebastian Graf, University of Konstanz
 */
public final class CountingMeter extends AbstractMeter {

    /**
     * Constant to store the default name.
     */
    private static final String DEFAULTNAME = "CountingMeter";

    /**
     * Constant to store the default unit.
     */
    private static final String DEFAULTUNIT = "ticks";

    /**
     * Constant to store the default unit description.
     */
    private static final String DEFAULTUNITDESC = "Simple ticks for counting";
    /**
     * Name for this counting meter.
     */
    private transient final String name;
    /**
     * Unit for this counting meter.
     */
    private transient final String unit;
    /**
     * Short description for the unit.
     */
    private transient final String unitDescription;
    /**
     * Counter for ticks.
     */
    private transient long counter;

    /**
     * Constructor, generates a simple CountingMeter.
     */
    public CountingMeter() {
        this(DEFAULTNAME, DEFAULTUNIT, DEFAULTUNITDESC);
    }

    /**
     * Constructor with a given name.
     *
     * @param paramName the name of this CountingMeter
     */
    public CountingMeter(final String paramName) {
        this(paramName, DEFAULTUNIT, DEFAULTUNITDESC);
    }

    /**
     * Constructor with a given name and a given unit.
     *
     * @param paramName the name of this CountingMeter
     * @param paramUnit the unit of this CountingMeter
     */
    public CountingMeter(final String paramName, final String paramUnit) {
        this(paramName, paramUnit, DEFAULTUNITDESC);
    }

    /**
     * Constructor with a given name and a given unit and a given unit description.
     *
     * @param paramName     the name of this CountingMeter
     * @param paramUnit     the unit of this CountingMeter
     * @param paramUnitDesc the description of this CountingMeter
     */
    public CountingMeter(final String paramName, final String paramUnit, final String paramUnitDesc) {
        super();
        name = paramName;
        unit = paramUnit;
        unitDescription = paramUnitDesc;
        counter = 0;
    }

    /**
     * Getting the name of this CountingMeter.
     *
     * @return the name of this CountingMeter
     */
    @Override
    public String getName() {
        return name;
    }

    /**
     * The meter is ticking one forward.
     */
    public void tick() {
        counter++;
    }

    /**
     * Getting the value of this CountingMeter.
     *
     * @return the counter's value.
     */
    @Override
    public double getValue() {
        return counter;
    }

    /**
     * Getting the name of this CountingMeter.
     *
     * @return the unit of this CountingMeter
     */
    @Override
    public String getUnit() {
        return unit;
    }

    /**
     * Getting the description of this CountingMeter.
     *
     * @return the description of this CountingMeter
     */
    @Override
    public String getUnitDescription() {
        return unitDescription;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public int hashCode() {
        final int prime = 31;
        int result = prime;
        if (name == null) {
            result = prime * result;
        } else {
            result = prime * result + name.hashCode();
        }
        if (unit == null) {
            result = prime * result;
        } else {
            result = prime * result + unit.hashCode();
        }
        if (unitDescription == null) {
            result = prime * result;
        } else {
            result = prime * result + unitDescription.hashCode();
        }
        return result;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public boolean equals(final Object obj) {
        boolean returnVal = true;
        if (this == obj) {
            returnVal = true;
        }
        if (getClass() != obj.getClass()) {
            returnVal = false;
        }
        final CountingMeter other = (CountingMeter) obj;
        if (name == null) {
            if (other.name != null) {
                returnVal = false;
            }
        } else {
            if (!name.equals(other.name)) {
                returnVal = false;
            }
        }
        if (unit == null) {
            if (other.unit != null) {
                returnVal = false;
            }
        } else if (!unit.equals(other.unit)) {
            returnVal = false;
        }
        if (unitDescription == null) {
            if (other.unitDescription == null) {
                if (!unitDescription.equals(other.unitDescription)) {
                    returnVal = false;
                }
            } else {
                returnVal = false;
            }
        }
        return returnVal;
    }

}


text:
#include "config.h"

#if ENABLE(WEB_AUDIO)

#include "ChannelSplitterNode.h"

#include "AudioContext.h"
#include "AudioNodeInput.h"
#include "AudioNodeOutput.h"

namespace WebCore {

PassRefPtr<ChannelSplitterNode> ChannelSplitterNode::create(AudioContext* context, float sampleRate, unsigned numberOfOutputs)
{
    if (!numberOfOutputs || numberOfOutputs > AudioContext::maxNumberOfChannels())
        return nullptr;

    return adoptRef(new ChannelSplitterNode(context, sampleRate, numberOfOutputs));
}

ChannelSplitterNode::ChannelSplitterNode(AudioContext* context, float sampleRate, unsigned numberOfOutputs)
    : AudioNode(context, sampleRate)
{
    addInput(std::make_unique<AudioNodeInput>(this));

    // Create a fixed number of outputs (able to handle the maximum number of channels fed to an input).
    for (unsigned i = 0; i < numberOfOutputs; ++i)
        addOutput(std::make_unique<AudioNodeOutput>(this, 1));

    setNodeType(NodeTypeChannelSplitter);

    initialize();
}

void ChannelSplitterNode::process(size_t framesToProcess)
{
    AudioBus* source = input(0)->bus();
    ASSERT(source);
    ASSERT_UNUSED(framesToProcess, framesToProcess == source->length());

    unsigned numberOfSourceChannels = source->numberOfChannels();

    for (unsigned i = 0; i < numberOfOutputs(); ++i) {
        AudioBus* destination = output(i)->bus();
        ASSERT(destination);

        if (i < numberOfSourceChannels) {
            // Split the channel out if it exists in the source.
            // It would be nice to avoid the copy and simply pass along pointers, but this becomes extremely difficult with fanout and fanin.
            destination->channel(0)->copyFrom(source->channel(i));
        } else if (output(i)->renderingFanOutCount() > 0) {
            // Only bother zeroing out the destination if it's connected to anything
            destination->zero();
        }
    }
}

void ChannelSplitterNode::reset()
{
}

} // namespace WebCore

#endif // ENABLE(WEB_AUDIO)


text:
package test.java.framework.manager.cucumber.runtime.xstream;

import test.java.framework.manager.cucumber.runtime.CucumberException;

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

public class ListOfSingleValueWriter extends CellWriter {
    private int nodeDepth;
    private final List<String> values = new ArrayList<>();

    @Override
    public List<String> getHeader() {
        return null;
    }

    @Override
    public List<String> getValues() {
        return values;
    }

    @Override
    public void startNode(String name) {
        if (nodeDepth > 1) {
            throw new CucumberException("Can only convert List<List<T>> to a table when T is a single value (primitive, string, date etc).");
        }
        nodeDepth++;
    }

    @Override
    public void addAttribute(String name, String value) {
    }

    @Override
    public void setValue(String value) {
        values.add(value == null ? "" : value);
    }

    @Override
    public void endNode() {
        nodeDepth--;
    }

    @Override
    public void flush() {
        throw new UnsupportedOperationException();
    }

    @Override
    public void close() {
        throw new UnsupportedOperationException();
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:padding="5dp"
    android:clickable="true" >
    <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="22sp"
        android:layout_marginLeft="8dp"
        android:layout_alignParentLeft="true"
        android:layout_centerVertical="true"/>
    <TextView
        android:id="@+id/subtitle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="14sp"
        android:layout_marginLeft="8dp"
        android:layout_marginTop="4dp"
        android:layout_marginBottom="4dp"
        android:layout_below="@id/title"/>
    <ImageView
        android:id="@+id/check_item"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_centerVertical="true"
        android:background="@android:color/transparent"
        android:src="@drawable/ic_action_check"
        android:layout_alignParentRight="true"
        android:visibility="invisible" />
</RelativeLayout>