text:
package com.amazonaws.metrics;
import static com.amazonaws.SDKGlobalConfiguration.DEFAULT_METRICS_SYSTEM_PROPERTY;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.InetAddress;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.amazonaws.SDKGlobalConfiguration;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.AWSCredentialsProvider;
import com.amazonaws.auth.DefaultAWSCredentialsProviderChain;
import com.amazonaws.auth.PropertiesCredentials;
import com.amazonaws.jmx.spi.SdkMBeanRegistry;
import com.amazonaws.regions.Regions;
import com.amazonaws.util.AWSRequestMetrics;
import com.amazonaws.util.AWSRequestMetrics.Field;
import com.amazonaws.util.AWSServiceMetrics;

/**
 * Used to control the default AWS SDK metric collection system.
 *

 * The default metric collection of the Java AWS SDK is disabled by default. To
 * enable it, simply specify the system property
 * "com.amazonaws.sdk.enableDefaultMetrics" when starting up the JVM.
 * When the system property is specified, a default metric collector will be
 * started at the AWS SDK level. The default implementation uploads the
 * request/response metrics captured to Amazon CloudWatch using AWS credentials
 * obtained via the {@link DefaultAWSCredentialsProviderChain}.
 *

 * For additional optional attributes that can be specified for the system
 * property, please read the javadoc of the individual fields of
 * this class for more details.
 *

 * Instead of via system properties, the default AWS SDK metric collection can
 * also be enabled programmatically via {@link #enableDefaultMetrics()}.
 * Similarly, metric collection at the AWS SDK level can be disabled via
 * {@link #disableMetrics()}.
 *

 * Clients who needs to fully customize the metric collection can implement the
 * SPI {@link MetricCollector}, and then replace the default AWS SDK
 * implementation of the collector via
 * {@link #setMetricCollector(MetricCollector)}.
 *

 * Alternatively, for limited customization of the internal collector
 * implementation provided by the AWS SDK, one can extend the internal Amazon
 * CloudWatch metric collector. See the javadoc at
 * com.amazonaws.metrics.internal.cloudwatch.CloudWatchMetricConfig for more
 * details.
 */
public enum AwsSdkMetrics {
    ;
    private static final Log log = LogFactory.getLog(AwsSdkMetrics.class);
    public static final String DEFAULT_METRIC_NAMESPACE = "AWSSDK/Java";
    private static final String MBEAN_OBJECT_NAME =
        "com.amazonaws.management:type=" + AwsSdkMetrics.class.getSimpleName();

    /**
     * Object name under which the Admin Mbean of the current classloader is
     * registered.
     */
    private static volatile String registeredAdminMbeanName;
    /**
     * Used to enable the use of a single metric namespace for all levels of SDK
     * generated CloudWatch metrics such as JVM level, host level, etc.
     *
     *

     * Example:
     *  -Dcom.amazonaws.sdk.enableDefaultMetrics=useSingleMetricNamespace
     *

     */
    public static final String USE_SINGLE_METRIC_NAMESPACE = "useSingleMetricNamespace";
    /**
     * Used to exclude the generation of JVM metrics when the AWS SDK default
     * metrics is enabled.
     * By default, jvm metrics is included.
     *
     *

     * Example:
     *  -Dcom.amazonaws.sdk.enableDefaultMetrics=excludeJvmMetrics
     *

     */
    public static final String EXCLUDE_MACHINE_METRICS = "excludeMachineMetrics";

    /**
     * Used to generate per host level metrics when the AWS SDK default
     * metrics is enabled.
     * By default, per-host level metrics is excluded.
     *
     *

     * Example:
     *  -Dcom.amazonaws.sdk.enableDefaultMetrics=includePerHostMetrics
     *

     */
    public static final String INCLUDE_PER_HOST_METRICS = "includePerHostMetrics";

    /**
     * Used to specify an AWS credential property file.
     * By default, the {@link DefaultAWSCredentialsProviderChain} is used.
     *
     *

     * Example:
     *  -Dcom.amazonaws.sdk.enableDefaultMetrics=credentialFile=/path/aws.properties
     *

     * @deprecated in favor of {@link AWS_CREDENTIAL_PROPERTIES_FILE}
     */
    public static final String AWS_CREDENTAIL_PROPERTIES_FILE= "credentialFile";

    /**
     * Used to specify an AWS credential property file.
     * By default, the {@link DefaultAWSCredentialsProviderChain} is used.
     *
     *

     * Example:
     *  -Dcom.amazonaws.sdk.enableDefaultMetrics=credentialFile=/path/aws.properties
     *

     */
    public static final String AWS_CREDENTIAL_PROPERTIES_FILE= "credentialFile";

    /**
     * Used to specify the Amazon CloudWatch region for metrics uploading purposes.
     * By default, metrics are uploaded to us-east-1.
     *
     *

     * Example:
     *  -Dcom.amazonaws.sdk.enableDefaultMetrics=cloudwatchRegion=us-west-2
     *

     */
    public static final String CLOUDWATCH_REGION = "cloudwatchRegion";

    /**
     * Used to specify the internal in-memory queue size for queuing metrics
     * data points. The default size is 1,000.
     *
     *

     * Example:
     *  -Dcom.amazonaws.sdk.enableDefaultMetrics=metricQueueSize=1000
     *

     */
    public static final String METRIC_QUEUE_SIZE = "metricQueueSize";

    /**
     * Used to specify the internal queue polling timeout in millisecond.
     * The default timeout is 1 minute, which is optimal for the default
     * CloudWatch implementation.
     *
     *

     * Example:
     *  -Dcom.amazonaws.sdk.enableDefaultMetrics=getQueuePollTimeoutMilli=60000
     *

     */
    public static final String QUEUE_POLL_TIMEOUT_MILLI = "getQueuePollTimeoutMilli";

    /**
     * Used to specify a custom metric name space.
     * The default name space is {@link #DEFAULT_METRIC_NAMESPACE}.
     *
     *

     * Example:
     *  -Dcom.amazonaws.sdk.enableDefaultMetrics=metricNameSpace=MyNameSpace
     *

     */
    public static final String METRIC_NAME_SPACE = "metricNameSpace";

    /**
     * Used to generate per JVM level metrics when the AWS SDK default
     * metrics is enabled.
     * By default, JVM level metrics are not generated.
     *
     *

     * Example:
     *  -Dcom.amazonaws.sdk.enableDefaultMetrics=jvmMetricName=Tomcat1
     *

     */
    public static final String JVM_METRIC_NAME = "jvmMetricName";

    /**
     * Used to explicitly specify the host name for metric purposes, instead of
     * detecting the host name via {@link InetAddress} when the AWS SDK default
     * metrics is enabled. Specifying the host name also has the side effecting
     * of enabling per host level metrics.
     *
     *

     * Example:
     *  -Dcom.amazonaws.sdk.enableDefaultMetrics=hostMetricName=MyHost
     *

     */
    public static final String HOST_METRIC_NAME = "hostMetricName";

    private static final String DEFAULT_METRIC_COLLECTOR_FACTORY =
        "com.amazonaws.metrics.internal.cloudwatch.DefaultMetricCollectorFactory";

    /**
     * Used to explicitly enable {@link Field#HttpSocketReadTime} for recording socket read time.
     *
     *

     * Example:
     *  -Dcom.amazonaws.sdk.enableDefaultMetrics=enableHttpSocketReadMetric
     *

     */
    private static final String ENABLE_HTTP_SOCKET_READ_METRIC = "enableHttpSocketReadMetric";
    /**
     * True if the system property {@link #DEFAULT_METRICS_SYSTEM_PROPERTY} has
     * been set; false otherwise.
     */
    private static final boolean defaultMetricsEnabled;
    private static volatile AWSCredentialsProvider credentialProvider;
    /**
     * True if machine metrics is to be excluded; false otherwise.
     */
    private static volatile boolean machineMetricsExcluded;
    /**
     * True if per-host metrics is to be included; false if per-host metrics is
     * to be excluded when {@link #hostMetricName} is not specified. In the
     * absence of {@link #hostMetricName}, the host name will be automatically
     * detected via {@link InetAddress}.
     */
    private static volatile boolean perHostMetricsIncluded;

    /**
     * True if socket read time metric is enabled; false otherwise. The {@link Field#HttpSocketReadTime}
     * could have a big impact to performance, disabled by default.
     */
    private static volatile boolean httpSocketReadMetricEnabled;

