text:
package msg

import (
	"istio.io/istio/galley/pkg/config/analysis/diag"
	"istio.io/istio/pkg/config/resource"
)

var (
	// InternalError defines a diag.MessageType for message "InternalError".
	// Description: There was an internal error in the toolchain. This is almost always a bug in the implementation.
	InternalError = diag.NewMessageType(diag.Error, "IST0001", "Internal error: %v")

	// Deprecated defines a diag.MessageType for message "Deprecated".
	// Description: A feature that the configuration is depending on is now deprecated.
	Deprecated = diag.NewMessageType(diag.Warning, "IST0002", "Deprecated: %s")

	// ReferencedResourceNotFound defines a diag.MessageType for message "ReferencedResourceNotFound".
	// Description: A resource being referenced does not exist.
	ReferencedResourceNotFound = diag.NewMessageType(diag.Error, "IST0101", "Referenced %s not found: %q")

	// NamespaceNotInjected defines a diag.MessageType for message "NamespaceNotInjected".
	// Description: A namespace is not enabled for Istio injection.
	NamespaceNotInjected = diag.NewMessageType(diag.Warning, "IST0102", "The namespace is not enabled for Istio injection. Run 'kubectl label namespace %s istio-injection=enabled' to enable it, or 'kubectl label namespace %s istio-injection=disabled' to explicitly mark it as not needing injection")

	// PodMissingProxy defines a diag.MessageType for message "PodMissingProxy".
	// Description: A pod is missing the Istio proxy.
	PodMissingProxy = diag.NewMessageType(diag.Warning, "IST0103", "The pod is missing the Istio proxy. This can often be resolved by restarting or redeploying the workload.")

	// GatewayPortNotOnWorkload defines a diag.MessageType for message "GatewayPortNotOnWorkload".
	// Description: Unhandled gateway port
	GatewayPortNotOnWorkload = diag.NewMessageType(diag.Warning, "IST0104", "The gateway refers to a port that is not exposed on the workload (pod selector %s; port %d)")

	// IstioProxyImageMismatch defines a diag.MessageType for message "IstioProxyImageMismatch".
	// Description: The image of the Istio proxy running on the pod does not match the image defined in the injection configuration.
	IstioProxyImageMismatch = diag.NewMessageType(diag.Warning, "IST0105", "The image of the Istio proxy running on the pod does not match the image defined in the injection configuration (pod image: %s; injection configuration image: %s). This often happens after upgrading the Istio control-plane and can be fixed by redeploying the pod.")

	// SchemaValidationError defines a diag.MessageType for message "SchemaValidationError".
	// Description: The resource has a schema validation error.
	SchemaValidationError = diag.NewMessageType(diag.Error, "IST0106", "Schema validation error: %v")

	// MisplacedAnnotation defines a diag.MessageType for message "MisplacedAnnotation".
	// Description: An Istio annotation is applied to the wrong kind of resource.
	MisplacedAnnotation = diag.NewMessageType(diag.Warning, "IST0107", "Misplaced annotation: %s can only be applied to %s")

	// UnknownAnnotation defines a diag.MessageType for message "UnknownAnnotation".
	// Description: An Istio annotation is not recognized for any kind of resource
	UnknownAnnotation = diag.NewMessageType(diag.Warning, "IST0108", "Unknown annotation: %s")

	// ConflictingMeshGatewayVirtualServiceHosts defines a diag.MessageType for message "ConflictingMeshGatewayVirtualServiceHosts".
	// Description: Conflicting hosts on VirtualServices associated with mesh gateway
	ConflictingMeshGatewayVirtualServiceHosts = diag.NewMessageType(diag.Error, "IST0109", "The VirtualServices %s associated with mesh gateway define the same host %s which can lead to undefined behavior. This can be fixed by merging the conflicting VirtualServices into a single resource.")

	// ConflictingSidecarWorkloadSelectors defines a diag.MessageType for message "ConflictingSidecarWorkloadSelectors".
	// Description: A Sidecar resource selects the same workloads as another Sidecar resource
	ConflictingSidecarWorkloadSelectors = diag.NewMessageType(diag.Error, "IST0110", "The Sidecars %v in namespace %q select the same workload pod %q, which can lead to undefined behavior.")

	// MultipleSidecarsWithoutWorkloadSelectors defines a diag.MessageType for message "MultipleSidecarsWithoutWorkloadSelectors".
	// Description: More than one sidecar resource in a namespace has no workload selector
	MultipleSidecarsWithoutWorkloadSelectors = diag.NewMessageType(diag.Error, "IST0111", "The Sidecars %v in namespace %q have no workload selector, which can lead to undefined behavior.")

	// VirtualServiceDestinationPortSelectorRequired defines a diag.MessageType for message "VirtualServiceDestinationPortSelectorRequired".
	// Description: A VirtualService routes to a service with more than one port exposed, but does not specify which to use.
	VirtualServiceDestinationPortSelectorRequired = diag.NewMessageType(diag.Error, "IST0112", "This VirtualService routes to a service %q that exposes multiple ports %v. Specifying a port in the destination is required to disambiguate.")

	// MTLSPolicyConflict defines a diag.MessageType for message "MTLSPolicyConflict".
	// Description: A DestinationRule and Policy are in conflict with regards to mTLS.
	MTLSPolicyConflict = diag.NewMessageType(diag.Error, "IST0113", "A DestinationRule and Policy are in conflict with regards to mTLS for host %s. The DestinationRule %q specifies that mTLS must be %t but the Policy object %q specifies %s.")

	// PolicySpecifiesPortNameThatDoesntExist defines a diag.MessageType for message "PolicySpecifiesPortNameThatDoesntExist".
	// Description: A Policy targets a port name that cannot be found.
	PolicySpecifiesPortNameThatDoesntExist = diag.NewMessageType(diag.Warning, "IST0114", "Port name %s could not be found for host %s, which means the Policy won't be enforced.")

	// DestinationRuleUsesMTLSForWorkloadWithoutSidecar defines a diag.MessageType for message "DestinationRuleUsesMTLSForWorkloadWithoutSidecar".
	// Description: A DestinationRule uses mTLS for a workload that has no sidecar.
	DestinationRuleUsesMTLSForWorkloadWithoutSidecar = diag.NewMessageType(diag.Error, "IST0115", "DestinationRule %s uses mTLS for workload %s that has no sidecar. Traffic from workloads with sidecars will fail.")

	// DeploymentAssociatedToMultipleServices defines a diag.MessageType for message "DeploymentAssociatedToMultipleServices".
	// Description: The resulting pods of a service mesh deployment can't be associated with multiple services using the same port but different protocols.
	DeploymentAssociatedToMultipleServices = diag.NewMessageType(diag.Warning, "IST0116", "This deployment is associated with multiple services using port %d but different protocols: %v")

	// DeploymentRequiresServiceAssociated defines a diag.MessageType for message "DeploymentRequiresServiceAssociated".
	// Description: The resulting pods of a service mesh deployment must be associated with at least one service.
	DeploymentRequiresServiceAssociated = diag.NewMessageType(diag.Warning, "IST0117", "No service associated with this deployment. Service mesh deployments must be associated with a service.")

	// PortNameIsNotUnderNamingConvention defines a diag.MessageType for message "PortNameIsNotUnderNamingConvention".
	// Description: Port name is not under naming convention. Protocol detection is applied to the port.
	PortNameIsNotUnderNamingConvention = diag.NewMessageType(diag.Info, "IST0118", "Port name %s (port: %d, targetPort: %s) doesn't follow the naming convention of Istio port.")

	// JwtFailureDueToInvalidServicePortPrefix defines a diag.MessageType for message "JwtFailureDueToInvalidServicePortPrefix".
	// Description: Authentication policy with JWT targets Service with invalid port specification.
	JwtFailureDueToInvalidServicePortPrefix = diag.NewMessageType(diag.Warning, "IST0119", "Authentication policy with JWT targets Service with invalid port specification (port: %d, name: %s, protocol: %s, targetPort: %s).")

	// PolicyResourceIsDeprecated defines a diag.MessageType for message "PolicyResourceIsDeprecated".
	// Description: The Policy resource is deprecated and will be removed in a future Istio release. Migrate to the PeerAuthentication resource.
	PolicyResourceIsDeprecated = diag.NewMessageType(diag.Info, "IST0120", "The Policy resource is deprecated and will be removed in a future Istio release. Migrate to the PeerAuthentication resource.")

	// MeshPolicyResourceIsDeprecated defines a diag.MessageType for message "MeshPolicyResourceIsDeprecated".
	// Description: The MeshPolicy resource is deprecated and will be removed in a future Istio release. Migrate to the PeerAuthentication resource.
	MeshPolicyResourceIsDeprecated = diag.NewMessageType(diag.Info, "IST0121", "The MeshPolicy resource is deprecated and will be removed in a future Istio release. Migrate to the PeerAuthentication resource.")

	// InvalidRegexp defines a diag.MessageType for message "InvalidRegexp".
	// Description: Invalid Regex
	InvalidRegexp = diag.NewMessageType(diag.Warning, "IST0122", "Field %q regular expression invalid: %q (%s)")

	// NamespaceMultipleInjectionLabels defines a diag.MessageType for message "NamespaceMultipleInjectionLabels".
	// Description: A namespace has both new and legacy injection labels
	NamespaceMultipleInjectionLabels = diag.NewMessageType(diag.Warning, "IST0123", "The namespace has both new and legacy injection labels. Run 'kubectl label namespace %s istio.io/rev-' or 'kubectl label namespace %s istio-injection-'")

	// InvalidAnnotation defines a diag.MessageType for message "InvalidAnnotation".
	// Description: An Istio annotation that is not valid
	InvalidAnnotation = diag.NewMessageType(diag.Warning, "IST0125", "Invalid annotation %s: %s")

	// UnknownMeshNetworksServiceRegistry defines a diag.MessageType for message "UnknownMeshNetworksServiceRegistry".
	// Description: A service registry in Mesh Networks is unknown
	UnknownMeshNetworksServiceRegistry = diag.NewMessageType(diag.Error, "IST0126", "Unknown service registry %s in network %s")
)

// All returns a list of all known message types.
func All() []*diag.MessageType {
	return []*diag.MessageType{
		InternalError,
		Deprecated,
		ReferencedResourceNotFound,
		NamespaceNotInjected,
		PodMissingProxy,
		GatewayPortNotOnWorkload,
		IstioProxyImageMismatch,
		SchemaValidationError,
		MisplacedAnnotation,
		UnknownAnnotation,
		ConflictingMeshGatewayVirtualServiceHosts,
		ConflictingSidecarWorkloadSelectors,
		MultipleSidecarsWithoutWorkloadSelectors,
		VirtualServiceDestinationPortSelectorRequired,
		MTLSPolicyConflict,
		PolicySpecifiesPortNameThatDoesntExist,
		DestinationRuleUsesMTLSForWorkloadWithoutSidecar,
		DeploymentAssociatedToMultipleServices,
		DeploymentRequiresServiceAssociated,
		PortNameIsNotUnderNamingConvention,
		JwtFailureDueToInvalidServicePortPrefix,
		PolicyResourceIsDeprecated,
		MeshPolicyResourceIsDeprecated,
		InvalidRegexp,
		NamespaceMultipleInjectionLabels,
		InvalidAnnotation,
		UnknownMeshNetworksServiceRegistry,
	}
}

// NewInternalError returns a new diag.Message based on InternalError.
func NewInternalError(r *resource.Instance, detail string) diag.Message {
	return diag.NewMessage(
		InternalError,
		r,
		detail,
	)
}