    private static volatile Regions region;
    private static volatile Integer metricQueueSize;
    private static volatile Long queuePollTimeoutMilli;
    private static volatile String metricNameSpace = DEFAULT_METRIC_NAMESPACE;
    private static volatile String credentialFile;

    /**
     * No JVM level metrics is generated if this field is set to null or blank.
     * Otherwise, the value in this field is used to compose the metric name
     * space.
     *
     * Example:
     *

     *
If jvmMetricName="Tomcat1" and host-level metrics is disabled, the
     * metric name space will be something like: "AWSSDK/Java/Tomcat1".

     *
If jvmMetricName="Tomcat1" and host-level metrics is enabled, the
     * metric name space will be something like:
     * "AWSSDK/Java/myhost.mycompany.com/Tomcat1".

     *
If jvmMetricName="Tomcat1" and host-level metrics is enabled and the
     * metricNameSpace="MyNameSpace", the metric name space will be something
     * like: "MyNameSpace/myhost.mycompany.com/Tomcat1".

     *

     */
    private static volatile String jvmMetricName;
    private static volatile String hostMetricName;
    /**
     * True if the same metric namespace is to be used for all levels (such as
     * JVM level, host-level, etc.) of AWS Cloudwatch Metrics for the Java SDK;
     * false otherwise.
     */
    private static volatile boolean singleMetricNamespace;

    static {
        String defaultMetrics = System.getProperty(DEFAULT_METRICS_SYSTEM_PROPERTY);
        defaultMetricsEnabled = defaultMetrics != null;
        if (defaultMetricsEnabled) {
            String[] values = defaultMetrics.split(",");
            boolean excludeMachineMetrics = false;
            boolean includePerHostMetrics = false;
            boolean useSingleMetricNamespace = false;
            boolean enableHttpSocketReadMetric = false;
            for (String s: values) {
                String part = s.trim();
                if (!excludeMachineMetrics && EXCLUDE_MACHINE_METRICS.equals(part)) {
                    excludeMachineMetrics = true;
                } else if (!includePerHostMetrics && INCLUDE_PER_HOST_METRICS.equals(part)) {
                    includePerHostMetrics = true;
                } else if (!useSingleMetricNamespace && USE_SINGLE_METRIC_NAMESPACE.equals(part)) {
                    useSingleMetricNamespace = true;
                } else if (!enableHttpSocketReadMetric && ENABLE_HTTP_SOCKET_READ_METRIC.equals(part)) {
                    enableHttpSocketReadMetric = true;
                } else {
                    String[] pair = part.split("=");
                    if (pair.length == 2) {
                        String key = pair[0].trim();
                        String value  = pair[1].trim();
                        try {
                            if (AWS_CREDENTAIL_PROPERTIES_FILE.equals(key)
                                    || AWS_CREDENTIAL_PROPERTIES_FILE.equals(key)) {
                                setCredentialFile0(value);
                            } else if (CLOUDWATCH_REGION.equals(key)) {
                                region = Regions.fromName(value);
                            } else if (METRIC_QUEUE_SIZE.equals(key)) {
                            	Integer i = Integer.valueOf(value);
                                if (i.intValue() < 1)
                                    throw new IllegalArgumentException(METRIC_QUEUE_SIZE + " must be at least 1");
                                metricQueueSize = i;
                            } else if (QUEUE_POLL_TIMEOUT_MILLI.equals(key)) {
                            	Long i = Long.valueOf(value);
                                if (i.intValue() < 1000)
                                    throw new IllegalArgumentException(QUEUE_POLL_TIMEOUT_MILLI + " must be at least 1000");
                                queuePollTimeoutMilli = i;
                            } else if (METRIC_NAME_SPACE.equals(key)) {
                                metricNameSpace = value;
                            } else if (JVM_METRIC_NAME.equals(key)) {
                                jvmMetricName = value;
                            } else if (HOST_METRIC_NAME.equals(key)) {
                                hostMetricName = value;
                            } else {
                                LogFactory.getLog(AwsSdkMetrics.class).debug("Ignoring unrecognized parameter: " + part);
                            }
                        } catch (Exception e) {
                            LogFactory.getLog(AwsSdkMetrics.class).debug("Ignoring failure", e);
                        }
                    }
                }
            }
            machineMetricsExcluded = excludeMachineMetrics;
            perHostMetricsIncluded = includePerHostMetrics;
            singleMetricNamespace = useSingleMetricNamespace;
            httpSocketReadMetricEnabled = enableHttpSocketReadMetric;
        }
    }

    private static final MetricRegistry registry = new MetricRegistry();
    private static volatile MetricCollector mc;
    /**
     * Used to disallow re-entrancy in enabling the default metric collection system.
     */
    private static boolean dirtyEnabling;
    /** Exports AwsSdkMetrics for JMX access. */
    static {
        try {
            registerMetricAdminMBean();
        } catch(Exception ex) {
            LogFactory.getLog(AwsSdkMetrics.class).warn("", ex);
        }
    }

    /**
     * Returns true if the metric admin MBean is currently registered for JMX
     * access; false otherwise.
     */
    public static boolean isMetricAdminMBeanRegistered() {
        SdkMBeanRegistry registry = SdkMBeanRegistry.Factory.getMBeanRegistry();
        return registeredAdminMbeanName != null
                && registry.isMBeanRegistered(registeredAdminMbeanName);
    }

    /**
     * Returns the name of the registered admin mbean; or null if the admin
     * mbean is not currently registered.
     */
    public static String getRegisteredAdminMbeanName() {
        return registeredAdminMbeanName;
    }

    /**
     * Registers the metric admin MBean for JMX access for the current
     * classloader. If an AdminMbean is found to have been registered under a
     * different class loader, the AdminMBean of the current class loader would
     * be registered under the same name {@link #MBEAN_OBJECT_NAME} but with an
     * additional suffix in the format of "/<count>", where count is a counter
     * incrementing from 1.
     *
     * @return true if the registeration succeeded; false otherwise.
     */
    public static boolean registerMetricAdminMBean() {
        SdkMBeanRegistry registry = SdkMBeanRegistry.Factory.getMBeanRegistry();
        synchronized(AwsSdkMetrics.class) {
            if (registeredAdminMbeanName != null)
                return false;   // already registered
            boolean registered = registry.registerMetricAdminMBean(MBEAN_OBJECT_NAME);
            if (registered) {
                registeredAdminMbeanName = MBEAN_OBJECT_NAME;
            } else {
                String mbeanName = MBEAN_OBJECT_NAME;
                int count = 0;
                while (registry.isMBeanRegistered(mbeanName)) {
                    mbeanName = MBEAN_OBJECT_NAME + "/" + ++count;
                }
                registered = registry.registerMetricAdminMBean(mbeanName);
                if (registered)
                    registeredAdminMbeanName = mbeanName;
            }
            if (registered)
                log.debug("Admin mbean registered under " + registeredAdminMbeanName);
            return registered;
        }
    }

    /**
     * Unregisters the metric admin MBean from JMX for the current classloader.
     *
     * @return true if the unregistration succeeded or if there is no admin
     *         MBean registered; false otherwise.
     */
    public static boolean unregisterMetricAdminMBean() {
        SdkMBeanRegistry registry = SdkMBeanRegistry.Factory.getMBeanRegistry();
        synchronized(AwsSdkMetrics.class) {
            if (registeredAdminMbeanName == null)
                return true;
            boolean success = registry.unregisterMBean(registeredAdminMbeanName);
            if (success)
                registeredAdminMbeanName = null;
            return success;
        }
    }
    /**
     * Returns a non-null request metric collector for the SDK. If no custom
     * request metric collector has previously been specified via
     * {@link #setMetricCollector(MetricCollector)} and the
     * {@link SDKGlobalConfiguration#DEFAULT_METRICS_SYSTEM_PROPERTY} has been set, then this method
     * will initialize and return the default metric collector provided by the
     * AWS SDK on a best-attempt basis.
     */
    public static <T extends RequestMetricCollector> T getRequestMetricCollector() {
        if (mc == null) {
            if (isDefaultMetricsEnabled())
                enableDefaultMetrics();
        }
        @SuppressWarnings("unchecked")
        T t = (T)(mc == null ? RequestMetricCollector.NONE : mc.getRequestMetricCollector());
        return t;
    }

    public static <T extends ServiceMetricCollector> T getServiceMetricCollector() {
        if (mc == null) {
            if (isDefaultMetricsEnabled())
                enableDefaultMetrics();
        }
        @SuppressWarnings("unchecked")
        T t = (T)(mc == null ? ServiceMetricCollector.NONE : mc.getServiceMetricCollector());
        return t;
    }

    /**
     * This method should never be called by anyone except the JMX MBean used
     * for administrative purposes only.
     */
    static MetricCollector getInternalMetricCollector() {
        return mc;
    }

    public static <T extends MetricCollector> T getMetricCollector() {
        if (mc == null) {
            if (isDefaultMetricsEnabled())
                enableDefaultMetrics();
        }
        @SuppressWarnings("unchecked")
        T t = (T)(mc == null ? MetricCollector.NONE : mc);
        return t;
    }

    /**
     * Sets the metric collector to be used by the AWS SDK, and stop the
     * previously running collector used by the AWS SDK, if any. Note, however,
     * a request metric collector specified at the web service client level or
     * request level, if any, always takes precedence over the one specified at
     * the AWS SDK level.
     *

     * Caller of this method is responsible for starting the new metric
     * collector specified as the input parameter.
     *
     * @param mc
     *            the metric collector to be used by the AWS SDK; or
     *            null if no metric collection is to be performed
     *            at the AWS SDK level.
     *
     * @see RequestMetricCollector
     * @see RequestMetricCollector#NONE
     */
    public static synchronized void setMetricCollector(MetricCollector mc) {
        MetricCollector old = AwsSdkMetrics.mc;
        AwsSdkMetrics.mc = mc;
        if (old != null) {
            old.stop();
        }
    }

    /**
     * Used to set whether the machine metrics is to be excluded.
     *
     * @param excludeMachineMetrics true if machine metrics is to be excluded;
     * false otherwise.
     */
    public static void setMachineMetricsExcluded(boolean excludeMachineMetrics) {
        AwsSdkMetrics.machineMetricsExcluded = excludeMachineMetrics;
    }

    /**
     * Used to set whether the per-host metrics is to be included.
     *
     * @param includePerHostMetrics true if per-host metrics is to be included;
     * false otherwise.
     */
    public static void setPerHostMetricsIncluded(boolean includePerHostMetrics) {
        AwsSdkMetrics.perHostMetricsIncluded = includePerHostMetrics;
    }

    /**
     * Used to enable {@link Field#HttpSocketReadTime} metric since by default it is disabled.
     */
    public static void enableHttpSocketReadMetric() {
        AwsSdkMetrics.httpSocketReadMetricEnabled = true;
    }

    /**
     * Returns true if the system property
     * {@link SDKGlobalConfiguration#DEFAULT_METRICS_SYSTEM_PROPERTY} has been
     * set; false otherwise.
     */
    public static boolean isDefaultMetricsEnabled() {
        return defaultMetricsEnabled;
    }

    /**
     * Returns true if a single metric name space is to be used for all
     * levels of SDK generated CloudWatch metrics, including JVM level, host
     * level, etc.; false otherwise.
     */
    public static boolean isSingleMetricNamespace() {
        return singleMetricNamespace;
    }

    /**
     * Used to set whether a single metric name space is to be used for all
     * levels of SDK generated CloudWatch metrics, including JVM level, host
     * level, etc.
     *
     * @param singleMetricNamespace
     *            true if single metric name is to be used; false otherwise.
     */
    public static void setSingleMetricNamespace(boolean singleMetricNamespace) {
        AwsSdkMetrics.singleMetricNamespace = singleMetricNamespace;
    }

    /**
     * Returns true if metrics at the AWS SDK level is enabled; false
     * if disabled.
     */
    public static boolean isMetricsEnabled() {
        MetricCollector mc = AwsSdkMetrics.mc;
        return mc != null && mc.isEnabled();
    }

    /**
     * Returns true if machine metrics is to be excluded.
     */
    public static boolean isMachineMetricExcluded() {
        return machineMetricsExcluded;
    }

    /**
     * Returns true if the per-host metrics flag has been set; false otherwise.
     */
    public static boolean isPerHostMetricIncluded() {
        return perHostMetricsIncluded;
    }

    /**
     * Returns true if per-host metrics is enabled; false otherwise.
     */
    public static boolean isPerHostMetricEnabled() {
        if (perHostMetricsIncluded)
            return true;
        String host = hostMetricName;
        host = host == null ? "" : host.trim();
        return host.length() > 0;
    }

    /**
     * Returns true if HttpSocketReadMetric is enabled; false otherwise.
     */
    public static boolean isHttpSocketReadMetricEnabled() {
        return httpSocketReadMetricEnabled;
    }

    /**
     * Starts the default AWS SDK metric collector, but
     * only if no metric collector is currently in use at the AWS SDK
     * level.
     *
     * @return true if the default AWS SDK metric collector has been
     *         successfully started by this call; false otherwise.
     */
    public static synchronized boolean enableDefaultMetrics() {
        if (mc == null || !mc.isEnabled()) {
            if (dirtyEnabling) {
                throw new IllegalStateException("Reentrancy is not allowed");
            }
            dirtyEnabling = true;
            try {
                Class<?> c = Class.forName(DEFAULT_METRIC_COLLECTOR_FACTORY);
                MetricCollector.Factory f = (MetricCollector.Factory)c.newInstance();
                MetricCollector instance = f.getInstance();
                if (instance != null) {
                    setMetricCollector(instance);
                    return true;
                }
            } catch (Exception e) {
                LogFactory.getLog(AwsSdkMetrics.class)
                    .warn("Failed to enable the default metrics", e);
            } finally {
                dirtyEnabling = false;
            }
        }
        return false;
    }

    /**
     * Convenient method to disable the metric collector at the AWS SDK
     * level.
     */
    public static void disableMetrics() {
        setMetricCollector(MetricCollector.NONE);
    }

    /**
     * Adds the given metric type to the registry of predefined metrics to be
     * captured at the AWS SDK level.
     *
     * @return true if the set of predefined metric types gets changed as a
     *        result of the call
     */
    public static boolean add(MetricType type) {
        return type == null ? false : registry.addMetricType(type);
    }
    /**
     * Adds the given metric types to the registry of predefined metrics to be
     * captured at the AWS SDK level.
     *
     * @return true if the set of predefined metric types gets changed as a
     *        result of the call
     */
    public static <T extends MetricType> boolean addAll(Collection<T> types) {
        return types == null || types.size() == 0
             ? false
             : registry.addMetricTypes(types);
    }
    /**
     * Sets the given metric types to replace the registry of predefined metrics
     * to be captured at the AWS SDK level.
     */
    public static <T extends MetricType> void set(Collection<T> types) {
        registry.setMetricTypes(types);
    }
    /**
     * Removes the given metric type from the registry of predefined metrics to
     * be captured at the AWS SDK level.
     *
     * @return true if the set of predefined metric types gets changed as a
     *        result of the call
     */
    public static boolean remove(MetricType type) {
        return type == null ? false : registry.removeMetricType(type);
    }
    /**
     * Returns an unmodifiable set of the current predefined metrics.
     */
    public static Set<MetricType> getPredefinedMetrics() {
        return registry.predefinedMetrics();
    }

    /**
     * Returns the credential provider for the default AWS SDK metric implementation.
     * This method is restricted to calls from the default AWS SDK metric implementation.
     *
     * @throws SecurityException if called outside the default AWS SDK metric implementation.
     */
    public static AWSCredentialsProvider getCredentialProvider() {
        StackTraceElement[] e = Thread.currentThread().getStackTrace();
        for (int i=0; i < e.length; i++) {
            if (e[i].getClassName().equals(DEFAULT_METRIC_COLLECTOR_FACTORY)) {
                return credentialProvider;
            }
        }
        SecurityException ex = new SecurityException();
        LogFactory.getLog(AwsSdkMetrics.class).warn("Illegal attempt to access the credential provider", ex);
        throw ex;
    }

    /**
     * Sets the credential provider for the default AWS SDK metric
     * implementation; or null if the default is to be used. Calling this method
     * may result in the credential provider being different from the credential
     * file property.
     */
    public static synchronized void setCredentialProvider(
            AWSCredentialsProvider provider) {
        credentialProvider = provider;
    }

    /**
     * Returns the region configured for the default AWS SDK metric collector;
     * or null if the default is to be used.
     */
    public static Regions getRegion() {
        return region;
    }

    /**
     * Sets the region to be used for the default AWS SDK metric collector;
     * or null if the default is to be used.
     */
    public static void setRegion(Regions region) {
        AwsSdkMetrics.region = region;
    }