// NewDeprecated returns a new diag.Message based on Deprecated.
func NewDeprecated(r *resource.Instance, detail string) diag.Message {
	return diag.NewMessage(
		Deprecated,
		r,
		detail,
	)
}

// NewReferencedResourceNotFound returns a new diag.Message based on ReferencedResourceNotFound.
func NewReferencedResourceNotFound(r *resource.Instance, reftype string, refval string) diag.Message {
	return diag.NewMessage(
		ReferencedResourceNotFound,
		r,
		reftype,
		refval,
	)
}

// NewNamespaceNotInjected returns a new diag.Message based on NamespaceNotInjected.
func NewNamespaceNotInjected(r *resource.Instance, namespace string, namespace2 string) diag.Message {
	return diag.NewMessage(
		NamespaceNotInjected,
		r,
		namespace,
		namespace2,
	)
}

// NewPodMissingProxy returns a new diag.Message based on PodMissingProxy.
func NewPodMissingProxy(r *resource.Instance) diag.Message {
	return diag.NewMessage(
		PodMissingProxy,
		r,
	)
}

// NewGatewayPortNotOnWorkload returns a new diag.Message based on GatewayPortNotOnWorkload.
func NewGatewayPortNotOnWorkload(r *resource.Instance, selector string, port int) diag.Message {
	return diag.NewMessage(
		GatewayPortNotOnWorkload,
		r,
		selector,
		port,
	)
}

// NewIstioProxyImageMismatch returns a new diag.Message based on IstioProxyImageMismatch.
func NewIstioProxyImageMismatch(r *resource.Instance, proxyImage string, injectionImage string) diag.Message {
	return diag.NewMessage(
		IstioProxyImageMismatch,
		r,
		proxyImage,
		injectionImage,
	)
}

// NewSchemaValidationError returns a new diag.Message based on SchemaValidationError.
func NewSchemaValidationError(r *resource.Instance, err error) diag.Message {
	return diag.NewMessage(
		SchemaValidationError,
		r,
		err,
	)
}

// NewMisplacedAnnotation returns a new diag.Message based on MisplacedAnnotation.
func NewMisplacedAnnotation(r *resource.Instance, annotation string, kind string) diag.Message {
	return diag.NewMessage(
		MisplacedAnnotation,
		r,
		annotation,
		kind,
	)
}

// NewUnknownAnnotation returns a new diag.Message based on UnknownAnnotation.
func NewUnknownAnnotation(r *resource.Instance, annotation string) diag.Message {
	return diag.NewMessage(
		UnknownAnnotation,
		r,
		annotation,
	)
}

// NewConflictingMeshGatewayVirtualServiceHosts returns a new diag.Message based on ConflictingMeshGatewayVirtualServiceHosts.
func NewConflictingMeshGatewayVirtualServiceHosts(r *resource.Instance, virtualServices string, host string) diag.Message {
	return diag.NewMessage(
		ConflictingMeshGatewayVirtualServiceHosts,
		r,
		virtualServices,
		host,
	)
}

// NewConflictingSidecarWorkloadSelectors returns a new diag.Message based on ConflictingSidecarWorkloadSelectors.
func NewConflictingSidecarWorkloadSelectors(r *resource.Instance, conflictingSidecars []string, namespace string, workloadPod string) diag.Message {
	return diag.NewMessage(
		ConflictingSidecarWorkloadSelectors,
		r,
		conflictingSidecars,
		namespace,
		workloadPod,
	)
}

// NewMultipleSidecarsWithoutWorkloadSelectors returns a new diag.Message based on MultipleSidecarsWithoutWorkloadSelectors.
func NewMultipleSidecarsWithoutWorkloadSelectors(r *resource.Instance, conflictingSidecars []string, namespace string) diag.Message {
	return diag.NewMessage(
		MultipleSidecarsWithoutWorkloadSelectors,
		r,
		conflictingSidecars,
		namespace,
	)
}

// NewVirtualServiceDestinationPortSelectorRequired returns a new diag.Message based on VirtualServiceDestinationPortSelectorRequired.
func NewVirtualServiceDestinationPortSelectorRequired(r *resource.Instance, destHost string, destPorts []int) diag.Message {
	return diag.NewMessage(
		VirtualServiceDestinationPortSelectorRequired,
		r,
		destHost,
		destPorts,
	)
}

// NewMTLSPolicyConflict returns a new diag.Message based on MTLSPolicyConflict.
func NewMTLSPolicyConflict(r *resource.Instance, host string, destinationRuleName string, destinationRuleMTLSMode bool, policyName string, policyMTLSMode string) diag.Message {
	return diag.NewMessage(
		MTLSPolicyConflict,
		r,
		host,
		destinationRuleName,
		destinationRuleMTLSMode,
		policyName,
		policyMTLSMode,
	)
}

// NewPolicySpecifiesPortNameThatDoesntExist returns a new diag.Message based on PolicySpecifiesPortNameThatDoesntExist.
func NewPolicySpecifiesPortNameThatDoesntExist(r *resource.Instance, portName string, host string) diag.Message {
	return diag.NewMessage(
		PolicySpecifiesPortNameThatDoesntExist,
		r,
		portName,
		host,
	)
}

// NewDestinationRuleUsesMTLSForWorkloadWithoutSidecar returns a new diag.Message based on DestinationRuleUsesMTLSForWorkloadWithoutSidecar.
func NewDestinationRuleUsesMTLSForWorkloadWithoutSidecar(r *resource.Instance, destinationRuleName string, host string) diag.Message {
	return diag.NewMessage(
		DestinationRuleUsesMTLSForWorkloadWithoutSidecar,
		r,
		destinationRuleName,
		host,
	)
}

// NewDeploymentAssociatedToMultipleServices returns a new diag.Message based on DeploymentAssociatedToMultipleServices.
func NewDeploymentAssociatedToMultipleServices(r *resource.Instance, deployment string, port int32, services []string) diag.Message {
	return diag.NewMessage(
		DeploymentAssociatedToMultipleServices,
		r,
		deployment,
		port,
		services,
	)
}

// NewDeploymentRequiresServiceAssociated returns a new diag.Message based on DeploymentRequiresServiceAssociated.
func NewDeploymentRequiresServiceAssociated(r *resource.Instance) diag.Message {
	return diag.NewMessage(
		DeploymentRequiresServiceAssociated,
		r,
	)
}

// NewPortNameIsNotUnderNamingConvention returns a new diag.Message based on PortNameIsNotUnderNamingConvention.
func NewPortNameIsNotUnderNamingConvention(r *resource.Instance, portName string, port int, targetPort string) diag.Message {
	return diag.NewMessage(
		PortNameIsNotUnderNamingConvention,
		r,
		portName,
		port,
		targetPort,
	)
}

// NewJwtFailureDueToInvalidServicePortPrefix returns a new diag.Message based on JwtFailureDueToInvalidServicePortPrefix.
func NewJwtFailureDueToInvalidServicePortPrefix(r *resource.Instance, port int, portName string, protocol string, targetPort string) diag.Message {
	return diag.NewMessage(
		JwtFailureDueToInvalidServicePortPrefix,
		r,
		port,
		portName,
		protocol,
		targetPort,
	)
}

// NewPolicyResourceIsDeprecated returns a new diag.Message based on PolicyResourceIsDeprecated.
func NewPolicyResourceIsDeprecated(r *resource.Instance) diag.Message {
	return diag.NewMessage(
		PolicyResourceIsDeprecated,
		r,
	)
}

// NewMeshPolicyResourceIsDeprecated returns a new diag.Message based on MeshPolicyResourceIsDeprecated.
func NewMeshPolicyResourceIsDeprecated(r *resource.Instance) diag.Message {
	return diag.NewMessage(
		MeshPolicyResourceIsDeprecated,
		r,
	)
}

// NewInvalidRegexp returns a new diag.Message based on InvalidRegexp.
func NewInvalidRegexp(r *resource.Instance, where string, re string, problem string) diag.Message {
	return diag.NewMessage(
		InvalidRegexp,
		r,
		where,
		re,
		problem,
	)
}

// NewNamespaceMultipleInjectionLabels returns a new diag.Message based on NamespaceMultipleInjectionLabels.
func NewNamespaceMultipleInjectionLabels(r *resource.Instance, namespace string, namespace2 string) diag.Message {
	return diag.NewMessage(
		NamespaceMultipleInjectionLabels,
		r,
		namespace,
		namespace2,
	)
}

// NewInvalidAnnotation returns a new diag.Message based on InvalidAnnotation.
func NewInvalidAnnotation(r *resource.Instance, annotation string, problem string) diag.Message {
	return diag.NewMessage(
		InvalidAnnotation,
		r,
		annotation,
		problem,
	)
}

// NewUnknownMeshNetworksServiceRegistry returns a new diag.Message based on UnknownMeshNetworksServiceRegistry.
func NewUnknownMeshNetworksServiceRegistry(r *resource.Instance, serviceregistry string, network string) diag.Message {
	return diag.NewMessage(
		UnknownMeshNetworksServiceRegistry,
		r,
		serviceregistry,
		network,
	)
}


text:
package gnu.CORBA;

import org.omg.CORBA.Request;
import org.omg.CORBA.WrongTransaction;

import java.util.Iterator;
import java.util.LinkedList;

/**
 * Handles the asynchronous dynamic invocations.
 *
 * @author Audrius Meskauskas, Lithuania (AudriusA@Bioinformatics.org)
 */
public class Asynchron
{
  LinkedList sent = new LinkedList();

  /**
   * Send multiple prepared requests one way, do not caring about the answer.
   * The messages, containing requests, will be marked, indicating that
   * the sender is not expecting to get a reply.
   *
   * @param requests the prepared array of requests.
   *
   * @see Request#send_oneway()
   */
  public void send_multiple_requests_oneway(Request[] requests)
  {
    for (int i = 0; i < requests.length; i++)
      {
        requests [ i ].send_oneway();
      }
  }

  /**
   * Send multiple prepared requests expecting to get a reply. All requests
   * are send in parallel, each in its own separate thread. When the
   * reply arrives, it is stored in the agreed fields of the corresponing
   * request data structure. If this method is called repeatedly,
   * the new requests are added to the set of the currently sent requests,
   * but the old set is not discarded.
   *
   * @param requests the prepared array of requests.
   *
   * @see #poll_next_response()
   * @see #get_next_response()
   * @see Request#send_deferred()
   */
  public void send_multiple_requests_deferred(Request[] requests)
  {
    synchronized (sent)
      {
        for (int i = 0; i < requests.length; i++)
          {
            sent.add(requests [ i ]);

            // TODO Reuse threads that are instantiated in the method below,
            // one thread per call.
            requests [ i ].send_deferred();
          }
      }
  }

  /**
   * Find if any of the requests that have been previously sent with
   * {@link #send_multiple_requests_deferred}, have a response yet.
   *
   * @return true if there is at least one response to the previously
   * sent request, false otherwise.
   */
  public boolean poll_next_response()
  {
    synchronized (sent)
      {
        Iterator iter = sent.iterator();
        Request r;
        while (iter.hasNext())
          {
            r = (Request) iter.next();
            if (r.poll_response())
              return true;
          }
      }
    return false;
  }