    /**
     * Returns the last set AWS credential file, or null if there is none.
     */
    public static String getCredentailFile() {
        return credentialFile;
    }

    /**
     * Sets the AWS credential file to be used for accessing Amazon CloudWatch.
     * Successfully calling this method would result in the AWS credential
     * provider to make use of the given credential file.
     */
    public static void setCredentialFile(String filepath)
            throws FileNotFoundException, IOException {
        setCredentialFile0(filepath);
    }

    /**
     * Internal method to implement the {@link #setCredentialFile(String)}.
     */
    private static void setCredentialFile0(String filepath)
            throws FileNotFoundException, IOException {
        final PropertiesCredentials cred =
            new PropertiesCredentials(new File(filepath));
        synchronized(AwsSdkMetrics.class) {
            credentialProvider = new AWSCredentialsProvider() {
                @Override public void refresh() {}
                @Override public AWSCredentials getCredentials() {
                    return cred;
                }
            };
            AwsSdkMetrics.credentialFile = filepath;
        }
    }

    /**
     * Returns the internal metric queue size to be used for the default AWS SDK
     * metric collector; or null if the default is to be used.
     */
    public static Integer getMetricQueueSize() {
        return metricQueueSize;
    }

    /**
     * Sets the metric queue size to be used for the default AWS SDK metric collector;
     * or null if the default is to be used.
     */
    public static void setMetricQueueSize(Integer size) {
        metricQueueSize = size;
    }

    /**
     * Returns the internal metric queue timeout in millisecond to be used for
     * the default AWS SDK metric collector; or null if the default is to be
     * used.
     */
    public static Long getQueuePollTimeoutMilli() {
        return queuePollTimeoutMilli;
    }

    /**
     * Sets the queue poll time in millisecond to be used for the default AWS
     * SDK metric collector; or null if the default is to be used.
     */
    public static void setQueuePollTimeoutMilli(Long timeoutMilli) {
        queuePollTimeoutMilli = timeoutMilli;
    }

    /**
     * Returns the metric name space, which is never null or blank.
     */
    public static String getMetricNameSpace() {
        return metricNameSpace;
    }

    /**
     * Sets the metric name space.
     *
     * @param metricNameSpace
     *            metric name space which must neither be null or blank.
     *
     * @throws IllegalArgumentException
     *             if the specified metric name space is either null or blank.
     */
    public static void setMetricNameSpace(String metricNameSpace) {
        if (metricNameSpace == null || metricNameSpace.trim().length() == 0)
            throw new IllegalArgumentException();
        AwsSdkMetrics.metricNameSpace = metricNameSpace;
    }

    /**
     * Returns the name of the JVM for generating per-JVM level metrics;
     * or null or blank if per-JVM level metrics are disabled.
     */
    public static String getJvmMetricName() {
        return jvmMetricName;
    }

    /**
     * Sets the name of the JVM for generating per-JVM level metrics.
     *
     * @param jvmMetricName
     *            name of the JVM for generating per-JVM level metrics; or null
     *            or blank if per-JVM level metrics are to be disabled.
     */
    public static void setJvmMetricName(String jvmMetricName) {
        AwsSdkMetrics.jvmMetricName = jvmMetricName;
    }

    /**
     * Returns the host name for generating per-host level metrics; or
     * null or blank if the host is to be automatically detected via
     * {@link InetAddress}.
     */
    public static String getHostMetricName() {
        return hostMetricName;
    }

    /**
     * Sets the host name for generating per-host level metrics.
     *
     * @param hostMetricName
     *            host name for generating per-host level metrics; or
     *            null or blank if the host is to be automatically detected via
     *            {@link InetAddress}.
     */
    public static void setHostMetricName(String hostMetricName) {
        AwsSdkMetrics.hostMetricName = hostMetricName;
    }

    /**
     * Used as a registry for the predefined metrics to be captured by the
     * metric collector at the AWS SDK level.
     */
    private static class MetricRegistry {
        private final Set<MetricType> metricTypes = new HashSet<MetricType>();
        private volatile Set<MetricType> readOnly;

        MetricRegistry() {
            metricTypes.add(Field.ClientExecuteTime);
            metricTypes.add(Field.Exception);
            metricTypes.add(Field.ThrottleException);
            metricTypes.add(Field.HttpClientRetryCount);
            metricTypes.add(Field.HttpRequestTime);
            metricTypes.add(Field.RequestCount);
//            metricTypes.add(Field.RequestSigningTime);
//            metricTypes.add(Field.ResponseProcessingTime);
            metricTypes.add(Field.RetryCount);
            metricTypes.add(Field.RetryCapacityConsumed);
            metricTypes.add(Field.HttpClientSendRequestTime);
            metricTypes.add(Field.HttpClientReceiveResponseTime);
            metricTypes.add(Field.HttpSocketReadTime);
            metricTypes.add(Field.HttpClientPoolAvailableCount);
            metricTypes.add(Field.HttpClientPoolLeasedCount);
            metricTypes.add(Field.HttpClientPoolPendingCount);
            metricTypes.add(AWSServiceMetrics.HttpClientGetConnectionTime);
            syncReadOnly();
        }

        private void syncReadOnly() {
            readOnly = Collections.unmodifiableSet(new HashSet<MetricType>(metricTypes));
        }

        public boolean addMetricType(MetricType type) {
            synchronized(metricTypes) {
                boolean added = metricTypes.add(type);
                if (added)
                    syncReadOnly();
                return added;
            }
        }
        public <T extends MetricType> boolean addMetricTypes(Collection<T> types) {
            synchronized(metricTypes) {
                boolean added = metricTypes.addAll(types);
                if (added)
                    syncReadOnly();
                return added;
            }
        }
        public <T extends MetricType> void setMetricTypes(Collection<T> types) {
            synchronized(metricTypes) {
                if (types == null || types.size() == 0) {
                    if (metricTypes.size() == 0)
                        return;
                    if (types == null)
                        types = Collections.emptyList();
                }
                metricTypes.clear();
                if (!addMetricTypes(types)) {
                    syncReadOnly(); // avoid missing sync
                }
            }
        }
        public boolean removeMetricType(MetricType type) {
            synchronized(metricTypes) {
                boolean removed = metricTypes.remove(type);
                if (removed)
                    syncReadOnly();
                return removed;
            }
        }
        public Set<MetricType> predefinedMetrics() {
            return readOnly;
        }
    }
}


text:
layout: page
title: Fletcher 50th Anniversary
date: 2016-05-24
author: Joseph Hahn
tags: weekly links, java
status: published
summary: In rutrum odio vel nisi porta, eu tempor ligula sagittis.
banner: images/banner/people.jpg
booking:
  startDate: 02/28/2017
  endDate: 03/01/2017
  ctyhocn: LFTJEHX
  groupCode: F5A
published: true
---
Mauris ut diam id lacus ornare suscipit. Fusce vel scelerisque lorem, eu suscipit elit. Vivamus eget vulputate augue. Nulla ultricies risus eu libero cursus volutpat. Nullam vitae tincidunt justo, at dignissim tellus. Vestibulum at congue risus. Morbi posuere nibh vel hendrerit accumsan. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.

* Suspendisse convallis metus ut tortor fringilla egestas non non justo
* In accumsan ante at nunc ornare pretium
* Aenean scelerisque justo a velit rutrum pellentesque
* In sagittis velit a facilisis commodo
* In bibendum urna eu lacus venenatis accumsan.

Duis a tempor dui. In et lacus metus. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Ut euismod augue eu dui vestibulum ullamcorper in non mi. Praesent egestas nisi eget congue porta. Nulla nibh ligula, mollis quis bibendum nec, convallis sed quam. Nunc in laoreet enim. Aenean eget massa suscipit, pulvinar nisl et, mollis lorem. In molestie posuere venenatis. Fusce lacus justo, tempus at erat non, mattis sagittis enim. Morbi sit amet dictum dui, a interdum lectus. Suspendisse potenti. Nam id feugiat nibh.
Duis nec orci in quam vulputate dictum in quis arcu. Fusce euismod velit at laoreet aliquam. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Praesent facilisis consequat neque eget hendrerit. Proin metus orci, maximus id congue eu, vulputate id lorem. Nulla maximus ultricies urna eu mollis. Pellentesque eget velit ultricies, cursus diam nec, ultricies enim. Cras ac pulvinar lacus, ac egestas felis. Quisque placerat quam est, ullamcorper volutpat quam dapibus eu. Duis volutpat euismod lectus, id volutpat odio fringilla sodales. Suspendisse pretium lectus eget ligula vulputate volutpat. Praesent in laoreet eros, eget varius quam. Donec cursus finibus tortor, pharetra vulputate tortor tristique eget. Sed rutrum urna ac mi rutrum varius.

redpajama_set_name: RedPajamaGithub


text:
TruthTree::TruthTree(std::string outputFile):
  m_outputFile(outputFile),
  m_tfile(0),
  m_tree(0) {
  m_particleDataTable = new HepPDT::ParticleDataTable("Generic Particle Table");
}

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

TruthTree::~TruthTree() {
  if(m_tfile) delete m_tfile;
  if(m_particleDataTable) delete m_particleDataTable;
}

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

int TruthTree::open(void) {
  m_tfile = new TFile(m_outputFile.c_str(),"RECREATE");
  if(!m_tfile) {
    std::cerr << "Error: could not open root file " << m_outputFile << std::endl;
    return 1;
  }

  // Create a new tree
  m_tree = new TTree("mctree","Pythia Data");

  // Read in particle.tbl
  std::string ptbl = "particle.tbl";
  std::ifstream pdFile(ptbl.c_str());
  if(!pdFile) {
    std::cerr << "Cannot open " << ptbl << " for reading!" << std::endl;
    return 1;
  }

  HepPDT::TableBuilder tb(*m_particleDataTable);
  if(!addParticleTable(pdFile,tb)) {
    std::cerr << "Cannot add particle table" << std::endl;
    return 2;
  }

  return 0;
}

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

int TruthTree::save(void) {
  m_tfile->Write();

  return 0;
}

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

int TruthTree::book(void) {
  // Create new objects but do not delete them such that they can be
  // stored in the TTree
  m_truth_part_px = new std::vector<float>();
  m_truth_part_py = new std::vector<float>();
  m_truth_part_pz = new std::vector<float>();
  m_truth_part_e = new std::vector<float>();
  m_truth_part_status = new std::vector<long>();
  m_truth_part_pdgId = new std::vector<long>();
  m_truth_part_barcode = new std::vector<long>();
  m_truth_part_charge = new std::vector<float>();
  m_truth_part_prod_vtx = new std::vector<long>();
  m_truth_part_end_vtx = new std::vector<long>();
  m_truth_vtx_x = new std::vector<float>();
  m_truth_vtx_y = new std::vector<float>();
  m_truth_vtx_z = new std::vector<float>();
  m_truth_vtx_t = new std::vector<float>();
  m_truth_vtx_id = new std::vector<long>();
  m_truth_vtx_barcode = new std::vector<long>();

  // Assign the branch addresses of particle and vertex variables.
  m_tree->Branch("truth_npart",        &m_truth_npart, "truth_npart/I");
  m_tree->Branch("truth_part_px",      &m_truth_part_px);
  m_tree->Branch("truth_part_py",      &m_truth_part_py);
  m_tree->Branch("truth_part_pz",      &m_truth_part_pz);
  m_tree->Branch("truth_part_e",       &m_truth_part_e);
  m_tree->Branch("truth_part_status",  &m_truth_part_status);
  m_tree->Branch("truth_part_pdgId",   &m_truth_part_pdgId);
  m_tree->Branch("truth_part_barcode", &m_truth_part_barcode);
  m_tree->Branch("truth_part_charge",  &m_truth_part_charge);
  m_tree->Branch("truth_part_prod_vtx",&m_truth_part_prod_vtx);
  m_tree->Branch("truth_part_end_vtx", &m_truth_part_end_vtx);

  m_tree->Branch("truth_nvtx",         &m_truth_nvtx, "truth_nvtx/I");
  m_tree->Branch("truth_vtx_x",        &m_truth_vtx_x);
  m_tree->Branch("truth_vtx_y",        &m_truth_vtx_y);
  m_tree->Branch("truth_vtx_z",        &m_truth_vtx_z);
  m_tree->Branch("truth_vtx_t",        &m_truth_vtx_t);
  m_tree->Branch("truth_vtx_id",       &m_truth_vtx_id);
  m_tree->Branch("truth_vtx_barcode",  &m_truth_vtx_barcode);

  return 0;
}

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

int TruthTree::fill(HepMC::GenEvent *genEvent) {
  long ipart = 0, ivtx = 0;
  int ret_val;

  // Instantiate iterators needed in this member function.
  HepMC::GenEvent::particle_const_iterator hepmc_part_itr;
  HepMC::GenEvent::vertex_const_iterator hepmc_vtx_itr;

  // Clear the TTree associated vectors
  m_truth_part_px->clear();
  m_truth_part_py->clear();
  m_truth_part_pz->clear();
  m_truth_part_e->clear();
  m_truth_part_status->clear();
  m_truth_part_pdgId->clear();
  m_truth_part_barcode->clear();
  m_truth_part_charge->clear();
  m_truth_part_prod_vtx->clear();
  m_truth_part_end_vtx->clear();
  m_truth_vtx_x->clear();
  m_truth_vtx_y->clear();
  m_truth_vtx_z->clear();
  m_truth_vtx_t->clear();
  m_truth_vtx_id->clear();
  m_truth_vtx_barcode->clear();

  // Clear the number of particles and vertices.
  m_truth_npart = 0;
  m_truth_nvtx = 0;

  // Create maps used to map indices to pointers.
  std::map<HepMC::GenParticle *, long > particleIndexMap;
  std::map<HepMC::GenVertex *, long > vertexIndexMap;

  // Loop over all particles and build up the particle-index map.
  for (hepmc_part_itr = genEvent->particles_begin();
       hepmc_part_itr != genEvent->particles_end();
       hepmc_part_itr++) {
    particleIndexMap.insert(std::make_pair((*hepmc_part_itr),ipart));
    ipart++;
  }

  // Record the total number of particles
  m_truth_npart = ipart;

  // Loop over the vertices and build up the vertex-index map.
  for (hepmc_vtx_itr = genEvent->vertices_begin();
       hepmc_vtx_itr != genEvent->vertices_end();
       hepmc_vtx_itr++) {
    vertexIndexMap.insert(std::make_pair((*hepmc_vtx_itr),ivtx));
    ivtx++;
  }

  // Record the total number of vertices
  m_truth_nvtx = ivtx;

  // Increase the size of the TTree vectors to the number of particles
  // in this event.
  m_truth_part_px->resize(m_truth_npart,0.);
  m_truth_part_py->resize(m_truth_npart,0.);
  m_truth_part_pz->resize(m_truth_npart,0.);
  m_truth_part_e->resize(m_truth_npart,0.);
  m_truth_part_status->resize(m_truth_npart,0);
  m_truth_part_pdgId->resize(m_truth_npart,0);
  m_truth_part_barcode->resize(m_truth_npart,0);
  m_truth_part_charge->resize(m_truth_npart,0.);
  m_truth_part_prod_vtx->resize(m_truth_npart,0);
  m_truth_part_end_vtx->resize(m_truth_npart,0);

  // Write out the event.

  // Loop over the GenParticle map and fill the vectors storing
  // particle quantities.
  std::map<HepMC::GenParticle *, long >::iterator part_index_itr;
  for (part_index_itr = particleIndexMap.begin();
       part_index_itr != particleIndexMap.end();
       part_index_itr++) {

    // Get the particle index
    ipart = (*part_index_itr).second;

    // Fill the particle entries
    (*m_truth_part_px)[ipart] = (*part_index_itr).first->momentum().px();
    (*m_truth_part_py)[ipart] = (*part_index_itr).first->momentum().py();
    (*m_truth_part_pz)[ipart] = (*part_index_itr).first->momentum().pz();
    (*m_truth_part_e)[ipart] = (*part_index_itr).first->momentum().e();
    (*m_truth_part_status)[ipart] = (*part_index_itr).first->status();
    (*m_truth_part_pdgId)[ipart] = (*part_index_itr).first->pdg_id();
    (*m_truth_part_barcode)[ipart] = (*part_index_itr).first->barcode();

    // Find the index of the production vertex
    ret_val= findVertexIndex (&vertexIndexMap,
			      (*part_index_itr).first->production_vertex(),
			      &(*m_truth_part_prod_vtx)[ipart]);
    if(ret_val) return ret_val;

    // Find the index of the end vertex
    ret_val = findVertexIndex (&vertexIndexMap,
			       (*part_index_itr).first->end_vertex(),
			       &(*m_truth_part_end_vtx)[ipart]);
    if(ret_val) return ret_val;

    // Record the charge if the PDG id is known
    (*m_truth_part_charge)[ipart]=-999.0;
    const HepPDT::ParticleData* particleData = m_particleDataTable->particle(HepPDT::ParticleID(abs((*part_index_itr).first->pdg_id())));
    if(particleData) {
      (*m_truth_part_charge)[ipart] = particleData->charge();
      if ((*part_index_itr).first->pdg_id()<0) {
	(*m_truth_part_charge)[ipart] = -(*m_truth_part_charge)[ipart];
      }
    }
  }

  // Increase the size of the TTree vectors associated with vectices
  // to match the number of vertices in this event.
  m_truth_vtx_x->resize(m_truth_nvtx, 0.);
  m_truth_vtx_y->resize(m_truth_nvtx, 0.);
  m_truth_vtx_z->resize(m_truth_nvtx, 0.);
  m_truth_vtx_t->resize(m_truth_nvtx, 0.);
  m_truth_vtx_id->resize(m_truth_nvtx, 0);
  m_truth_vtx_barcode->resize(m_truth_nvtx, 0);

  // Write out the GenVertex object data.
  std::map<HepMC::GenVertex *, long >::iterator vtx_index_itr;
  std::vector<long > attachedParticles;
  for (vtx_index_itr = vertexIndexMap.begin();
       vtx_index_itr != vertexIndexMap.end();
       vtx_index_itr++) {

    // Get the vertex index
    ivtx = (*vtx_index_itr).second;

    // Fill the vertex entries
    (*m_truth_vtx_x)[ivtx] = (*vtx_index_itr).first->position().x();
    (*m_truth_vtx_y)[ivtx] = (*vtx_index_itr).first->position().y();
    (*m_truth_vtx_z)[ivtx] = (*vtx_index_itr).first->position().z();
    (*m_truth_vtx_t)[ivtx] = (*vtx_index_itr).first->position().t();
    (*m_truth_vtx_id)[ivtx] = (*vtx_index_itr).first->id();
    (*m_truth_vtx_barcode)[ivtx] = (*vtx_index_itr).first->barcode();
  }

  // Copy this entry into the TTree;
  m_tree->Fill();

  return 0;
}

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