  /**
   * Get the next instance with a response being received. If all currently
   * sent responses not yet processed, this method pauses till at least one of
   * them is complete. If there are no requests currently sent, the method
   * pauses till some request is submitted and the response is received.
   * This strategy is identical to the one accepted by Suns 1.4 ORB
   * implementation.
   *
   * The returned response is removed from the list of the currently
   * submitted responses and is never returned again.
   *
   * @return the previously sent request that now contains the received
   * response.
   *
   * @throws WrongTransaction If the method was called from the transaction
   * scope different than the one, used to send the request. The exception
   * can be raised only if the request is implicitly associated with some
   * particular transaction.
   */
  public Request get_next_response()
                            throws WrongTransaction
  {
    // The hard-coded waiting times for the incremental waiter.
    // TODO it is possible to write more tricky system where the
    // requests notify the Asynchron when they are complete.
    // Wait for 5 ms intially.
    int wait = 8;

    // Double the waiting time
    int INC = 2;

    // Do not increase if the waiting time is already over 500 ms.
    int MAX = 500;
    while (true)
      {
        synchronized (sent)
          {
            Iterator iter = sent.iterator();
            Request r;
            while (iter.hasNext())
              {
                r = (Request) iter.next();
                if (r.poll_response())
                {
                  sent.remove(r);
                  return r;
                }
              }
          }
        try
          {
            Thread.sleep(wait);
            if (wait < MAX)
              wait = wait * INC;
          }
        catch (InterruptedException ex)
          {
          }
      }
  }
}

redpajama_set_name: RedPajamaGithub


text:
namespace VueCoreFramework.MigrationsConsole
{
    class Program
    {
        static void Main(string[] args) { }
    }
}


text:
<!DOCTYPE html>

  <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  <meta charset="UTF-8" />
  <title>
   Closure Unit Tests - goog.ui.Popup
  </title>

    color picker


text:
@class GHLinearGradientBackgroundView, GHLinearGradientSelectedBackgroundView;

@interface GHTableViewCellWithLinearGradientBackgroundView : UITableViewCell {
@private
    GHLinearGradientBackgroundView *_linearBackgroundView;
    GHLinearGradientSelectedBackgroundView *_selectedLinearGradientView;
}

@property (nonatomic, retain, readonly) GHLinearGradientBackgroundView *linearBackgroundView;
@property (nonatomic, retain, readonly) GHLinearGradientSelectedBackgroundView *selectedLinearGradientView;

@end


text:
export const TRACKING_EVENTS = {
  PAGE_NAVIGATION: {
    category: 'page',
    label: 'arrow_navigate',
  },
  PAGE_PREVIEW_CLICK: {
    category: 'page',
    label: 'carousel_navigate',
  },
  PAGE_ADD: {
    category: 'page',
    label: 'add_new',
  },
  PAGE_DELETE: {
    category: 'page',
    label: 'delete',
  },
  SELECT_ELEMENT: {
    category: 'select_element',
  },
  LIBRARY_PANEL_CLICK: {
    category: 'library_panel',
  },
  DESIGN_PANEL_CLICK: {
    category: 'design_panel',
  },
  INSERT_ELEMENT: {
    category: 'insert_element',
  },
  DELETE_ELEMENT: {
    category: 'delete_element',
  },
  SET_BACKGROUND_MEDIA: {
    category: 'background',
    label: 'set_media_as_bg',
  },
};


text:
<?php

namespace WlanThermo\API\Controller;

use WlanThermo\API\Service\LogfileService;

require_once PATH_LIB . '/accessProtection.php';

/**
 * Controller for getting some device info such as
 * number and size of logfiles.
 *
 * Class InfoController
 * @package WlanThermo\API\Controller
 */
class InfoController extends AbstractController
{
    /**
     * Retrieves the info.
     *
     * @return array
     */
    public function run()
    {
        $logfileService = new LogfileService();

        return array(
            'logs' => $logfileService->statsLogfiles(),
            'plots' => $logfileService->statsPlots(),
        );
    }
}


text:
package org.apache.pig.penny.apps.tr;

import java.io.Serializable;
import java.util.Set;

import org.apache.pig.backend.executionengine.ExecException;
import org.apache.pig.data.Tuple;
import org.apache.pig.penny.Location;
import org.apache.pig.penny.MonitorAgent;

public class TRMonitorAgent extends MonitorAgent {

    private final static int NUM_SAMPLES = 5;

    private int tupleCount = 0;

    public void finish() {
    }

    public Set<Integer> furnishFieldsToMonitor() {
        return null;
    }

    public void init(Serializable[] args) {
    }

    public Set<String> observeTuple(Tuple t, Set<String> tags) throws ExecException {
        if (tupleCount++ < NUM_SAMPLES) {
            return tags;
        } else {
            return null;
        }
    }

    public void receiveMessage(Location source, Tuple message) {
    }

}


text:
import { connect, connection, Connection, Model } from 'mongoose';
import { IPost, ICategory, IComment, ICache, ISetting, IProfile, IAuth } from '@/types/schema';
import config from '../blog.config';
import { Post } from './models/post';
import { Cache } from './models/cache';
import { Category } from './models/category';
import { Comment } from './models/comment';
import { Guestbook } from './models/guestbook';
import { Setting } from './models/setting';
import { Profile } from './models/profile';
import { Auth } from './models/auth';

/**
 * 重连次数
 */
let retryTimes = 5;

interface IModels {
    Post: Model<IPost>;
    Cache: Model<ICache>;
    Category: Model<ICategory>,
    Comment: Model<IComment>,
    Guestbook: Model<IComment>,
    Setting: Model<ISetting>,
    Profile: Model<IProfile>,
    Auth: Model<IAuth>
}

export default class DB {
    private static instance: DB;

    private _db: Connection;

    private _models: IModels;

    private constructor () {
      // 连接 MongoDB
      this.connectDB();

      this._db = connection;
      this._db.on('open', this.connected);
      this._db.on('error', this.error);

      this._models = {
        Post: new Post().model,
        Cache: new Cache().model,
        Category: new Category().model,
        Comment: new Comment().model,
        Guestbook: new Guestbook().model,
        Setting: new Setting().model,
        Profile: new Profile().model,
        Auth: new Auth().model
      };
    }

    public static get Models () {
      if (!DB.instance) {
        DB.instance = new DB();
      }
      return DB.instance._models;
    }

    connectDB () {
      connect(
        config.mongoUrl,
        {
          useUnifiedTopology: true,
          useNewUrlParser: true,
          useCreateIndex: true,
          useFindAndModify: false
        },
        () => {
          // 设置默认数据
          (this._models.Category as any).initData();
          (this._models.Setting as any).initData();
        }
      );
    }

    private connected () {
      console.log('成功连接MongoDB!');
      retryTimes = 5;
    }

    private error () {
      if (retryTimes > 0) {
        console.error(`连接MongoDB失败!mongoUrl: ${config.mongoUrl}. 准备尝试重新连接...`);
        setTimeout(() => {
          DB.instance.connectDB();
          retryTimes--;
        }, 1000);
      } else {
        console.error('重试数次后依然连接MongoDB失败,请检查MongoDB连接设置!');
        process.exit(1);
      }
    }
}


text:
if ENV['TRAVIS']
  require 'coveralls'
  Coveralls.wear!
end

require 'minitest/autorun'
require 'mocha/mini_test'
require 'mobu'

class MockCookies < Hash
  attr_accessor :permanent

  def initialize
    @permanent = {}
    super
  end

  def delete(cookie, opts={})
    super cookie
  end
end


text:
![Træfɪk](http://traefik.github.io/traefik.logo.svg "Træfɪk")
___

#  Documentation

* [Basics](#basics)
* [Global configuration](#global)
* [File backend](#file)
* [API backend](#api)
* [Docker backend](#docker)
* [Mesos/Marathon backend](#marathon)
* [Consul backend](#consul)
* [Benchmarks](#benchmarks)

##  Basics

Træfɪk is a modern HTTP reverse proxy and load balancer made to deploy microservices with ease.
It supports several backends ([Docker :whale:](https://www.docker.com/), [Mesos/Marathon](https://mesosphere.github.io/marathon/), [Consul](https://consul.io/), [Etcd](https://coreos.com/etcd/), Rest API, file...) to manage its configuration automatically and dynamically.

Basically, Træfɪk is a http router, which sends traffic from frontends to http backends, following rules you have configured.

### Frontends

Frontends can be defined using the following rules:

 * ```Headers```: Headers adds a matcher for request header values. It accepts a sequence of key/value pairs to be matched. For example: ```application/json```
 * ```HeadersRegexp```: Regular expressions can be used with headers as well. It accepts a sequence of key/value pairs, where the value has regex support. For example: ```application/(text|json)```
 * ```Host```: Host adds a matcher for the URL host. It accepts a template with zero or more URL variables enclosed by {}. Variables can define an optional regexp pattern to be matched: ```www.traefik.io```, ```{subdomain:[a-z]+}.traefik.io```
 * ```Methods```: Methods adds a matcher for HTTP methods. It accepts a sequence of one or more methods to be matched, e.g.: ```GET```, ```POST```, ```PUT```
 * ```Path```: Path adds a matcher for the URL path. It accepts a template with zero or more URL variables enclosed by {}. The template must start with a "/". For exemple ```/products/``` ```/articles/{category}/{id:[0-9]+}```
 * ```PathPrefix```: PathPrefix adds a matcher for the URL path prefix. This matches if the given template is a prefix of the full URL path.

 A frontend is a set of rules that forwards the incoming http traffic to a backend.

### HTTP Backends

A backend is responsible to load-balance the traffic coming from one or more frontends to a set of http servers.
Various methods of load-balancing is supported:

* ```wrr```: Weighted Round Robin
* ```drr```: Dynamic Round Robin: increases weights on servers that perform better than others. It also rolls back to original weights if the servers have changed.

A circuit breaker can also be applied to a backend, preventing high loads on failing servers.
It can be configured using:

* Methods: ```LatencyAtQuantileMS```, ```NetworkErrorRatio```, ```ResponseCodeRatio```
* Operators:  ```AND```, ```OR```, ```EQ```, ```NEQ```, ```LT```, ```LE```, ```GT```, ```GE```

For example:
* ```NetworkErrorRatio() > 0.5```
* ```LatencyAtQuantileMS(50.0) > 50```
* ```ResponseCodeRatio(500, 600, 0, 600) > 0.5```

##  Global configuration

```toml
# traefik.toml
################################################################
# Global configuration
################################################################

# Reverse proxy port
#
# Optional
# Default: ":80"
#
# port = ":80"

# Timeout in seconds.
# Duration to give active requests a chance to finish during hot-reloads
#
# Optional
# Default: 10
#
# graceTimeOut = 10

# Traefik logs file
# If not defined, logs to stdout
#
# Optional
#
# traefikLogsFile = "log/traefik.log"

# Access logs file
#
# Optional
#
# accessLogsFile = "log/access.log"

# Log level
#
# Optional
# Default: "ERROR"
#
# logLevel = "ERROR"

# SSL certificate and key used
#
# Optional
#
# CertFile = "traefik.crt"
# KeyFile = "traefik.key"
```

##  File backend

Like any other reverse proxy, Træfɪk can be configured with a file. You have two choices:

* simply add your configuration at the end of the global configuration file ```traefik.toml``` :

```toml
# traefik.toml
port = ":80"
graceTimeOut = 10
logLevel = "DEBUG"

[file]

# rules
[backends]
  [backends.backend1]
    [backends.backend1.circuitbreaker]
      expression = "NetworkErrorRatio() > 0.5"
    [backends.backend1.servers.server1]
    url = "http://172.17.0.2:80"
    weight = 10
    [backends.backend1.servers.server2]
    url = "http://172.17.0.3:80"
    weight = 1
  [backends.backend2]
    [backends.backend2.LoadBalancer]
      method = "drr"
    [backends.backend2.servers.server1]
    url = "http://172.17.0.4:80"
    weight = 1
    [backends.backend2.servers.server2]
    url = "http://172.17.0.5:80"
    weight = 2

[frontends]
  [frontends.frontend1]
  backend = "backend2"
    [frontends.frontend1.routes.test_1]
    rule = "Host"
    value = "test.localhost"
  [frontends.frontend2]
  backend = "backend1"
    [frontends.frontend2.routes.test_2]
    rule = "Path"
    value = "/test"

```

* or put your rules in a separate file, for example ```rules.tml```:

```toml
# traefik.toml
port = ":80"
graceTimeOut = 10
logLevel = "DEBUG"

[file]
filename = "rules.toml"
```

```toml
# rules.toml
[backends]
  [backends.backend1]
    [backends.backend1.circuitbreaker]
      expression = "NetworkErrorRatio() > 0.5"
    [backends.backend1.servers.server1]
    url = "http://172.17.0.2:80"
    weight = 10
    [backends.backend1.servers.server2]
    url = "http://172.17.0.3:80"
    weight = 1
  [backends.backend2]
    [backends.backend2.LoadBalancer]
      method = "drr"
    [backends.backend2.servers.server1]
    url = "http://172.17.0.4:80"
    weight = 1
    [backends.backend2.servers.server2]
    url = "http://172.17.0.5:80"
    weight = 2

[frontends]
  [frontends.frontend1]
  backend = "backend2"
    [frontends.frontend1.routes.test_1]
    rule = "Host"
    value = "test.localhost"
  [frontends.frontend2]
  backend = "backend1"
    [frontends.frontend2.routes.test_2]
    rule = "Path"
    value = "/test"

```

If you want Træfɪk to watch file changes automatically, just add:

```toml
[file]
watch = true
```

##  API backend

Træfik can be configured using a restful api.
To enable it:

```toml
[web]
address = ":8080"

# SSL certificate and key used
#
# Optional
#
# CertFile = "traefik.crt"
# KeyFile = "traefik.key"
```

* ```/```: provides a simple HTML frontend of Træfik

![HTML frontend](img/web.frontend.png)

* ```/health```: ```GET``` json metrics

```sh
$ curl -s "http://localhost:8080/health" | jq .
{
  "average_response_time_sec": 0,
  "average_response_time": "0",
  "total_response_time_sec": 0,
  "total_response_time": "0",
  "total_count": 0,
  "pid": 12861,
  "uptime": "7m12.80607635s",
  "uptime_sec": 432.80607635,
  "time": "2015-09-22 10:25:16.448023473 +0200 CEST",
  "unixtime": 1442910316,
  "status_code_count": {},
  "total_status_code_count": {},
  "count": 0
}
```

* ```/api```: ```GET``` configuration for all providers

```sh
$ curl -s "http://localhost:8082/api" | jq .
{
  "file": {
    "Frontends": {
      "frontend-traefik": {
        "Routes": {
          "route-host-traefik": {
            "Value": "traefik.docker.localhost",
            "Rule": "Host"
          }
        },
        "Backend": "backend-test2"
      },
      "frontend-test": {
        "Routes": {
          "route-host-test": {
            "Value": "test.docker.localhost",
            "Rule": "Host"
          }
        },
        "Backend": "backend-test1"
      }
    },
    "Backends": {
      "backend-test2": {
        "Servers": {
          "server-stoic_brattain": {
            "Weight": 0,
            "Url": "http://172.17.0.8:80"
          },
          "server-jovial_khorana": {
            "Weight": 0,
            "Url": "http://172.17.0.12:80"
          },
          "server-jovial_franklin": {
            "Weight": 0,
            "Url": "http://172.17.0.11:80"
          },
          "server-elegant_panini": {
            "Weight": 0,
            "Url": "http://172.17.0.9:80"
          },
          "server-adoring_elion": {
            "Weight": 0,
            "Url": "http://172.17.0.10:80"
          }
        }
      },
      "backend-test1": {
        "Servers": {
          "server-trusting_wozniak": {
            "Weight": 0,
            "Url": "http://172.17.0.5:80"
          },
          "server-sharp_jang": {
            "Weight": 0,
            "Url": "http://172.17.0.7:80"
          },
          "server-dreamy_feynman": {
            "Weight": 0,
            "Url": "http://172.17.0.6:80"
          }
        }
      }
    }
  },
  "marathon": {
    "Frontends": {
      "frontend-marathon": {
        "Routes": {
          "route-host-marathon": {
            "Value": "marathon.docker.localhost",
            "Rule": "Host"
          }
        },
        "Backend": "backend-marathon"
      },
    },
    "Backends": {
      "backend-marathon": {
        "Servers": {
          "server-marathon-1": {
            "Weight": 0,
            "Url": "http://172.17.0.8:802"
          },
        },
      },
    },
  },
}

```

* ```/api/{provider}```: ```GET``` or ```PUT``` provider
* ```/api/{provider}/backends```: ```GET``` backends
* ```/api/{provider}/backends/{backend}```: ```GET``` a backend
* ```/api/{provider}/backends/{backend}/servers```: ```GET``` servers in a backend
* ```/api/{provider}/backends/{backend}/servers/{server}```: ```GET``` a server in a backend
* ```/api/{provider}/frontends```: ```GET``` frontends
* ```/api/{provider}/frontends/{frontend}```: ```GET``` a frontend

##  Docker backend

Træfɪk can be configured to use Docker as a backend configuration:

```toml
################################################################
# Docker configuration backend
################################################################

# Enable Docker configuration backend
#
# Optional
#
[docker]

# Docker server endpoint. Can be a tcp or a unix socket endpoint.
#
# Required
#
endpoint = "unix:///var/run/docker.sock"

# Default domain used.
# Can be overridden by setting the "traefik.domain" label on a container.
#
# Required
#
domain = "docker.localhost"

# Enable watch docker changes
#
# Optional
#
watch = true

# Override default configuration template. For advanced users :)
#
# Optional
#
# filename = "docker.tmpl"
```

Labels can be used on containers to override default behaviour:

* ```traefik.backend=foo```: assign the container to ```foo``` backend
* ```traefik.port=80```: register this port. Useful when the container exposes multiples ports.
* ```traefik.weight=10```: assign this weight to the container
* ```traefik.enable=false```: disable this container in Træfɪk
* ```traefik.host=bar```: override the default routing from {containerName}.{domain} to bar.{domain}

##  Marathon backend

Træfɪk can be configured to use Marathon as a backend configuration:

```toml
################################################################
# Mesos/Marathon configuration backend
################################################################

# Enable Marathon configuration backend
#
# Optional
#
[marathon]

# Marathon server endpoint.
# You can also specify multiple endpoint for Marathon:
# endpoint := "http://10.241.1.71:8080,10.241.1.72:8080,10.241.1.73:8080"
#
# Required
#
endpoint = "http://127.0.0.1:8080"

# Network interface used to call Marathon web services
# Optional
# Default: "eth0"
#
# networkInterface = "eth0"

# Enable watch Marathon changes
#
# Optional
#
watch = true

# Default domain used.
# Can be overridden by setting the "traefik.domain" label on an application.
#
# Required
#
domain = "marathon.localhost"

# Override default configuration template. For advanced users :)
#
# Optional
#
# filename = "marathon.tmpl"
```

Labels can be used on containers to override default behaviour:

* ```traefik.backend=foo```: assign the application to ```foo``` backend
* ```traefik.port=80```: register this port. Useful when the application exposes multiples ports.
* ```traefik.weight=10```: assign this weight to the application
* ```traefik.enable=false```: disable this application in Træfɪk
* ```traefik.host=bar```: override the default routing from {appName}.{domain} to bar.{domain}
* ```traefik.prefixes=pf1,pf2```: use PathPrefix(es) instead of hostname for routing, use filename="providerTemplates/marathon-prefix.tmpl" with this option

##  Consul backend

Træfɪk can be configured to use Consul as a backend configuration:

```toml
################################################################
# Consul KV configuration backend
################################################################

# Enable Consul KV configuration backend
#
# Optional
#
[consul]

# Consul server endpoint
#
# Required
#
endpoint = "http://127.0.0.1:8500"

# Enable watch Consul changes
#
# Optional
#
watch = true

# Prefix used for KV store.
#
# Optional
#
prefix = "traefik"

# Override default configuration template. For advanced users :)
#
# Optional
#
# filename = "consul.tmpl"
```

##  Benchmarks

Here are some early Benchmarks between Nginx and Træfɪk acting as simple load balancers between two servers.

* Nginx:

```sh
$ docker run -d -e VIRTUAL_HOST=test1.localhost emilevauge/whoami
$ docker run -d -e VIRTUAL_HOST=test1.localhost emilevauge/whoami
$ docker run --log-driver=none -d -p 80:80 -v /var/run/docker.sock:/tmp/docker.sock:ro jwilder/nginx-proxy
$ ab -n 20000 -c 20  -r http://test1.localhost/
This is ApacheBench, Version 2.3 <$Revision: 1528965 $>
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Licensed to The Apache Software Foundation, http://www.apache.org/

Benchmarking test1.localhost (be patient)
Completed 2000 requests
Completed 4000 requests
Completed 6000 requests
Completed 8000 requests
Completed 10000 requests
Completed 12000 requests
Completed 14000 requests
Completed 16000 requests
Completed 18000 requests
Completed 20000 requests
Finished 20000 requests

Server Software:        nginx/1.9.2
Server Hostname:        test1.localhost
Server Port:            80

Document Path:          /
Document Length:        287 bytes

Concurrency Level:      20
Time taken for tests:   5.874 seconds
Complete requests:      20000
Failed requests:        0
Total transferred:      8900000 bytes
HTML transferred:       5740000 bytes
Requests per second:    3404.97 [#/sec] (mean)
Time per request:       5.874 [ms] (mean)
Time per request:       0.294 [ms] (mean, across all concurrent requests)
Transfer rate:          1479.70 [Kbytes/sec] received

Connection Times (ms)
              min  mean[+/-sd] median   max
Connect:        0    0   0.1      0       2
Processing:     0    6   2.4      6      35
Waiting:        0    5   2.3      5      33
Total:          0    6   2.4      6      36

Percentage of the requests served within a certain time (ms)
  50%      6
  66%      6
  75%      7
  80%      7
  90%      9
  95%     10
  98%     12
  99%     13
 100%     36 (longest request)

```

* Træfɪk:

```sh
$ docker run -d -l traefik.backend=test1 -l traefik.host=test1 emilevauge/whoami
$ docker run -d -l traefik.backend=test1 -l traefik.host=test1 emilevauge/whoami
docker run -d -p 8080:8080 -p 80:80 -v $PWD/traefik.toml:/traefik.toml -v /var/run/docker.sock:/var/run/docker.sock emilevauge/traefik
$ ab -n 20000 -c 20  -r http://test1.docker.localhost/
This is ApacheBench, Version 2.3 <$Revision: 1528965 $>
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Licensed to The Apache Software Foundation, http://www.apache.org/

Benchmarking test1.docker.localhost (be patient)
Completed 2000 requests
Completed 4000 requests
Completed 6000 requests
Completed 8000 requests
Completed 10000 requests
Completed 12000 requests
Completed 14000 requests
Completed 16000 requests
Completed 18000 requests
Completed 20000 requests
Finished 20000 requests

Server Software:        .
Server Hostname:        test1.docker.localhost
Server Port:            80

Document Path:          /
Document Length:        312 bytes

Concurrency Level:      20
Time taken for tests:   6.545 seconds
Complete requests:      20000
Failed requests:        0
Total transferred:      8600000 bytes
HTML transferred:       6240000 bytes
Requests per second:    3055.60 [#/sec] (mean)
Time per request:       6.545 [ms] (mean)
Time per request:       0.327 [ms] (mean, across all concurrent requests)
Transfer rate:          1283.11 [Kbytes/sec] received

Connection Times (ms)
              min  mean[+/-sd] median   max
Connect:        0    0   0.2      0       7
Processing:     1    6   2.2      6      22
Waiting:        1    6   2.1      6      21
Total:          1    7   2.2      6      22

Percentage of the requests served within a certain time (ms)
  50%      6
  66%      7
  75%      8
  80%      8
  90%      9
  95%     10
  98%     11
  99%     13
 100%     22 (longest request)

```


text:
package org.apache.hadoop.hive.ql.parse.repl.metric.event;

import org.apache.hive.common.util.SuppressFBWarnings;

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

/**
 * Class for deserializing the different stages of replication.
 */
public class StageMapper {

  @SuppressFBWarnings("UWF_UNWRITTEN_FIELD")
  private String name;

  private Status status = Status.IN_PROGRESS;

  private long startTime = 0;

  private long endTime = 0;

  private List<Metric> metrics = new ArrayList<>();

  public StageMapper() {

  }
  public String getName() {
    return name;
  }

  public Status getStatus() {
    return status;
  }

  public long getStartTime() {
    return startTime;
  }

  public long getEndTime() {
    return endTime;
  }

  public List<Metric> getMetrics() {
    return metrics;
  }

}


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

#nullable disable

using Microsoft.VisualStudio.Debugger.Evaluation;
using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation;

namespace Microsoft.CodeAnalysis.ExpressionEvaluator
{
    internal sealed class RootHiddenExpansion : Expansion
    {
        internal static Expansion CreateExpansion(
            MemberAndDeclarationInfo members,
            CustomTypeInfoTypeArgumentMap customTypeInfoMap)
        {
            return new RootHiddenExpansion(members, customTypeInfoMap);
        }

        private readonly MemberAndDeclarationInfo _member;
        private readonly CustomTypeInfoTypeArgumentMap _customTypeInfoMap;

        internal RootHiddenExpansion(MemberAndDeclarationInfo member, CustomTypeInfoTypeArgumentMap customTypeInfoMap)
        {
            _member = member;
            _customTypeInfoMap = customTypeInfoMap;
        }

        internal override void GetRows(
            ResultProvider resultProvider,
            ArrayBuilder<EvalResult> rows,
            DkmInspectionContext inspectionContext,
            EvalResultDataItem parent,
            DkmClrValue value,
            int startIndex,
            int count,
            bool visitAll,
            ref int index)
        {
            var memberValue = value.GetMemberValue(_member, inspectionContext);
            var isDynamicDebugViewEmptyException = memberValue.Type.GetLmrType().IsDynamicDebugViewEmptyException();
            if (isDynamicDebugViewEmptyException || memberValue.IsError())
            {
                if (InRange(startIndex, count, index))
                {
                    if (isDynamicDebugViewEmptyException)
                    {
                        var emptyMember = memberValue.Type.GetMemberByName("Empty");
                        memberValue = memberValue.GetMemberValue(emptyMember, inspectionContext);
                    }
                    var row = new EvalResult(Resources.ErrorName, (string)memberValue.HostObjectValue, inspectionContext);
                    rows.Add(row);
                }
                index++;
            }
            else
            {
                var other = MemberExpansion.CreateMemberDataItem(
                    resultProvider,
                    inspectionContext,
                    _member,
                    memberValue,
                    parent,
                    _customTypeInfoMap,
                    ExpansionFlags.IncludeBaseMembers | ExpansionFlags.IncludeResultsView,
                    supportsFavorites: false);
                var expansion = other.Expansion;
                if (expansion != null)
                {
                    expansion.GetRows(resultProvider, rows, inspectionContext, other.ToDataItem(), other.Value, startIndex, count, visitAll, ref index);
                }
            }
        }
    }
}


text:
package com.danielesegato.adme.db;

import android.content.ContentValues;
import android.database.Cursor;

import com.danielesegato.adme.config.ADMEFieldConfig;
import com.danielesegato.adme.config.SQLiteType;

/**
 * A Serializer to convert from/to the SQLite database and Java classes/primitives.
 */
public interface ADMESerializer {
    /**
     * Null value for SQLite
     */
    String NULL_RAW = "NULL";

    /**
     * @return the SQLite data type associated to this serializer.
     */
    SQLiteType getSQLiteType();

    /**
     * Convert an SQL value into it's java Object / primitive type.
     *
     * @param cursor      the Android Cursor.
     * @param columnPos   the column position to read
     * @param fieldConfig the configuration to the associated field (can be used by the serializer)
     * @return the java value of the object
     */
    Object sqlToJava(Cursor cursor, int columnPos, ADMEFieldConfig fieldConfig);

    /**
     * Convert a String value to it's raw string value ready for insertion in a statement for the
     * SQLite database. Any escape for SQLite should be performed here to avoid SQL Injection.
     * Strings should be wrapped with single quotes etc...
     *

     * This method is used to convert the default value specified in the annotation into a database
     * CREATE TABLE statement but it may be used for other fields.
     *

     * Example:
     *

     *     CREATE TABLE `test` (
     *         `my_column` TEXT DEFAULT {raw_string_will_be_placed_here_as_is}
     *     )
     *

     *
     * @param val         the string value of the content to put in the database
     * @param fieldConfig the configuration to the associated field (can be used by the serializer)
     * @return the raw string value ready to be placed in the SQLite statement.
     */
    String stringToSqlRaw(String val, ADMEFieldConfig fieldConfig);

    /**
     * Put a fieldValue into an Android {@link android.content.ContentValues}.
     *
     * @param key         the key this value should have in the ContentValues
     * @param values      the non null ContentValues container
     * @param fieldValue  the field value, it should be compatible with the type of this serializer
     * @param fieldConfig the configuration to the associated field (can be used by the serializer)
     * @throws java.lang.IllegalArgumentException if the fieldValue is not cast-able to a type handled
     *                                            by this serializer or, for example, if the field should be a primitive non null and a null value
     *                                            is passed
     */
    void storeInContentValues(String key, ContentValues values, Object fieldValue, ADMEFieldConfig fieldConfig) throws IllegalArgumentException;
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>org.eclipse.gemini.blueprint.iandt</groupId>
        <artifactId>gemini-blueprint-integration-test-bundles</artifactId>
        <version>3.0.0.M01-SNAPSHOT</version>
        <relativePath>../pom.xml</relativePath>
    </parent>

    <artifactId>configuration</artifactId>
    <packaging>jar</packaging>
    <name>Gemini Blueprint Test Bundle: Configuration test bundle</name>
    <description>A test bundle for the atomic updates of service and factory configuration changes</description>
    <url>http://www.eclipse.org/gemini/blueprint/</url>
</project>


text:
// Copyright 2016 Google Inc. All rights reserved.
//
// 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
//
// 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.

package com.google.archivepatcher.shared;

/**
 * A range, annotated with metadata, that is represented as an offset and a length. Comparison is
 * performed based on the natural ordering of the offset field.
 * @param <T> the type of the metadata
 */
public class TypedRange<T> implements Comparable<TypedRange<T>> {
  /**
   * The offset at which the range starts.
   */
  private final long offset;

  /**
   * The length of the range.
   */
  private final long length;

  /**
   * Optional metadata associated with this range.
   */
  private final T metadata;

  /**
   * Constructs a new range with the specified parameters.
   * @param offset the offset at which the range starts
   * @param length the length of the range
   * @param metadata optional metadata associated with this range
   */
  public TypedRange(long offset, long length, T metadata) {
    this.offset = offset;
    this.length = length;
    this.metadata = metadata;
  }

  @Override
  public String toString() {
    return "offset " + offset + ", length " + length + ", metadata " + metadata;
  }

  /**
   * Returns the offset at which the range starts.
   * @return as described
   */
  public long getOffset() {
    return offset;
  }

  /**
   * Returns the length of the range.
   * @return as described
   */
  public long getLength() {
    return length;
  }

  /**
   * Returns the metadata associated with the range, or null if no metadata has been set.
   * @return as described
   */
  public T getMetadata() {
    return metadata;
  }

  @Override
  public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result + (int) (length ^ (length >>> 32));
    result = prime * result + ((metadata == null) ? 0 : metadata.hashCode());
    result = prime * result + (int) (offset ^ (offset >>> 32));
    return result;
  }

  @Override
  public boolean equals(Object obj) {
    if (this == obj) return true;
    if (obj == null) return false;
    if (getClass() != obj.getClass()) return false;
    TypedRange<?> other = (TypedRange<?>) obj;
    if (length != other.length) return false;
    if (metadata == null) {
      if (other.metadata != null) return false;
    } else if (!metadata.equals(other.metadata)) return false;
    if (offset != other.offset) return false;
    return true;
  }

  @Override
  public int compareTo(TypedRange<T> other) {
    if (getOffset() < other.getOffset()) {
      return -1;
    } else if (getOffset() > other.getOffset()) {
      return 1;
    }
    return 0;
  }
}


text:
<resources>
    <string name="app_name">TimeKeeper</string>
</resources>


text:
class Motorset:
    """
    Drop-in replacement for wpilib.SpeedController. Useful for grouping
    bunches of motors together.
    """
    val = 0

    def __init__(self, motors, scalefactors=None):
        """
        Takes a tuple of motors and possibly a tuple of
        scalefactors, with which the motor outputs are multiplied.
        """
        self.motors = motors
        self.num_motors = len(motors)
        self.setscalefactors(scalefactors)
        self.Set = self.set
        self.Get = self.get

    def set(self, value):
        """
        Set motor value.
        This function is called identically to that for a normal single Talon.
        """
        self.val = value
        for motor, scalefactor in zip(self.motors, self.scalefactors):
            motor.Set(scalefactor * value)

    def get(self):
        """
        Get motor output.
        """
        return self.val

    def setscalefactors(self, scalefactors):
        """
        Depending on robot orientation, drivetrain configuration, controller
        configuration, motors in the same gearbox may need to be
        driven in differing directions. These "scale factor" numbers change the
        magnitude and/or direction of the different motors; they are multipliers
        for the speed fed to the motors.
        """
        if scalefactors:
            if self.num_motors != len(scalefactors):
                raise ValueError("Scalefactors must have the same number of elements as motors")
        else:
            scalefactors = (1, ) * self.num_motors
        self.scalefactors = scalefactors

    def Disable(self):
        for motor in self.motors:
            motor.Disable()


text:
const EventEmitter = require('events');
const BaseCommandLoader = require('./_base-loader.js');
const Utils = require('../../utils');

class CommandLoader extends BaseCommandLoader {

  static get interfaceMethods() {
    return {
      command: 'function'
    };
  }

  static isDeprecatedCommandStyle(CommandModule) {
    return Utils.isObject(CommandModule) && Utils.isFunction(CommandModule.command);
  }

  /**
   * This is to support backwards-compatibility for commands defined as objects,
   *  with a command() property
   *
   * @param CommandModule
   */
  static createFromObject(CommandModule) {
    return class CommandClass extends EventEmitter {
      command(...args) {
        if (Utils.isES6AsyncFn(CommandModule.command)) {
          return CommandModule.command.apply(this.api, args);
        }

        setImmediate(async () => {
          CommandModule.command.apply(this.api, args);
        });

        return this.api;
      }
    };
  }

  static transportActions({actions, api}) {
    return new Proxy(actions, {
      get(target, name) {
        return function(...args) {
          let callback;
          let method;
          let isLastArgFunction = Utils.isFunction(args[args.length-1]);

          if (isLastArgFunction) {
            callback = args.pop();
          } else if (args.length === 0 || !isLastArgFunction) {
            callback = function(result) {return result};
          }

          const definition = {
            args
          };

          if (name in target.session) { // actions that require the current session
            method = target.session[name];
            definition.sessionId = api.sessionId;
          } else {
            method = target[name];
          }

          return method(definition).then((result) => Utils.makePromise(callback, api, [result]));
        };
      }
    });
  }

  static createInstance(nightwatchInstance, CommandModule, opts) {
    const CommandClass = CommandLoader.isDeprecatedCommandStyle(CommandModule) ? CommandLoader.createFromObject(CommandModule) : CommandModule;

    class CommandInstance extends CommandClass {
      get api() {
        const isES6Async = this.isES6AsyncCommand;

        return {
          ...nightwatchInstance.api,
          get isES6Async() {
            return isES6Async;
          }
        };
      }

      get isES6AsyncCommand() {
        return Utils.isES6AsyncFn(
          CommandLoader.isDeprecatedCommandStyle(CommandModule) ? CommandModule.command: this.command
        );
      }

      get client() {
        return this.__nightwatchInstance || nightwatchInstance;
      }

      get commandFileName() {
        return opts.commandName;
      }

      get commandArgs() {
        return opts.args;
      }

      get transportActions() {
        return this.client.transportActions;
      }

      httpRequest(requestOptions) {
        return this.client.transport.runProtocolAction(requestOptions);
      }

      toString() {
        return `${this.constructor.name} [name=${opts.commandName}]`;
      }

      complete(...args) {
        if (Utils.isFunction(super.complete)) {
          return super.complete(...args);
        }

        this.emit('complete', ...args);
      }
    }

    const instance = new CommandInstance();

    Object.keys(CommandLoader.interfaceMethods).forEach(method => {
      let type = CommandLoader.interfaceMethods[method];
      if (!BaseCommandLoader.isTypeImplemented(instance, method, type)) {
        throw new Error(`Command class must implement method .${method}()`);
      }
    });

    instance.stackTrace = opts.stackTrace;
    instance.needsPromise = CommandLoader.isDeprecatedCommandStyle(CommandModule);

    return instance;
  }

  get loadSubDirectories() {
    return true;
  }

  createWrapper() {
    if (this.module) {
      this.commandFn = function commandFn({args, stackTrace}) {
        const instance = CommandLoader.createInstance(this.nightwatchInstance, this.module, {
          stackTrace,
          args,
          commandName: this.commandName
        });

        const result = this.resolveElementSelector(args)
          .then(elementResult => {
            if (elementResult) {
              args[0] = elementResult;
            }

            return instance.command(...args);
          })
          .catch(err => {
            if (instance instanceof EventEmitter) {
              instance.emit('error', err);

              return;
            }

            throw err;
          })
          .then(result => {
            let reportErrors = instance.client.settings.report_command_errors;

            if (result && result.code && result.error && result.status === -1) {
              // node.js errors, e.g. ECONNRESET
              reportErrors = true;
            }

            if (result && result.status === -1 && instance.reportProtocolErrors(result) && reportErrors) {
              const error = new Error(`Error while running .${this.commandName}(): ${result.error}`);
              instance.client.reporter.registerTestError(error);
            }

            return result;
          });

        if (instance instanceof EventEmitter) {
          return instance;
        }

        if (result instanceof Promise) {
          return result;
        }

        return result;
      };
    }

    return this;
  }

  getTargetNamespace(parent) {
    let namespace;
    if (parent) {
      namespace = super.getTargetNamespace(parent);
    } else if (Array.isArray(this.namespace) && this.namespace.length > 0) {
      namespace = BaseCommandLoader.unflattenNamespace(this.api, this.namespace.slice());
    }

    return namespace;
  }
}

module.exports = CommandLoader;


text:
package main

import (
	"bufio"
	"context"
	"fmt"
	"io"
	"os/exec"
	"sync"
	"syscall"
)

// process represents a single process that needs to be run.
type process struct {
	tag string
	// path is the path of the program to execute.
	path                   string
	stdoutSink, stderrSink io.Writer
	args                   []string
	// addTag specifies whether a tag should be prepended to each line on the stdin/stderr from the command.
	addTag bool
}

func (p *process) run(ctx context.Context) error {
	cmd := &exec.Cmd{
		Path: p.path,
		Args: append([]string{p.path}, p.args...),
		// nil means "use environment of the parent process", see the godoc. We do this explicitly to show the intent.
		Env: nil,
	}
	var stdout, stderr io.ReadCloser
	if p.addTag {
		var err error
		stdout, err = cmd.StdoutPipe()
		if err != nil {
			return fmt.Errorf("failed to get stdout pipe for %q: %v", p.path, err)
		}
		stderr, err = cmd.StderrPipe()
		if err != nil {
			return fmt.Errorf("failed to get stderr pipe for %q: %v", p.path, err)
		}
	} else {
		cmd.Stdout = p.stdoutSink
		cmd.Stderr = p.stderrSink
	}
	if err := cmd.Start(); err != nil {
		return fmt.Errorf("failed to start process for %q: %v", p.path, err)
	}
	var wg sync.WaitGroup
	if p.addTag {
		wg.Add(2)
		go func() {
			defer wg.Done()
			p.readLinesAndAddPrefix(stdout, p.stdoutSink)
		}()
		go func() {
			defer wg.Done()
			p.readLinesAndAddPrefix(stderr, p.stderrSink)
		}()
	}
	var wg2 sync.WaitGroup
	defer wg2.Wait() // waiting for terminating go-routine to finish
	done := make(chan struct{})
	defer close(done)
	wg2.Add(1)
	go func() {
		defer wg2.Done()
		select {
		case <-ctx.Done(): // process should be terminated earlier
			if err := cmd.Process.Signal(syscall.SIGTERM); err != nil && !isFinished(err) {
				_, _ = fmt.Fprintf(p.stderrSink, "[multirun:%s] Failed to send SIGTERM, sending SIGKILL\n", p.tag)
				if err = cmd.Process.Kill(); err != nil && !isFinished(err) {
					_, _ = fmt.Fprintf(p.stderrSink, "[multirun:%s] Failed to send SIGKILL\n", p.tag)
				}
			}
		case <-done:
			// Nothing to do - process finished
		}
	}()
	wg.Wait() // waiting for stderr/stdout to be fully consumed before calling cmd.Wait() as per os/exec.Cmd documentation
	return cmd.Wait()
}

func isFinished(err error) bool {
	return err.Error() == "os: process already finished"
}

func (p *process) readLinesAndAddPrefix(in io.Reader, out io.Writer) {
	s := bufio.NewScanner(in)
	s.Buffer(make([]byte, 0, maxLineSize), maxLineSize)
	for s.Scan() {
		// ignore errors
		_, _ = fmt.Fprintf(out, "[%s] %s\n", p.tag, s.Bytes())
	}
	if err := s.Err(); err != nil {
		_, _ = fmt.Fprintf(p.stderrSink, "[multirun:%s] Read failed: %v\n", p.tag, err)
	}
}


text:
<?php

namespace Google\Service\Dataproc;

class InjectCredentialsRequest extends \Google\Model
{
  /**
   * @var string
   */
  public $clusterUuid;
  /**
   * @var string
   */
  public $credentialsCiphertext;

  /**
   * @param string
   */
  public function setClusterUuid($clusterUuid)
  {
    $this->clusterUuid = $clusterUuid;
  }
  /**
   * @return string
   */
  public function getClusterUuid()
  {
    return $this->clusterUuid;
  }
  /**
   * @param string
   */
  public function setCredentialsCiphertext($credentialsCiphertext)
  {
    $this->credentialsCiphertext = $credentialsCiphertext;
  }
  /**
   * @return string
   */
  public function getCredentialsCiphertext()
  {
    return $this->credentialsCiphertext;
  }
}

// Adding a class alias for backwards compatibility with the previous class name.
class_alias(InjectCredentialsRequest::class, 'Google_Service_Dataproc_InjectCredentialsRequest');


text:
<?php

/* Purpose:
   - set 'text/plain' and 'text/html' version of message
   - send mail directly to client (without MTA support)
   - print result
*/

// manage errors
error_reporting(E_ALL); // php errors
define('DISPLAY_XPM4_ERRORS', true); // display XPM4 errors

// path to 'SMTP.php' file from XPM4 package
require_once '../SMTP.php';

// CONFIGURATION ------------------
$from = 'me@mydomain.net'; // from mail address
$to   = 'client@destination.net'; // to mail address
$subj = 'Hello World!'; // mail subject
$text = 'Text version of message.'; // text/plain version of message
$html = 'HTML version of message.'; // text/html version of message
// CONFIGURATION ------------------

// set text/plain version of message
$msg1 = MIME::message($text, 'text/plain');
// set text/html version of message
$msg2 = MIME::message($html, 'text/html');
// compose message in MIME format
$mess = MIME::compose($msg1, $msg2);
// standard mail message RFC2822
$body = 'From: '.$from."\r\n".
		'To: '.$to."\r\n".
		'Subject: '.$subj."\r\n".
		$mess['header']."\r\n\r\n".
		$mess['content'];

// get client hostname
$expl = explode('@', $to);

// connect to SMTP server (direct) from MX hosts list
$conn = SMTP::mxconnect($expl[1]) or die(print_r($_RESULT));

// send mail
$sent = SMTP::send($conn, array($to), $body, $from);

// print result
if ($sent) echo 'Sent !';
else print_r($_RESULT);

// disconnect from SMTP server
SMTP::disconnect($conn);

?>


text:
<?php

namespace Wookieb\RelativeDate\Rules;

use Wookieb\RelativeDate\DateDiffRequest;

/**
 * Produces "months ago" for date difference if greater or equal than one calendar month to the past but less than one calendar year.
 */
class MonthsAgoRule implements RuleInterface
{
    public function isApplicable(DateDiffRequest $diffRequest)
    {
        return $diffRequest->getCalendarMonths() < 0;
    }

    public function createResult(DateDiffRequest $request)
    {
        return Results::calculateMonthsAgo($request);
    }
}


text:
class Profile;
class ChromeURLRequestContextGetter;
class AutomationResourceMessageFilter;

namespace AutomationRequestContext {

// Returns the URL request context to be used by HTTP requests handled over
// the automation channel.
ChromeURLRequestContextGetter* CreateAutomationURLRequestContextForTab(
    int tab_handle,
    Profile* profile,
    AutomationResourceMessageFilter* automation_client);

}

#endif  // CHROME_BROWSER_AUTOMATION_AUTOMATION_PROFILE_IMPL_H_


text:
/************************************************************************
*
* Flood Project © (2008-201x)
* Licensed under the simplified BSD license. All rights reserved.
*
************************************************************************/

#pragma once

#include "Engine/Scene/Component.h"
#include "Core/Math/Color.h"

NAMESPACE_ENGINE_BEGIN

//-----------------------------------//

/**
 * Lights can have different properties, depending on their purpose.
 * Directional lights are modelled by a distant source of light that has
 * a direction and no position, so it simulates light from a distant source.
 * Point lights just diffuse a uniform ammount of energy in all directions,
 * hence they have a position but no direction. Spot lights are modelled by
 * a cone, they have a direction and position and also a cut-off value.
 */

API_SCENE REFLECT_DECLARE_ENUM(LightType)

enum struct LightType
{
	Directional,
	Point,
	Spot
};

//-----------------------------------//

/**
 * Lights give life to a scene. Just add one and turn it on and there you go.
 * The light's position and direction should be set in the entity's Transform
 * component. Just rotate it to change the direction.
 */

API_SCENE REFLECT_DECLARE_CLASS(Light)

class API_ENGINE Light : public Component
{
	REFLECT_DECLARE_OBJECT(Light)

public:

	Light( LightType type = LightType::Point );

	// Gets/sets the type of this light source.
	ACCESSOR(LightType, LightType, lightType)

	// Gets/sets if this light source is active (powered on).
	ACCESSOR(Active, bool, isLightOn)

	// Gets/sets if this light source casts shadows.
	ACCESSOR(CastsShadows, bool, castsShadows)

	// Gets/sets the diffuse color of the light.
	ACCESSOR(DiffuseColor, const Color&, diffuseColor)

	// Gets/sets the specular color of the light.
	ACCESSOR(SpecularColor, const Color&, diffuseColor)

	// Gets/sets the emissive color of the light.
	ACCESSOR(EmissiveColor, const Color&, emissiveColor)

	// Gets/sets the ambient color of the light.
	ACCESSOR(AmbientColor, const Color&, ambientColor)

	// Gets/sets the cut-off radius of the light.
	ACCESSOR(CutOffRadius, float, cutoffRadius)

	// Called once per frame to update the component.
	virtual void update( float delta ) OVERRIDE;

protected:

	// Creates the debug renderable of this component.
	RenderBatchPtr createDebugRenderable() const;

	// Light type and colors
	LightType lightType;

	Color diffuseColor;
	Color specularColor;
	Color emissiveColor;
	Color ambientColor;

	// Cutoff Radius (for Spotlights).
	float cutoffRadius;

	// Light state
	bool isLightOn;
	bool castsShadows;
};

TYPEDEF_INTRUSIVE_POINTER_FROM_TYPE( Light );

//-----------------------------------//

NAMESPACE_ENGINE_END


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="horizontal" >

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_weight="0.30"
        android:orientation="vertical" >

        <FrameLayout
            android:id="@+id/camera_preview"
            android:layout_width="fill_parent"
            android:layout_height="199dp" />

        <Button
            android:id="@+id/button_capture"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:onClick="snapIt"
            android:text="@string/Capture" />

        <ImageView
            android:id="@+id/imageView1"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:scaleType="fitXY"
            android:src="@drawable/ic_launcher" />

    </LinearLayout>

    </LinearLayout>


text:
require 'rails/generators/named_base'
require 'generators/devise/orm_helpers'
require 'couchrest/model/base'

module CouchrestModel
  module Generators
    class DeviseGenerator < Rails::Generators::NamedBase
      include Devise::Generators::OrmHelpers

      def generate_model
        invoke "couchrest_model:model", [name] unless model_exists? && behavior == :invoke
      end

      def inject_property_types
        inject_into_file model_path, migration_data, after: "include CouchRest::Model::Base\n" if model_exists?
      end

      def inject_devise_content
        inject_into_file model_path, model_contents, after: "include CouchRest::Model::Base\n" if model_exists?
      end

      def migration_data
<<RUBY
  ## Database authenticatable
	property :email, String, :default => ""
	property :encrypted_password, String, :default => ""

  ## Recoverable
	property :reset_password_token, String
	property :reset_password_sent_at, Time

  ## Rememberable
	property :remember_created_at, Time

  ## Trackable
	property :sign_in_count, Integer, default: 0
  	property :current_sign_in_at, Time
	property :last_sign_in_at, Time
   property :current_sign_in_ip, String
  	property :last_sign_in_ip, String

  ## Confirmable
  # property :confirmation_token, String
  # property :confirmed_at,       Time
  # property :confirmation_sent_at, Time
  # property :unconfirmed_email,  String # Only if using reconfirmable

  ## Lockable
  # property :failed_attempts, Integer, default: 0 # Only if lock strategy is :failed_attempts
  # property :unlock_token,  String # Only if unlock strategy is :email or :both
  # property :locked_at,  Time
RUBY
      end
    end
  end
end


text:
const port = process.env.PORT || 4000;
let db = process.env.MONGODB_URI || "mongodb://localhost:27017/nodegoat";

module.exports = {
    port,
    db,
    cookieSecret: "session_cookie_secret_key_here",
    cryptoKey: "a_secure_key_for_crypto_here",
    cryptoAlgo: "aes256",
    hostName: "localhost",
    environmentalScripts: []
};


text:
#ifndef _DECAF_IO_READER_H
#define _DECAF_IO_READER_H

#include <string>
#include <decaf/lang/Readable.h>
#include <decaf/io/Closeable.h>
#include <decaf/io/IOException.h>
#include <decaf/io/InputStream.h>

#include <decaf/lang/exceptions/IndexOutOfBoundsException.h>
#include <decaf/lang/exceptions/NullPointerException.h>

namespace decaf{
namespace io{

    /*
     * Abstract class for reading character streams. The only methods that a subclass
     * must implement are read( char*, size_t, size_t ) and close(). Most subclasses,
     * however, will override some of the methods defined here in order to provide
     * higher efficiency, additional functionality, or both.
     *
     * @since 1.0
     */
    class DECAF_API Reader: public virtual decaf::io::Closeable, public virtual decaf::lang::Readable {
    private:

        Reader(const Reader&);
        Reader& operator=(const Reader&);

    protected:

        Reader();

    public:

        virtual ~Reader();

        /**
         * Marks the present position in the stream. Subsequent calls to reset() will attempt
         * to reposition the stream to this point. Not all character-input streams support
         * the mark() operation.
         *
         * @param readAheadLimit
         *      Limit on the number of characters that may be read while still preserving the
         *      mark. After reading this many characters, attempting to reset the stream may fail.
         *
         * @throw IOException if an I/O error occurs, or the stream does not support mark.
         */
        virtual void mark(int readAheadLimit);

        /**
         * Tells whether this stream supports the mark() operation. The default implementation
         * always returns false. Subclasses should override this method.
         *
         * @return true if and only if this stream supports the mark operation.
         */
        virtual bool markSupported() const {
            return false;
        }

        /**
         * Tells whether this stream is ready to be read.
         *
         * @return True if the next read() is guaranteed not to block for input, false otherwise.
         *         Note that returning false does not guarantee that the next read will block.
         *
         * @throw IOException if an I/O error occurs.
         */
        virtual bool ready() const;

        /**
         * Resets the stream. If the stream has been marked, then attempt to reposition it at the
         * mark. If the stream has not been marked, then attempt to reset it in some way appropriate
         * to the particular stream, for example by repositioning it to its starting point. Not all
         * character-input streams support the reset() operation, and some support reset() without
         * supporting mark().
         *
         * @throw IOException if an I/O error occurs.
         */
        virtual void reset();

        /**
         * Skips characters. This method will block until some characters are available, an I/O error
         * occurs, or the end of the stream is reached.
         *
         * @param count
         *      The number of character to skip.
         *
         * @return the number of Character actually skipped.
         *
         * @throw IOException if an I/O error occurs.
         */
        virtual long long skip(long long count);

        /**
         * Reads characters into an array. This method will block until some input is available,
         * an I/O error occurs, or the end of the stream is reached.
         *
         * @param buffer
         *       The buffer to read characters into.
         *
         * @return The number of characters read, or -1 if the end of the stream has been reached
         *
         * @throws IOException thrown if an I/O error occurs.
         */
        virtual int read(std::vector<char>& buffer);

        /**
         * Reads characters into an array, the method will attempt to read as much data as the size
         * of the array. This method will block until some input is available, an I/O error occurs,
         * or the end of the stream is reached.
         *
         * @param buffer
         *      The target char buffer.
         * @param size
         *      The size in bytes of the target buffer.
         *
         * @return The number of bytes read or -1 if the end of stream is reached.
         *
         * @throws IOException thrown if an I/O error occurs.
         * @throws NullPointerException if buffer is NULL.
         */
        virtual int read(char* buffer, int size);

        /**
         * Reads characters into a portion of an array. This method will block until some input
         * is available, an I/O error occurs, or the end of the stream is reached.
         *
         * @param buffer
         *      The target char buffer.
         * @param size
         *      The size in bytes of the target buffer.
         * @param offset
         *      The position in the buffer to start filling.
         * @param length
         *      The maximum number of bytes to read.
         *
         * @return The number of bytes read or -1 if the end of stream is reached.
         *
         * @throws IOException thrown if an I/O error occurs.
         * @throws NullPointerException if buffer is NULL.
         * @throws IndexOutOfBoundsException if the offset + length is greater than the array size.
         */
        virtual int read(char* buffer, int size, int offset, int length);

        /**
         * Reads a single character. This method will block until a character is available,
         * an I/O error occurs, or the end of the stream is reached.
         *
         * Subclasses that intend to support efficient single-character input should override
         * this method.
         *
         * @return The character read, as an integer in the range 0 to 65535 (0x00-0xffff),
         *         or -1 if the end of the stream has been reached.
         *
         * @throws IOException thrown if an I/O error occurs.
         */
        virtual int read();

        virtual int read(decaf::nio::CharBuffer* charBuffer);

    protected:

        /**
         * Override this method to customize the functionality of the method
         * read( unsigned char* buffer, int size, int offset, int length ).
         *
         * All subclasses must override this method to provide the basic Reader
         * functionality.
         */
        virtual int doReadArrayBounded(char* buffer, int size, int offset, int length) = 0;

    protected:

        /**
         * Override this method to customize the functionality of the method
         * read( std::vector<char>& buffer ).
         */
        virtual int doReadVector(std::vector<char>& buffer);

        /**
         * Override this method to customize the functionality of the method
         * read( char* buffer, std::size_t length ).
         */
        virtual int doReadArray(char* buffer, int length);

        /**
         * Override this method to customize the functionality of the method
         * read().
         */
        virtual int doReadChar();

        /**
         * Override this method to customize the functionality of the method
         * read( CharBuffer* charBuffer ).
         */
        virtual int doReadCharBuffer(decaf::nio::CharBuffer* charBuffer);

    };

}}

#endif /*_DECAF_IO_READER_H*/


text:
package org.jkiss.dbeaver.ext.postgresql.model.sql.generator;

import org.jkiss.dbeaver.DBException;
import org.jkiss.dbeaver.model.runtime.DBRProgressMonitor;
import org.jkiss.dbeaver.model.sql.generator.SQLGenerator;
import org.jkiss.dbeaver.model.struct.DBSEntity;

public class SQLGeneratorTypeAddValue extends SQLGenerator<Object> {

    @Override
    protected void generateSQL(DBRProgressMonitor monitor, StringBuilder sql, Object object) throws DBException {
        String entityName = getEntityName((DBSEntity) object);
        sql.append("ALTER TYPE ").append(entityName).append(" ADD VALUE ''");
        sql.append(";").append(getLineSeparator());
    }
}


text:
title: Solut
layout: default
---

Tähän pitäisi tulla sisältöä.


text:
import React, { Component } from 'react';

// Components
import Icon from './Icon.js';

class Reference extends Component {
  constructor(props) {
    super(props);
    this.state = {
      github: "https://github.com/icalving",
      email: "mailto:calvinieong1118@gmail.com",
      linkedin: "https://www.linkedin.com/in/calvinieong",
    };
  }

  render() {

    const {
      github,
      email,
      linkedin,
     } = this.state;

    return (
      <div className="reference__wrapper">
        <Icon
          brand={"b"}
          type={"github"}
          link={github}
        />
        <Icon
          type={"envelope"}
          link={email}
        />
        <Icon
          brand={"b"}
          type={"linkedin-in"}
          link={linkedin}
        />
      </div>
    );
  };
};

export default Reference;


text:
package proguard.optimize;

import proguard.classfile.*;
import proguard.classfile.util.MethodLinker;
import proguard.classfile.visitor.*;
import proguard.optimize.info.NoSideEffectMethodMarker;

/**
 * This ClassVisitor and MemberVisitor
 * marks classes and class members it visits. The marked elements
 * will remain unchanged as necessary in the optimization step.
 *
 * @see NoSideEffectMethodMarker
 * @author Eric Lafortune
 */
public class KeepMarker
implements   ClassVisitor,
             MemberVisitor
{
    // A visitor info flag to indicate the visitor accepter is being kept.
    private static final Object KEPT = new Object();

    // Implementations for ClassVisitor.

    public void visitProgramClass(ProgramClass programClass)
    {
        markAsKept(programClass);
    }

    public void visitLibraryClass(LibraryClass libraryClass)
    {
        markAsKept(libraryClass);
    }

    // Implementations for MemberVisitor.

    public void visitProgramField(ProgramClass programClass, ProgramField programField)
    {
        markAsKept(programField);
    }

    public void visitProgramMethod(ProgramClass programClass, ProgramMethod programMethod)
    {
        markAsKept(MethodLinker.lastMember(programMethod));
    }

    public void visitLibraryField(LibraryClass libraryClass, LibraryField libraryField)
    {
        markAsKept(libraryField);
    }

    public void visitLibraryMethod(LibraryClass libraryClass, LibraryMethod libraryMethod)
    {
        markAsKept(MethodLinker.lastMember(libraryMethod));
    }

    // Small utility methods.

    private static void markAsKept(VisitorAccepter visitorAccepter)
    {
        visitorAccepter.setVisitorInfo(KEPT);
    }

    public static boolean isKept(VisitorAccepter visitorAccepter)
    {
        // We're also checking for the constant in NoSideEffectMethodMarker,
        // to keep things simple.
        Object visitorInfo =
            MethodLinker.lastVisitorAccepter(visitorAccepter).getVisitorInfo();

        return visitorInfo == KEPT ||
               visitorInfo == NoSideEffectMethodMarker.KEPT_BUT_NO_SIDE_EFFECTS;
    }
}


text:
function processResults(data) {
    var serviceData = [];
    for (i = 0; i < data.length; i++) {
        var groupName = data[i].ServiceType;
        var serviceDescription = data[i].Description;
        groupName = groupName.replace(/\\n/g, "\n");
        groupName = groupName.replace(/\n /g, "\n");
        serviceDescription = serviceDescription.replace(/\\n/g, "\n");
        serviceDescription = serviceDescription.replace(/\n /g, "\n");
        serviceDescription = serviceDescription.replace(/\nRecycling/g, " Recycling");
        serviceDescription = serviceDescription.replace(/\n\nPlease/g, " Please");
        var link = "";
        var buttonTitle = "";
        if (void 0 !== data[i].additionalData && null !== data[i].additionalData) {
            link = data[i].additionalData[0].link;
            buttonTitle = data[i].additionalData[0].title;
        }
        var serviceObj = {
            service: groupName,
            value: serviceDescription,
            link: link,
            buttonTitle: buttonTitle
        };
        serviceData.push(serviceObj);
    }
    createServicesSections(serviceData);
}

var webCalls = require("webcalls");

exports.parentHandle = null;

exports.getCombinedServicesfromServer = function(parentHandle, cagaddressid) {
    var addrID = cagaddressid;
    exports.parentHandle = parentHandle;
    webCalls.JSONrequest({
        method: "GET",
        action: Alloy.Globals.cagapp.csrDomain + Alloy.Globals.cagapp.csrVirtualDir + "CinciServices/servicesList",
        parameters: {
            addressid: addrID
        },
        success: onServerDataCall_Success_services,
        error: onServerDataCall_Failure_services
    });
};

var onServerDataCall_Success_services = function(_jsonReply) {
    var $ = exports.parentHandle;
    $.actIndicator.hide();
    "SUCCESS" === _jsonReply.Status ? processResults(_jsonReply.Services) : alert(_jsonReply.Status);
};

var onServerDataCall_Failure_services = function() {
    $.actIndicator.hide();
};

var createServicesSections = function(serviceData) {
    var $ = exports.parentHandle;
    var fData = [];
    for (var i = 0; i < serviceData.length; i++) {
        var tableViewSection = Ti.UI.createTableViewSection({
            headerTitle: serviceData[i].service
        });
        var tvr = Ti.UI.createTableViewRow();
        var lblArgs = {
            classes: [ "rowLabel" ],
            text: serviceData[i].value
        };
        var txtLbl = $.UI.create("Label", lblArgs);
        tvr.add(txtLbl);
        if ("" !== serviceData[i].buttonTitle) {
            var btnArgs = {
                classes: [ "rowDocumentButton" ],
                title: serviceData[i].buttonTitle
            };
            var documentButton = $.UI.create("Button", btnArgs);
            mLink = serviceData[i].link;
            documentButton.addEventListener("click", function() {
                Titanium.Platform.openURL(mLink);
            });
            tvr.add(documentButton);
        }
        tableViewSection.add(tvr);
        fData.push(tableViewSection);
    }
    $.TV_serviceDates.setData(fData);
};


text:
<?php

require __DIR__ . "/../common/Zan_BaseTcpServer.php";

class EofSplitTcpServer extends Zan_BaseTcpServer {
    protected $package_sof = null;   // 包开始的标记
    protected $package_eof = null;   // 包结尾的标记

    protected $param = array();
    public function setParam(array $param) {
        $this->param = $param;
    }
    public function getParam() {
        return $this->param;
    }

    protected $server_conf = array(
        'dispatch_mode'         => 3,    //1: 轮循, 2: 固定(同一个连接的数据只会发给同一个worker处理), 3: 争抢
        'open_eof_check'        => true, //打开EOF检测
        'open_eof_split'        => true, //从数据中查找EOF,并切分数据
        'package_eof'           => '#',  //包结尾标记
    );

    public static function createServer(string $listen_ip = "0.0.0.0", int $listen_port = 9505, string $package_sof='*', string $package_eof='#') {

        $server = parent::createServer($listen_ip, $listen_port);

        $server->server_conf['package_eof'] = $package_eof;
        $server->package_sof = $package_sof;
        $server->package_eof = $package_eof;

        return $server;
    }

    //进程名前缀
    private $base_process_name = 'zan_tcp_server_';
    private $isset_process_name = true;

    //存放master进程pid的文件
    protected $pid_file = '/tmp/';

    public function getZanServer() {
        if (null != $this->zan_server) {
            return $this->zan_server;
        }

        $this->setServerConf($this->param);

        $listen_port = $this->getListenPort();
        $process_name = "";

        //set process name
        if(isset($this->param['process_name'])) {
            $process_name = $this->param['process_name'];
        }

        if(empty($process_name)) {
            $this->base_process_name = $this->base_process_name . $listen_port . '_';
            $this->isset_process_name = false;
        } else {
            $this->base_process_name = $this->base_process_name . $process_name . "_" . $listen_port . '_';
        }

        //pid_file name
        if (isset($this->param['pid_file_prefix'])) {
            $this->pid_file = $this->param['pid_file_prefix'] . '_' . $listen_port . '_pid';
        } else {
            $this->pid_file = $this->pid_file . $this->base_process_name . 'pid';
        }

        $this->zan_server = parent::getZanServer();
        return $this->zan_server;
    }

    //master process start
    public function onStart(swoole_server $serv) {
        if($this->isset_process_name) {
            swoole_set_process_name($this->base_process_name . 'master');
        }

        $mypid = $this->getZanServer()->master_pid;
        file_put_contents($this->pid_file, $mypid);

        $this->logger("onStart: master process start, pid=$mypid.\n");
    }

    //manager process start
    public function onManagerStart(swoole_server $serv) {
        $pid = getmypid();
        //$this->logger("onManagerStart: manager process start, pid=$pid.\n");

        if($this->isset_process_name) {
            swoole_set_process_name($this->base_process_name . 'Manager');
        }
    }

    protected $worker_id = -1;
    //worker process start
    public function onWorkerStart(swoole_server $serv, int $worker_id) {
        $pid = getmypid();
        $this->worker_id = $worker_id;
        if ($worker_id >= $this->getZanServer()->setting['worker_num']) {
            //task_worker
            if($this->isset_process_name) {
                swoole_set_process_name($this->base_process_name . 'TaskWorker');
            }
            //$this->logger("TaskWorker worker_id=$worker_id start, pid=$pid.\n");
        } else {
            //worker process
            if($this->isset_process_name) {
                swoole_set_process_name($this->base_process_name . 'Worker');
            }
            //$this->logger("Worker worker_id=$worker_id start, pid=$pid.\n");

            //我们在第一个 worker 进程, worker_id=0 的进程中启动一个定时器
            if (0 == $worker_id) {
                $this->resetTimer(30000);
            }
        }
    }

    protected $timer_id = null;
    protected function resetTimer($ms) {
        if ($this->timer_id && swoole_timer_exists($this->timer_id)) {
            swoole_timer_clear($this->timer_id);
            $this->timer_id = null;
        }
        $this->timer_id = swoole_timer_after($ms, array($this, 'onTimerTick'));
    }

    public function onTimerTick() {
        //$this->logger("onTimerTick...\n");

        //TODO::可以在这里做一些需要定时操作的事情

        $this->resetTimer(30000);
    }

    //server shutdown
    public function onShutdown(swoole_server $serv) {
        $this->logger("onShutdown: server shutdown.\n");
        file_put_contents($this->pid_file, '');
    }

    //onReceive event
    public function onReceiveCall(swoole_server $serv, int $worker_id, int $reactor_id, string $data) {
        $this->logger("onReceiveCall: worker_id=$worker_id, reactor_id=$reactor_id,data=$data\n");

        //TODO::这里可以做一些数据处理的事情
        //==================分包,丢弃包头和包尾的字符
        $start  = mb_strpos($data, $this->package_sof);
        $length = mb_strlen($data);
        if (false === $start) {
            $offset = 0;
        } else if($start == $length - 1) {
            $offset = 0;
        } else {
            $offset = $start + mb_strlen($this->package_sof);
        }

        $end = mb_strpos($data, $this->package_eof, $offset);
        if ($end > $offset) {
            $data = mb_substr($data, $offset, $end - $offset);
        } else {
            $data = mb_substr($data, $offset);
        }

        //丢弃了包头* 和包尾$ 的字符串,并投递到 task_worker 进程中
        $serv->task($data);
        //$task_id = $serv->task($data);

    }

    public function onTask(swoole_server $serv, int $task_id, int $worker_id, string $task_data){
        //$this->logger("onTask: worker_id=$worker_id, data=$task_data\n");

        //TODO::task_worker进程,这里可以进行一些比较耗时的操作
        //      比如,访问 mysql, 请求其他 http 接口等...
        //......
        $data_array = explode('|', $task_data);
        $this->logger($data_array[0] . ',' . $data_array[1] . ',' . $data_array[2] . ',' . $data_array[3]);

        //将处理结果返回给 worker 进程
        $ret = 1;
        $serv->finish($ret);
    }

    public function onFinish(swoole_server $serv, int $task_id, string $result) {
        //$this->logger("onFinish: receive result from task_worker, task_id=$task_id, result=$result\n");
    }

    public function logger(string $data) {
        echo "\n[" . date('Y-m-d H:i:s') . "]" . " " . get_class() . " " . $data;
    }
}