int TruthTree::findVertexIndex (std::map<HepMC::GenVertex *, long > *vertexIndexMap,
				HepMC::GenVertex *vtxPtr, long *index) {
  std::map<HepMC::GenVertex *, long >::iterator vtx_index_itr;

  // Test if the vertex pointer is null or not.
  if(vtxPtr) {

    // Find the vertex in the map
    vtx_index_itr = vertexIndexMap->find(vtxPtr);

    if(vtx_index_itr==vertexIndexMap->end()) {
      std::cerr << "Error: the vertex does not exist in the map" << std::endl;
      *index = -999;
      return 1;
    }

    // Assign the index of this vertex;
    *index = (*vtx_index_itr).second;
  }
  else {
    // There is no vertex assign -1;
    *index = -1;
  }

  return 0;
}


text:
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq.Expressions;
using System.Text;

namespace FclEx.TypeCasters
{
    public class DelegateTypeCaster : AbstractTypeCaster<DelegateTypeCaster>
    {
        [return: MaybeNull]
        public override TOutput CastTo<TInput, TOutput>([AllowNull]TInput obj)
        {
            return obj == null
                ? default
                : ConvertHelper<TOutput>.ConvertTo(obj);
        }

        private static class ConvertHelper<TOutput>
        {
            private delegate TOutput Converter(object obj);
            private static readonly ConcurrentDictionary<Type, Converter> _dic
                = new ConcurrentDictionary<Type, Converter>();

            public static TOutput ConvertTo(object obj)
            {
                var converter = _dic.GetOrAdd(obj.GetType(), t =>
                {
                    var p = Expression.Parameter(typeof(object));
                    var exp = (Expression)p;
                    if (t != typeof(object))
                    {
                        exp = Expression.Convert(exp, t);
                    }
                    var lambda = Expression.Convert(exp, typeof(TOutput));
                    return Expression.Lambda<Converter>(lambda, p).Compile();
                });
                return converter.Invoke(obj);
            }
        }
    }
}


text:
{% load pinax_theme_bootstrap_tags %}

  {% for message in messages %}

      <button type="button" class="close" data-dismiss="alert">×</button>
      {{ message }}

  {% endfor %}


text:
def cat(filename):
    """Return the contents of a file. Replaces the `cat` command.

    This function took about ~148 time units per call, while
    run(['cat']) needed ~4688 time units.
    """
    try:
        with open(filename, 'r', encoding='utf-8') as infile:
            return 'success', infile.read()
    except Exception:
        return 'failure', None


text:
const env = process.env.NODE_ENV || 'production'

/* copy the .env.(dev|prod) to .env */
const envPath = `.env.${env === 'production' ? 'prod' : 'dev'}`

const fs = require('fs')
;(function copySync(src, dest, fs) {
  if (!fs.existsSync(src)) {
    throw new Error(
      `please setup your ${envPath}!\n .env.example could be referred for setting your runtime environment.`
    )
  }
  fs.writeFileSync(dest, fs.readFileSync(src, 'utf-8'))
})(envPath, '.env', fs)

require('dotenv-safe').load({ allowEmptyValues: true })
if (env === 'development') {
  module.exports = require(`./development.js`)
} else {
  module.exports = require('./production.js')
}


text:
<?php
/**
 * Short description
 *
 * Long Description
 *
 * @license   http://opensource.org/licenses/BSD-3-Clause BSD-3-Clause
 */

namespace Pharc\Project;
use Pharc\Project\Target\Composer;
use Pharc\Project\Target\FileGroup;
use Pharc\Project\Target\StubInterface;
use Pharc\Project\Target\Dependency\DependencyManagerInterface;

/**
 * Class Target
 * @package Pharc\Compiler
 */
class Target
{
    /**
     * @var array
     */
    public static $SIGNATURE_METHODS = [
        'SHA1' => \Phar::SHA1,
        'SHA256' => \Phar::SHA256,
        'SHA512' => \Phar::SHA512,
        'NONE'   => null,
    ];

    /**
     * @var string
     */
    protected $phar;

    /**
     * @var StubInterface
     */
    protected $stub;

    /**
     * @var string
     */
    protected $license;

    /**
     * @var string
     */
    protected $signatureMethod;

    /**
     * @var array
     */
    protected $dependencyManager;

    /**
     * @var mixed
     */
    protected $files;

    /**
     * @var string
     */
    protected $bin;

    /**
     * @return string
     */
    public function getPhar()
    {
        return $this->phar;
    }

    /**
     * @param string $phar
     * @return static
     */
    public function setPhar($phar)
    {
        $this->phar = $phar;
        return $this;
    }

    /**
     * @return StubInterface
     */
    public function getStub()
    {
        return $this->stub;
    }

    /**
     * @param StubInterface $stub
     * @return static
     */
    public function setStub(StubInterface $stub)
    {
        $this->stub = $stub;
        return $this;
    }

    /**
     * @return string
     */
    public function getLicense()
    {
        return $this->license;
    }

    /**
     * @param string $license
     * @return static
     */
    public function setLicense($license)
    {
        $this->license = $license;
        return $this;
    }

    /**
     * @return string
     */
    public function getSignatureMethod()
    {
        return $this->signatureMethod;
    }

    /**
     * @param string $signatureMethod
     * @return static
     */
    public function setSignatureMethod($signatureMethod)
    {
        $this->signatureMethod = $signatureMethod;
        return $this;
    }

    /**
     * @return DependencyManagerInterface
     */
    public function getDependencyManager()
    {
        return $this->dependencyManager;
    }

    /**
     * @param DependencyManagerInterface $dependencyManager
     * @return static
     */
    public function setDependencyManager(DependencyManagerInterface $dependencyManager)
    {
        $this->dependencyManager = $dependencyManager;
        return $this;
    }

    /**
     * @return FileGroup[]
     */
    public function getFileGroups()
    {
        return $this->files;
    }

    /**
     * @param FileGroup[] $files
     * @return static
     */
    public function setFileGroups(array $files)
    {
        $this->files = $files;
        return $this;
    }

    /**
     * @param $name
     * @param FileGroup $files
     */
    public function addFiles($name, FileGroup $files)
    {
        $this->files[$name] = $files;
    }

    /**
     * @return string
     */
    public function getBin()
    {
        return $this->bin;
    }

    /**
     * @param string $bin
     * @return static
     */
    public function setBin($bin)
    {
        $this->bin = $bin;
        return $this;
    }
}


text:
"""
Test cases format for time space networks and jointed dispatch of time and space networks
"""

F_BUS = 0
T_BUS = 1
TIME = 2

BUS_ID = 0
D = 1
LOCATION = 2


text:
// DataMonitorDlg.cpp : implementation file
//

#include "stdafx.h"
#include "Modbus Poll.h"
#include "DataMonitorDlg.h"
#include "afxdialogex.h"

// CDataMonitorDlg dialog

IMPLEMENT_DYNAMIC(CDataMonitorDlg, CDialogEx)

CDataMonitorDlg::CDataMonitorDlg(CWnd* pParent /*=NULL*/)
	: CDialogEx(CDataMonitorDlg::IDD, pParent)
{

}

CDataMonitorDlg::~CDataMonitorDlg()
{
}

void CDataMonitorDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialogEx::DoDataExchange(pDX);
}

BEGIN_MESSAGE_MAP(CDataMonitorDlg, CDialogEx)
END_MESSAGE_MAP()

// CDataMonitorDlg message handlers


text:
package org.apache.commons.ognl.internal.entry;

/*
 * $Id$
 */

import org.apache.commons.ognl.internal.CacheException;

import java.lang.reflect.Array;
import java.lang.reflect.GenericArrayType;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;

public class GenericMethodParameterTypeFactory
    implements CacheEntryFactory<GenericMethodParameterTypeCacheEntry, Class<?>[]>
{
    public Class<?>[] create( GenericMethodParameterTypeCacheEntry entry )
        throws CacheException
    {
        Class<?>[] types;

        ParameterizedType param = (ParameterizedType) entry.type.getGenericSuperclass();
        Type[] genTypes = entry.method.getGenericParameterTypes();
        TypeVariable<?>[] declaredTypes = entry.method.getDeclaringClass().getTypeParameters();

        types = new Class[genTypes.length];

        for ( int i = 0; i < genTypes.length; i++ )
        {
            TypeVariable<?> paramType = null;

            if ( TypeVariable.class.isInstance( genTypes[i] ) )
            {
                paramType = (TypeVariable<?>) genTypes[i];
            }
            else if ( GenericArrayType.class.isInstance( genTypes[i] ) )
            {
                paramType = (TypeVariable<?>) ( (GenericArrayType) genTypes[i] ).getGenericComponentType();
            }
            else if ( ParameterizedType.class.isInstance( genTypes[i] ) )
            {
                types[i] = (Class<?>) ( (ParameterizedType) genTypes[i] ).getRawType();
                continue;
            }
            else if ( Class.class.isInstance( genTypes[i] ) )
            {
                types[i] = (Class<?>) genTypes[i];
                continue;
            }

            Class<?> resolved = resolveType( param, paramType, declaredTypes );

            if ( resolved != null )
            {
                if ( GenericArrayType.class.isInstance( genTypes[i] ) )
                {
                    resolved = Array.newInstance( resolved, 0 ).getClass();
                }

                types[i] = resolved;
                continue;
            }
            types[i] = entry.method.getParameterTypes()[i];
        }

        return types;
    }

    private Class<?> resolveType( ParameterizedType param, TypeVariable<?> var, TypeVariable<?>[] declaredTypes )
    {
        if ( param.getActualTypeArguments().length < 1 )
        {
            return null;
        }

        for ( int i = 0; i < declaredTypes.length; i++ )
        {
            if ( !TypeVariable.class.isInstance( param.getActualTypeArguments()[i] )
                && declaredTypes[i].getName().equals( var.getName() ) )
            {
                return (Class<?>) param.getActualTypeArguments()[i];
            }
        }

        return null;
    }
}


text:
package com.yahoo.pulsar.websocket.service;

import static com.google.common.base.Preconditions.checkArgument;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.yahoo.pulsar.broker.ServiceConfiguration;
import com.yahoo.pulsar.broker.ServiceConfigurationLoader;
import com.yahoo.pulsar.websocket.WebSocketConsumerServlet;
import com.yahoo.pulsar.websocket.WebSocketProducerServlet;
import com.yahoo.pulsar.websocket.WebSocketService;

public class WebSocketServiceStarter {
    public static void main(String args[]) throws Exception {
        checkArgument(args.length == 1, "Need to specify a configuration file");

        try {
            // load config file and start proxy service
            String configFile = args[0];
            log.info("Loading configuration from {}", configFile);
            ServiceConfiguration config = ServiceConfigurationLoader.create(configFile);
            ProxyServer proxyServer = new ProxyServer(config);

            WebSocketService service = new WebSocketService(config);

            proxyServer.addWebSocketServlet(WebSocketProducerServlet.SERVLET_PATH,
                    new WebSocketProducerServlet(service));
            proxyServer.addWebSocketServlet(WebSocketConsumerServlet.SERVLET_PATH,
                    new WebSocketConsumerServlet(service));

            proxyServer.start();

            service.start();
        } catch (Exception e) {
            log.error("Failed to start WebSocket service", e);
            Runtime.getRuntime().halt(1);
        }
    }

    private static final Logger log = LoggerFactory.getLogger(WebSocketServiceStarter.class);

}


text:
<?php

namespace Afpa\ChessGameBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * User
 *
 * @ORM\Table()
 * @ORM\Entity
 */
class User {

    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @var string
     *
     * @ORM\Column(name="nickname", type="string", length=255)
     */
    protected $nickname;

    /**
     * @var string
     *
     * @ORM\Column(name="email", type="string", length=255)
     */
    protected $email;

    /**
     * @ORM\ManyToOne(targetEntity="Game", inversedBy="user")
     * @ORM\JoinColumn(name="game_id", referencedColumnName="id")
     */
    protected $game;

    /**
     * @var string
     *
     * @ORM\Column(name="password", type="string", length=255)
     */
    protected $password;

    /**
     * Get id
     *
     * @return integer
     */
    public function getId() {
        return $this->id;
    }

    /**
     * Set nickname
     *
     * @param string $nickname
     * @return User
     */
    public function setNickname($nickname) {
        $this->nickname = $nickname;

        return $this;
    }

    /**
     * Get nickname
     *
     * @return string
     */
    public function getNickname() {
        return $this->nickname;
    }

    /**
     * Set email
     *
     * @param string $email
     * @return User
     */
    public function setEmail($email) {
        $this->email = $email;

        return $this;
    }

    /**
     * Get email
     *
     * @return string
     */
    public function getEmail() {
        return $this->email;
    }

    /**
     * Set password
     *
     * @param string $password
     * @return User
     */
    public function setPassword($password) {
        $this->password = $password;

        return $this;
    }

    /**
     * Get password
     *
     * @return string
     */
    public function getPassword() {
        return $this->password;
    }

    public function verifAuth($password) {
        return ($this->password == $password);
    }

    /**
     * Constructor
     */
    public function __construct() {
        $this->games = new \Doctrine\Common\Collections\ArrayCollection();
    }

    /**
     * Add games
     *
     * @param \Afpa\ChessGameBundle\Entity\Game $games
     * @return User
     */
    public function addGame(\Afpa\ChessGameBundle\Entity\Game $games) {
        $this->games[] = $games;

        return $this;
    }

    /**
     * Remove games
     *
     * @param \Afpa\ChessGameBundle\Entity\Game $games
     */
    public function removeGame(\Afpa\ChessGameBundle\Entity\Game $games) {
        $this->games->removeElement($games);
    }

    /**
     * Get games
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getGames() {
        return $this->games;
    }

    /**
     * Set game
     *
     * @param \Afpa\ChessGameBundle\Entity\Game $game
     * @return User
     */
    public function setGame(\Afpa\ChessGameBundle\Entity\Game $game = null) {
        $this->game = $game;

        return $this;
    }

    /**
     * Get game
     *
     * @return \Afpa\ChessGameBundle\Entity\Game
     */
    public function getGame() {
        return $this->game;
    }

}


text:
"""
    Please consult file tutorial.html under the doc directory
    for an introduction on how to use this class.
"""

import sys
import config
from PTools import PToolsError, PythonCycError
if 'IPython' in sys.modules:
    from IPython.display import display, HTML

def convertLispIdtoPythonId(s):
    """
     Convert string s such that it can be a valid Python identifier.
    """
    return s.replace('-','_').replace('.','_').replace('?','_p').replace('|','').lower()

class Symbol():
    """
    This class can be used to represent Lisp symbols in PythonCyc.
    For example, Symbol('trp') represents the symbol trp. It is mainly used
    to ensure that some arguments of methods are interpreted as symbols and not
    as strings during the translation to send a request to Pathway Tools.
    """
    def __init__(self, name):
        self._name = name
        return None

class PFrame():
    """
    PFrame is a class to represent Pathway Tools' frames. A PFrame can
    represent a class frame (e.g., Reactions) as well as an instance frame
    (e.g., RXN-9000).

    The required parameters to create a PFrame are the frame id (a string) and a PGDB
    object. For example, assuming that 'meta' is bound to a PGDB object, the following
    create a PFrame to represent the reaction RXN-9000,

        PFrame('RXN-9000', meta)

    By default, an instance PFrame (not a class PFrame) is created.
    To create a PGDB object, use class PGDB, or call method pythoncyc.so.

    IPython
    -------

    A few methods were written to display frames using HTML in IPython.
    Naturally, this functionality is only defined when using IPython as a
    Python interpreter.

    Please consult file tutorial.html under the doc directory for an introduction
    on how to use this class.

    """

    def __init__(self, frameid, pgdb, getFrameData=False, isClass = False):
        """
        The PFrame is created assuming that the frameid is coercible to a frame in the PGDB.
        In particular, the frameid string is not converted and must have the appropriate camel case.
        Creation of a PFrame is done lazily when getFrameData is False but is retrieved
        now when getFrameData is True.
        """
        # Always store the frameid surrounded by vertical bars.
        self.__dict__['frameid'] =  frameid if (frameid.startswith('|') and frameid.endswith('|')) else '|'+frameid+'|'
        self._isclass = isClass
        if isClass:
           self.__dict__['instances'] = []
        # The complete frame (the slot values) is not created by default.
        self._gotframe = False
        # This is the PGDB object, not the PGDB name.
        self.__dict__['pgdb'] = pgdb
        # Add this frame on the list of current frames for this pgdb.
        pgdb.__dict__['_frames'][convertLispIdtoPythonId(frameid)] = self
        # Retrieve the whole frame from Pathway Tools if requested.
        # TBD: add the frame on the list of instances for the corresponding class.
        if getFrameData:
            self.get_frame_data()
        return None

    # The following four definitions are for the pickle (or cPickle) module.
    # TBD: this is work in progress.
    def __getinitargs__(self):
        return (self.frameid, self.pgdb)

    def __getstate__(self):
        # Use a compact representation of a PFrame.
        return self.vectorize_dict()

    def __setstate__(self, values):
        # TBD: Use schema of this PFrame to recreate dictionary.
        self.__dict__ = dict

    def vectorize_dict(self):
        self.__dict__.values()

    # End of definitions for pickle.

    def __getslice__(self, i, j, stride = None):
        if config._debug:
            print 'PFrame __getslice__ ', i, j, stride
        return self.instances[i:j:stride]

    def __getattr__(self, attr):
        # Accessing a slot of the frame using attribute syntax (e.g. r.left)
        if config._debug:
            print 'PFrame __getattr__ ', attr

        if attr in self.__dict__:
            return self.__dict__[attr]
        else:
            attrId = convertLispIdtoPythonId(attr)
            if attrId in self.__dict__:
                return self.__dict__[attrId]

        if self._gotframe:
                return None
                # raise PythonCycError('No slot with name %s exists for frame %s.' % (attr, self.frameid))
        else:
            # Get the slot value from Pathway Tools.
            self.get_frame_slot_value(attr)
            if not (attrId in self.__dict__):
                return None
                # raise PythonCycError('No slot with name %s exists for frame %s.' % (attr, self.frameid))
            else:
                return self.__dict__[attrId]

    def __getitem__(self,attr):
        if config._debug:
           print "PFrame __getitem__ ", attr
        # The slice case is for attr = slice(i,j,s)
        if (isinstance(attr,int) or isinstance(attr, slice)):
           if 'instances' in self.__dict__:
              return self.instances[attr]
           else:
              raise PythonCycError('Indexing cannot be applied because this is a PFrame which is not a vector and this PFrame has no instances attribute.')

        if attr in self.__dict__:
            return self.__dict__[attr]
        else:
            attrId = convertLispIdtoPythonId(attr)
            if attrId in self.__dict__:
                return self.__dict__[attrId]
            else:
                return self.__getattr__(attr)

    def __dir__(self):
        return (dir(self.__class__) + self.__dict__.keys())

    def get_frame_slot_value(self, slot):
        """
        Retrieve the slot data for frame from Pathway Tools.

        Return
           the self PFrame, modified with the new slot with data.
        """
        # FrameObject is a dictionary of slot names and values.
        [slotName, value] = self.pgdb.sendPgdbFnCall('get-frame-slot-value', self.frameid, Symbol(slot))
        if not slotName:
            raise PythonCycError("Slot "+slot+" does not exist for frame "+self.frameid+" from organism (orgid) "+self.pgdb._orgid)
        # Modify slot name to allow Python's syntax (e.g., '_' instead of '-').
        self.__dict__[convertLispIdtoPythonId(slotName)] = value
        return self

    def get_frame_data(self):
        """
        Retrieve the frame data from Pathway Tools, that is, all slots and their values
        for this PFrame are retrieved and stored locally. For a class, the instances
        are not retrieved by this method. Instead, use method get_class_data applied to a PGDB
        object.

        Return
           the self PFrame, modified with the new slots and data.
        """
        # FrameObject is a dictionary of slot names and values.
        frameObject = self.pgdb.sendPgdbFnCall('get-frame-object', self.frameid)
        if not frameObject:
            raise PythonCycError("Could not retrieve frame "+self.frameid+" from organism (orgid) "+self.pgdb._orgid)
        else:
            self._gotframe = True
            # Modify slot names to allow Python's syntax (e.g., '_' instead of '-').
            for slot in frameObject:
                self.__dict__[convertLispIdtoPythonId(slot)] = frameObject[slot]
        return self

    def __setattr__(self, attr, val):
        if not attr.startswith('_'):
           raise PythonCycError("PFrames are read only objects. Attributes of PFrame objects cannot be modified "+str((self.frameid,attr,val))+". You can only modify slot frames for the PGDB in the running Pathway Tools by using methods put_slot_value or put_slot_values using a PGDB object.")
        self.__dict__[attr] = val
        return None

    def __setitem__(self, attr, val):
        if not attr.startswith('_'):
            raise PythonCycError("PFrames are read only objects. Attributes of PFrame objects cannot be modified "+str((self.frameid,attr,val))+". You can only modify slot frames for the PGDB in the running Pathway Tools by using methods put_slot_value or put_slot_values using a PGDB object.")
        self.__dict__[attr] = val
        return None

    def __str__(self):
        if self._isclass:
            return '<PFrame class ' + self.frameid+' currently with '+str(len(self.instances))+' instances ('+self.pgdb._orgid+')>'
        else:
            return '<PFrame instance ' + self.frameid+' ('+self.pgdb._orgid+')>'

    def __repr__(self):
        if self._isclass:
           return self.__str__()
        else:
           return str(self.__dict__)

    if 'IPython' in sys.modules:
        def _ipython_display_(self):
          table = ''
          if not self._isclass:
              for attr in sorted(self.__dict__):
                  if not (attr.startswith('_')):
                     table = table+"
"+str(attr)+"	"+str(self.__dict__[attr])+"
"
          else:
              table = table+'
Class '+self.frameid+' has '+str(self._nb_pframes())+' instances
'
          if table == '':
             table = '
' + self.__str__() + '
'
          table = '
'+ table + '
'
          display(HTML(table))

    def _nb_pframes(self):
        return len(self.instances)

    def __eq__(self, frame):
        # If the given frame is a string, it is assumed to be a frameid.
        if isinstance(frame, str):
            return self.frameid == frame
        # Otherwise it could be a Frame.
        elif isinstance(frame, PFrame):
            # TBD: should we consider the name of the pgdb?
            return (self.pgdb == frame.pgdb) and (self.frameid == frame.frameid)
        # Otherwise it cannot be equal to this object.
        else: return False

    def __ne__(self, frame):
        return not self.__eq__(frame)