text:
import json
import logging
import random
import string
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any, Dict, List, NewType, Optional, Union
from uuid import UUID, uuid5

import boto3

from dataclasses_jsonschema import FieldEncoder, JsonSchemaMixin
from taskcat._cfn.template import Template
from taskcat._client_factory import Boto3Cache
from taskcat._common_utils import merge_nested_dict
from taskcat.exceptions import TaskCatException

LOG = logging.getLogger(__name__)

# property descriptions

METADATA = {
    "project__name": {
        "description": "Project name, used as s3 key prefix when " "uploading objects"
    },
    "auth": {"description": "AWS authentication section"},
    "project__owner": {
        "description": "email address for project owner (not used at present)"
    },
    "regions": {"description": "List of AWS regions"},
    "az_ids": {
        "description": "List of Availablilty Zones ID's to exclude when generating "
        "availability zones"
    },
    "package_lambda": {
        "description": "Package Lambda functions into zips before uploading to s3, "
        "set to false to disable"
    },
    "s3_regional_buckets": {"description": "Enable regional auto-buckets."},
    "lambda_zip_path": {
        "description": "Path relative to the project root to place Lambda zip "
        "files, default is 'lambda_functions/zips'"
    },
    "lambda_source_path": {
        "description": "Path relative to the project root containing Lambda zip "
        "files, default is 'lambda_functions/source'"
    },
    "s3_bucket": {
        "description": "Name of S3 bucket to upload project to, if left out "
        "a bucket will be auto-generated"
    },
    "parameters": {
        "description": "Parameter key-values to pass to CloudFormation, "
        "parameters provided in global config take precedence"
    },
    "build_submodules": {
        "description": "Build Lambda zips recursively for submodules, "
        "set to false to disable"
    },
    "template": {
        "description": "path to template file relative to the project "
        "config file path"
    },
    "tags": {"description": "Tags to apply to CloudFormation template"},
    "enable_sig_v2": {
        "description": "Enable (deprecated) sigv2 access to auto-generated buckets"
    },
    "s3_object_acl": {
        "description": "ACL for uploaded s3 objects, defaults to 'private'"
    },
    "shorten_stack_name": {
        "description": "Shorten stack names generated for tests, set to true to enable"
    },
    "role_name": {"description": "Role name to use when launching CFN Stacks."},
}

# types

ParameterKey = NewType("ParameterKey", str)
ParameterValue = Union[str, int, bool, List[Union[int, str]]]
TagKey = NewType("TagKey", str)
TagValue = NewType("TagValue", str)
S3Acl = NewType("S3Acl", str)
Region = NewType("Region", str)
AlNumDash = NewType("AlNumDash", str)
ProjectName = NewType("ProjectName", AlNumDash)
S3BucketName = NewType("S3BucketName", AlNumDash)
TestName = NewType("TestName", AlNumDash)
AzId = NewType("AzId", str)
Templates = NewType("Templates", Dict[TestName, Template])
# regex validation

class ParameterKeyField(FieldEncoder):
    @property
    def json_schema(self):
        return {
            "type": "string",
            "pattern": r"[a-zA-Z0-9]*^$",
            "Description": "CloudFormation parameter name, can contain letters and "
            "numbers only",
        }

JsonSchemaMixin.register_field_encoders({ParameterKey: ParameterKeyField()})

class RegionField(FieldEncoder):
    @property
    def json_schema(self):
        return {
            "type": "string",
            "pattern": r"^(ap|eu|us|sa|ca|cn|af|me|us-gov)-(central|south|north|east|"
            r"west|southeast|southwest|northeast|northwest)-[0-9]$",
            "description": "AWS Region name eg.: 'us-east-1'",
        }

JsonSchemaMixin.register_field_encoders({Region: RegionField()})

class S3AclField(FieldEncoder):
    @property
    def json_schema(self):
        return {
            "type": "string",
            "pattern": r"^("
            r"bucket-owner-full-control|"
            r"bucket-owner-read|"
            r"authenticated-read|"
            r"aws-exec-read|"
            r"public-read-write|"
            r"public-read|"
            r"private)$",
            "description": "Must be a valid S3 ACL (private, public-read, "
            "aws-exec-read, public-read-write, authenticated-read, "
            "bucket-owner-read, bucket-owner-full-control)",
        }

JsonSchemaMixin.register_field_encoders({S3Acl: S3AclField()})

class AlNumDashField(FieldEncoder):
    @property
    def json_schema(self):
        return {
            "type": "string",
            "pattern": r"^[a-z0-9-]*$",
            "description": "accepts lower case letters, numbers and -",
        }

JsonSchemaMixin.register_field_encoders({AlNumDash: AlNumDashField()})

class AzIdField(FieldEncoder):
    @property
    def json_schema(self):
        return {
            "type": "string",
            "pattern": r"^((ap|eu|us|sa|ca|cn|af|me)(n|s|e|w|c|ne|se|nw|sw)"
            r"[0-9]-az[0-9]|usw2-lax1-az(1|2))$",
            "description": "Availability Zone ID, eg.: 'use1-az1'",
        }

JsonSchemaMixin.register_field_encoders({AzId: AzIdField()})

# dataclasses
@dataclass
class RegionObj:
    name: str
    account_id: str
    partition: str
    profile: str
    taskcat_id: UUID
    _boto3_cache: Boto3Cache
    _role_name: Optional[str]

    def client(self, service: str):
        return self._boto3_cache.client(service, region=self.name, profile=self.profile)

    @property
    def session(self):
        return self._boto3_cache.session(region=self.name, profile=self.profile)

    @property
    def role_arn(self):
        if self._role_name:
            return f"arn:{self.partition}:iam::{self.account_id}:role/{self._role_name}"
        return None

@dataclass
class S3BucketObj:
    name: str
    region: str
    account_id: str
    partition: str
    s3_client: boto3.client
    sigv4: bool
    auto_generated: bool
    regional_buckets: bool
    object_acl: str
    taskcat_id: UUID

    @property
    def sigv4_policy(self):
        policy = {
            "Version": "2012-10-17",
            "Statement": [
                {
                    "Sid": "Test",
                    "Effect": "Deny",
                    "Principal": "*",
                    "Action": "s3:*",
                    "Resource": f"arn:{self.partition}:s3:::{self.name}/*",
                    "Condition": {"StringEquals": {"s3:signatureversion": "AWS"}},
                }
            ],
        }
        return json.dumps(policy)

    def create(self):
        if self._bucket_matches_existing():
            return
        kwargs = {"Bucket": self.name}
        if self.region != "us-east-1":
            kwargs["CreateBucketConfiguration"] = {"LocationConstraint": self.region}

        self.s3_client.create_bucket(**kwargs)
        error = None
        try:
            self.s3_client.get_waiter("bucket_exists").wait(Bucket=self.name)

            if not self.regional_buckets:
                self.s3_client.put_bucket_tagging(
                    Bucket=self.name,
                    Tagging={
                        "TagSet": [{"Key": "taskcat-id", "Value": self.taskcat_id.hex}]
                    },
                )
            if self.sigv4:
                self.s3_client.put_bucket_policy(
                    Bucket=self.name, Policy=self.sigv4_policy
                )
        except Exception as e:  # pylint: disable=broad-except
            error = e
            try:
                self.s3_client.delete_bucket(Bucket=self.name)
            except Exception as inner_e:  # pylint: disable=broad-except
                LOG.warning(f"failed to remove bucket {self.name}: {inner_e}")
        if error:
            raise error

    def empty(self):
        if not self.auto_generated:
            LOG.error(f"Will not empty bucket created outside of taskcat {self.name}")
            return
        objects_to_delete = []
        pages = self.s3_client.get_paginator("list_objects_v2").paginate(
            Bucket=self.name
        )
        for page in pages:
            objects = []
            for obj in page.get("Contents", []):
                del_obj = {"Key": obj["Key"]}
                if obj.get("VersionId"):
                    del_obj["VersionId"] = obj["VersionId"]
                objects.append(del_obj)
            objects_to_delete += objects
        batched_objects = [
            objects_to_delete[i : i + 1000]
            for i in range(0, len(objects_to_delete), 1000)
        ]
        for objects in batched_objects:
            if objects:
                self.s3_client.delete_objects(
                    Bucket=self.name, Delete={"Objects": objects}
                )

    def delete(self, delete_objects=False):
        if not self.auto_generated:
            LOG.info(f"Will not delete bucket created outside of taskcat {self.name}")
            return
        if delete_objects:
            try:
                self.empty()
            except self.s3_client.exceptions.NoSuchBucket:
                LOG.info(f"Cannot delete bucket {self.name} as it does not exist")
                return
        try:
            self.s3_client.delete_bucket(Bucket=self.name)
        except self.s3_client.exceptions.NoSuchBucket:
            LOG.info(f"Cannot delete bucket {self.name} as it does not exist")

    def _bucket_matches_existing(self):
        try:
            location = self.s3_client.get_bucket_location(Bucket=self.name)[
                "LocationConstraint"
            ]
            location = location if location else "us-east-1"
        except self.s3_client.exceptions.NoSuchBucket:
            location = None
        if location != self.region and location is not None:
            raise TaskCatException(
                f"bucket {self.name} already exists, but is not in "
                f"the expected region {self.region}, expected {location}"
            )
        if location:
            if self.regional_buckets:
                return True
            tags = self.s3_client.get_bucket_tagging(Bucket=self.name)["TagSet"]
            tags = {t["Key"]: t["Value"] for t in tags}
            uid = tags.get("taskcat-id")
            uid = UUID(uid) if uid else uid
            if uid != self.taskcat_id:
                raise TaskCatException(
                    f"bucket {self.name} already exists, but does not have a matching"
                    f" uuid"
                )
            return True
        return False

class Tag:
    def __init__(self, tag_dict: dict):
        if isinstance(tag_dict, Tag):
            tag_dict = {"Key": tag_dict.key, "Value": tag_dict.value}
        self.key: str = tag_dict["Key"]
        self.value: str = tag_dict["Value"]

    def dump(self):
        tag_dict = {"Key": self.key, "Value": self.value}
        return tag_dict

@dataclass
class TestRegion(RegionObj):
    s3_bucket: S3BucketObj
    parameters: Dict[ParameterKey, ParameterValue]

    @classmethod
    def from_region_obj(cls, region: RegionObj, s3_bucket, parameters):
        return cls(s3_bucket=s3_bucket, parameters=parameters, **region.__dict__)

@dataclass
# pylint: disable=too-many-instance-attributes
class TestObj:
    def __init__(
        self,
        template_path: Path,
        template: Template,
        project_root: Path,
        name: TestName,
        regions: List[TestRegion],
        tags: List[Tag],
        uid: UUID,
        _project_name: str,
        _stack_name: str = "",
        _stack_name_prefix: str = "",
        _stack_name_suffix: str = "",
        _shorten_stack_name: bool = False,
    ):
        self.template_path = template_path
        self.template = template
        self.project_root = project_root
        self.name = name
        self.regions = regions
        self.tags = tags
        self.uid = uid
        self._project_name = _project_name
        self._stack_name = _stack_name
        self._stack_name_prefix = _stack_name_prefix
        self._stack_name_suffix = _stack_name_suffix
        self._shorten_stack_name = _shorten_stack_name
        self._assert_param_combo()

    def _assert_param_combo(self):
        throw = False
        if self._stack_name_prefix and self._stack_name_suffix:
            throw = True
        if self._stack_name and (self._stack_name_prefix or self._stack_name_suffix):
            throw = True
        if throw:
            raise TaskCatException(
                "Please provide only *ONE* of stack_name, stack_name_prefix, \
                or stack_name_suffix"
            )

    @property
    def stack_name(self):
        prefix = "tCaT-"
        if self._stack_name:
            return self._stack_name
        # TODO: prefix *OR* suffix
        if self._stack_name_prefix:
            if self._shorten_stack_name:
                return "{}{}-{}".format(
                    self._stack_name_prefix, self.name, self.uid.hex[:6]
                )
            return "{}{}-{}-{}".format(
                self._stack_name_prefix, self._project_name, self.name, self.uid.hex
            )
        if self._stack_name_suffix:
            return "{}{}-{}-{}".format(
                prefix, self._project_name, self.name, self._stack_name_suffix
            )
        if self._shorten_stack_name:
            return "{}{}-{}".format(prefix, self.name, self.uid.hex[:6])
        return "{}{}-{}-{}".format(prefix, self._project_name, self.name, self.uid.hex)

@dataclass
class GeneralConfig(JsonSchemaMixin, allow_additional_props=False):  # type: ignore
    """General configuration settings."""

    parameters: Optional[Dict[ParameterKey, ParameterValue]] = field(
        default=None, metadata=METADATA["parameters"]
    )
    tags: Optional[Dict[TagKey, TagValue]] = field(
        default=None, metadata=METADATA["tags"]
    )
    auth: Optional[Dict[Region, str]] = field(default=None, metadata=METADATA["auth"])
    s3_bucket: Optional[str] = field(default=None, metadata=METADATA["s3_bucket"])
    s3_regional_buckets: Optional[bool] = field(
        default=None, metadata=METADATA["s3_regional_buckets"]
    )

@dataclass
class TestConfig(JsonSchemaMixin, allow_additional_props=False):  # type: ignore
    """Test specific configuration section."""

    template: Optional[str] = field(default=None, metadata=METADATA["template"])
    parameters: Dict[ParameterKey, ParameterValue] = field(
        default_factory=dict, metadata=METADATA["parameters"]
    )
    regions: Optional[List[Region]] = field(default=None, metadata=METADATA["regions"])
    tags: Optional[Dict[TagKey, TagValue]] = field(
        default=None, metadata=METADATA["tags"]
    )
    auth: Optional[Dict[Region, str]] = field(default=None, metadata=METADATA["auth"])
    s3_bucket: Optional[S3BucketName] = field(
        default=None, metadata=METADATA["s3_bucket"]
    )
    s3_regional_buckets: Optional[bool] = field(
        default=None, metadata=METADATA["s3_regional_buckets"]
    )
    az_blacklist: Optional[List[AzId]] = field(
        default=None, metadata=METADATA["az_ids"]
    )
    role_name: Optional[str] = field(default=None, metadata=METADATA["role_name"])

# pylint: disable=too-many-instance-attributes
@dataclass
class ProjectConfig(JsonSchemaMixin, allow_additional_props=False):  # type: ignore
    """Project specific configuration section"""

    name: Optional[ProjectName] = field(
        default=None, metadata=METADATA["project__name"]
    )
    auth: Optional[Dict[Region, str]] = field(default=None, metadata=METADATA["auth"])
    owner: Optional[str] = field(default=None, metadata=METADATA["project__owner"])
    regions: Optional[List[Region]] = field(default=None, metadata=METADATA["regions"])
    az_blacklist: Optional[List[AzId]] = field(
        default=None, metadata=METADATA["az_ids"]
    )
    package_lambda: Optional[bool] = field(
        default=None, metadata=METADATA["package_lambda"]
    )
    lambda_zip_path: Optional[str] = field(
        default=None, metadata=METADATA["lambda_zip_path"]
    )
    lambda_source_path: Optional[str] = field(
        default=None, metadata=METADATA["lambda_source_path"]
    )
    s3_bucket: Optional[S3BucketName] = field(
        default=None, metadata=METADATA["s3_bucket"]
    )
    s3_regional_buckets: Optional[bool] = field(
        default=None, metadata=METADATA["s3_regional_buckets"]
    )
    parameters: Optional[Dict[ParameterKey, ParameterValue]] = field(
        default=None, metadata=METADATA["parameters"]
    )
    build_submodules: Optional[bool] = field(
        default=None, metadata=METADATA["build_submodules"]
    )
    template: Optional[str] = field(default=None, metadata=METADATA["template"])
    tags: Optional[Dict[TagKey, TagValue]] = field(
        default=None, metadata=METADATA["tags"]
    )
    s3_enable_sig_v2: Optional[bool] = field(
        default=None, metadata=METADATA["enable_sig_v2"]
    )
    s3_object_acl: Optional[S3Acl] = field(
        default=None, metadata=METADATA["s3_object_acl"]
    )
    shorten_stack_name: Optional[bool] = field(
        default=None, metadata=METADATA["shorten_stack_name"]
    )
    role_name: Optional[str] = field(default=None, metadata=METADATA["role_name"])

PROPAGATE_KEYS = ["tags", "parameters", "auth"]
PROPOGATE_ITEMS = [
    "regions",
    "s3_bucket",
    "template",
    "az_blacklist",
    "s3_regional_buckets",
]

def generate_regional_bucket_name(region_obj: RegionObj, prefix: str = "tcat"):
    if len(prefix) > 8 or len(prefix) < 1:  # pylint: disable=len-as-condition
        raise TaskCatException("prefix must be between 1 and 8 characters long")
    hashed_account_id = uuid5(
        name=str(region_obj.account_id), namespace=UUID(int=0)
    ).hex
    return f"{prefix}-{hashed_account_id}-{region_obj.name}"

def generate_bucket_name(project: str, prefix: str = "tcat"):
    if len(prefix) > 8 or len(prefix) < 1:  # pylint: disable=len-as-condition
        raise TaskCatException("prefix must be between 1 and 8 characters long")
    alnum = string.ascii_lowercase + string.digits
    suffix = "".join(random.choice(alnum) for i in range(8))  # nosec: B311
    mid = f"-{project}-"
    avail_len = 63 - len(mid)
    mid = mid[:avail_len]
    return f"{prefix}{mid}{suffix}"

# pylint raises false positive due to json-dataclass
# pylint: disable=no-member
@dataclass
class BaseConfig(JsonSchemaMixin, allow_additional_props=False):  # type: ignore
    """Taskcat configuration file"""

    general: GeneralConfig = field(default_factory=GeneralConfig)
    project: ProjectConfig = field(default_factory=ProjectConfig)
    tests: Dict[TestName, TestConfig] = field(default_factory=dict)

    # pylint doesn't like instance variables being added in post_init
    # pylint: disable=attribute-defined-outside-init
    def __post_init__(self):
        self._source: Dict[str, Any] = {}
        self._propogate()
        self.set_source("UNKNOWN")
        self._propogate_source()

    @staticmethod
    def _merge(source, dest):
        for section_key, section_value in source.items():
            if section_key in PROPAGATE_KEYS + PROPOGATE_ITEMS:
                if section_key not in dest:
                    dest[section_key] = section_value
                    continue
                if section_key in PROPAGATE_KEYS:
                    for key, value in section_value.items():
                        dest[section_key][key] = value
        return dest

    def _propogate(self):
        project_dict = self._merge(self.general.to_dict(), self.project.to_dict())
        self.project = ProjectConfig.from_dict(project_dict)
        for test_key, test in self.tests.items():
            test_dict = self._merge(self.project.to_dict(), test.to_dict())
            self.tests[test_key] = TestConfig.from_dict(test_dict)

    def _propogate_source(self):
        self._source["project"] = self._merge(
            self._source["general"], self._source["project"]
        )
        for test_key in self._source["tests"]:
            test = self._merge(self._source["project"], self._source["tests"][test_key])
            self._source["tests"][test_key] = test

    def set_source(
        self, source_name: str, dest: Optional[Any] = None
    ) -> Optional[Union[str, dict]]:
        base_case = False
        if dest is None:
            base_case = True
            self._source = self.to_dict()
            dest = self._source
        if not isinstance(dest, dict):
            return source_name
        if isinstance(dest, dict):
            for item in dest:
                dest[item] = self.set_source(source_name, dest[item])
        if not base_case:
            return dest
        return None

    @classmethod
    def merge(
        cls, base_config: "BaseConfig", merge_config: "BaseConfig"
    ) -> "BaseConfig":

        merged = base_config.to_dict()
        merge_nested_dict(merged, merge_config.to_dict())

        merged_source = base_config._source.copy()
        merge_nested_dict(merged_source, merge_config._source)

        config = cls.from_dict(merged)

        config._source = merged_source
        config._propogate_source()  # pylint: disable=protected-access
        return config


text:
var F2BApp = angular.module('F2BApp',[
    'ngRoute'
]);

F2BApp.config(['$routeProvider', function ($routeProvider) {

    $routeProvider
    .when('/', {
        templateUrl: "app/home/home.html",
        controller: "HomeCtrl",
        controllerAs: 'home'
    })
    .when('/config', {
        templateUrl: 'app/config/config.html',
        controller: "ConfigCtrl",
        controllerAs: 'config'
    })
    .when('/banned', {
        templateUrl: 'app/banned/banned.html',
        controller: "BannedCtrl",
        controllerAs: 'banned'
    })
    .otherwise({
        redirectTo: '/'
    });
}]);

redpajama_set_name: RedPajamaGithub


text:
package com.amazonaws.services.simplesystemsmanagement.model;

import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.protocol.StructuredPojo;
import com.amazonaws.protocol.ProtocolMarshaller;

/**
 *

 * A user-defined set of one or more filters on which to aggregate inventory data. Groups return a count of resources
 * that match and don't match the specified criteria.
 *

 *
 * @see AWS API
 *      Documentation
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class InventoryGroup implements Serializable, Cloneable, StructuredPojo {

    /**
     *

     * The name of the group.
     *

     */
    private String name;
    /**
     *

     * Filters define the criteria for the group. The matchingCount field displays the number of resources
     * that match the criteria. The notMatchingCount field displays the number of resources that don't
     * match the criteria.
     *

     */
    private com.amazonaws.internal.SdkInternalList<InventoryFilter> filters;

    /**
     *

     * The name of the group.
     *

     *
     * @param name
     *        The name of the group.
     */

    public void setName(String name) {
        this.name = name;
    }

    /**
     *

     * The name of the group.
     *

     *
     * @return The name of the group.
     */

    public String getName() {
        return this.name;
    }

    /**
     *

     * The name of the group.
     *

     *
     * @param name
     *        The name of the group.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public InventoryGroup withName(String name) {
        setName(name);
        return this;
    }

    /**
     *

     * Filters define the criteria for the group. The matchingCount field displays the number of resources
     * that match the criteria. The notMatchingCount field displays the number of resources that don't
     * match the criteria.
     *

     *
     * @return Filters define the criteria for the group. The matchingCount field displays the number of
     *         resources that match the criteria. The notMatchingCount field displays the number of
     *         resources that don't match the criteria.
     */

    public java.util.List<InventoryFilter> getFilters() {
        if (filters == null) {
            filters = new com.amazonaws.internal.SdkInternalList<InventoryFilter>();
        }
        return filters;
    }

    /**
     *

     * Filters define the criteria for the group. The matchingCount field displays the number of resources
     * that match the criteria. The notMatchingCount field displays the number of resources that don't
     * match the criteria.
     *

     *
     * @param filters
     *        Filters define the criteria for the group. The matchingCount field displays the number of
     *        resources that match the criteria. The notMatchingCount field displays the number of
     *        resources that don't match the criteria.
     */

    public void setFilters(java.util.Collection<InventoryFilter> filters) {
        if (filters == null) {
            this.filters = null;
            return;
        }

        this.filters = new com.amazonaws.internal.SdkInternalList<InventoryFilter>(filters);
    }

    /**
     *

     * Filters define the criteria for the group. The matchingCount field displays the number of resources
     * that match the criteria. The notMatchingCount field displays the number of resources that don't
     * match the criteria.
     *

     *

     * NOTE: This method appends the values to the existing list (if any). Use
     * {@link #setFilters(java.util.Collection)} or {@link #withFilters(java.util.Collection)} if you want to override
     * the existing values.
     *

     *
     * @param filters
     *        Filters define the criteria for the group. The matchingCount field displays the number of
     *        resources that match the criteria. The notMatchingCount field displays the number of
     *        resources that don't match the criteria.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public InventoryGroup withFilters(InventoryFilter... filters) {
        if (this.filters == null) {
            setFilters(new com.amazonaws.internal.SdkInternalList<InventoryFilter>(filters.length));
        }
        for (InventoryFilter ele : filters) {
            this.filters.add(ele);
        }
        return this;
    }

    /**
     *

     * Filters define the criteria for the group. The matchingCount field displays the number of resources
     * that match the criteria. The notMatchingCount field displays the number of resources that don't
     * match the criteria.
     *

     *
     * @param filters
     *        Filters define the criteria for the group. The matchingCount field displays the number of
     *        resources that match the criteria. The notMatchingCount field displays the number of
     *        resources that don't match the criteria.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public InventoryGroup withFilters(java.util.Collection<InventoryFilter> filters) {
        setFilters(filters);
        return this;
    }

    /**
     * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
     * redacted from this string using a placeholder value.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getName() != null)
            sb.append("Name: ").append(getName()).append(",");
        if (getFilters() != null)
            sb.append("Filters: ").append(getFilters());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof InventoryGroup == false)
            return false;
        InventoryGroup other = (InventoryGroup) obj;
        if (other.getName() == null ^ this.getName() == null)
            return false;
        if (other.getName() != null && other.getName().equals(this.getName()) == false)
            return false;
        if (other.getFilters() == null ^ this.getFilters() == null)
            return false;
        if (other.getFilters() != null && other.getFilters().equals(this.getFilters()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getName() == null) ? 0 : getName().hashCode());
        hashCode = prime * hashCode + ((getFilters() == null) ? 0 : getFilters().hashCode());
        return hashCode;
    }

    @Override
    public InventoryGroup clone() {
        try {
            return (InventoryGroup) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
        }
    }

    @com.amazonaws.annotation.SdkInternalApi
    @Override
    public void marshall(ProtocolMarshaller protocolMarshaller) {
        com.amazonaws.services.simplesystemsmanagement.model.transform.InventoryGroupMarshaller.getInstance().marshall(this, protocolMarshaller);
    }
}


text:
sap.ui.define([
	"sap/ui/test/Opa5",
	"sap/ui/test/opaQunit",
	"sap/ui/test/actions/Press",
	"sap/ui/test/actions/EnterText",
	"cp/opa/test/env/integration/actions/SwatchColorPress",
	"cp/opa/test/env/integration/matchers/SwatchColor",
	"sap/ui/core/Core"
], function (Opa5, opaTest, Press, EnterText, SwatchColorPress, SwatchColor, oCore) {
	"use strict";

	var COMPONENT_VIEW_PREFFIX = "__component0---myHomeView--",
		COMPLEX_CONTROLDEFAULTS_COLORPALETTEPOPOVER_OPENER_ID = "open-complex-control-defaults-sample",
		COMPLEX_CONTROLDEFAULTS_COLORPALETTEPOPOVER_ID = "Complex_ControlDefaults-colorPalettePopover-popover",
		COMPLEX_CONTROLDEFAULTS_COLORPALETTEPOPOVER_COLORPICKER_ID = "Complex_ControlDefaults-palette-moreColorsDialog",
		COMPLEX_CONTROLDEFAULTS_COLORPALETTEPOPOVER_COLORPICKER_OKBUTTON_ID = "__button0",
		COMPLEX_CONTROLDEFAULTS_COLORPALETTEPOPOVER_COLORPICKER_SLIDERHANDLE_ID =  "__picker0-hSLD",
		COMPLEX_CONTROLDEFAULTS_COLORPALETTEPOPOVER_COLORPICKER_HEXADECIMALINPUT_ID = "__picker0-hxF";

	var colorSelectEventParamsShouldMatch = function (oExpected) {
		var tryJsonParse = function (sString) {
			try {
				return JSON.parse(sString);
			} catch (e) {
				throw e.message = sString + " was passed to JSON.parse() " + e.message;
			}
		};
		return this.waitFor({
			id: COMPONENT_VIEW_PREFFIX + "colorSelectEventInput",
			success: function (oInput) {
				var vColorSelectEventParameters = oInput.getValue(),
					sExpectedParams = JSON.stringify(oExpected),
					bExpectationMet = !!vColorSelectEventParameters.length;

				if (bExpectationMet) {
					vColorSelectEventParameters = tryJsonParse(vColorSelectEventParameters);
					bExpectationMet = Object.keys(oExpected).every(function (sKey) {
						return vColorSelectEventParameters[sKey] === oExpected[sKey];
					});
				}
				Opa5.assert.ok(bExpectationMet, "colorSelect event was fired with correct parameters\n" + sExpectedParams);
			}
		});
	};

	/* OPA tests Part #1 */

	Opa5.extendConfig({
		autoWait: true,
		viewNamespace: "cp.opa.test.app.views.",
		arrangements: new Opa5({
			iStartMyComponent: function (sComponentName) {
				return this.iStartMyUIComponent({
					componentConfig: {
						name: sComponentName,
						id: "__component0",
						manifest:true
					},
					// testing deep links is possible by setting a hash
					hash: ""
				});
			}
		}),
		actions: new Opa5({
			iOpenComplexControlDefaultsColorPalettePopover: function () {
				return this.waitFor({
					viewName: "Home",
					id: COMPLEX_CONTROLDEFAULTS_COLORPALETTEPOPOVER_OPENER_ID,
					actions: [
						/*
						 * ToDo: Currently, the OPA build-in sap.ui.test.action.Press() action doesn't focus the target before firing the corresponding events (on IE only).
						 * ToDo: Adding an additional action (function) which focuses it works around this problem and should be removed when a fix is provided.
						 */
						function (oElement) {
						if (document.activeElement.id !== oElement.getId()) {
							oElement.focus();
						}
					}, new Press()],
					success: function () {
						Opa5.assert.ok(true, COMPLEX_CONTROLDEFAULTS_COLORPALETTEPOPOVER_OPENER_ID + " opener is successfully activated.");
					},
					errorMessage: COMPLEX_CONTROLDEFAULTS_COLORPALETTEPOPOVER_OPENER_ID + " opener was not found"
				});
			},
			iClickOnATargetId: function (sTargetId) {
				return this.waitFor({
					id: sTargetId,
					actions: [
						/*
						 * ToDo: Currently, the OPA build-in sap.ui.test.action.Press() action doesn't focus the target before firing the corresponding events (on IE only).
						 * ToDo: Adding an additional action (function) which focuses it works around this problem and should be removed when a fix is provided.
						 */
						function (oElement) {
							if (document.activeElement.id !== oElement.getId()) {
								oElement.focus();
							}
						}, function(oElement) {
							oElement.firePress();
						}],
					success: function () {
						Opa5.assert.ok(true, sTargetId + " is clicked successfully");
					},
					errorMessage: "Target with id: " + sTargetId + " was not found"
				});
			},
			iPressKeyOnATargetId: function(sTarget, iKey, bShiftKey, bAltKey, bCtrlKey) {
				return this.waitFor({
					id: sTarget,
					actions: function (oTarget) {
						Opa5.getUtils().triggerKeydown(oTarget.getId(), iKey, bShiftKey, bAltKey, bCtrlKey);
						Opa5.getUtils().triggerKeyup(oTarget.getId(), iKey, bShiftKey, bAltKey, bCtrlKey);
					},
					success: function (oTarget) {
						Opa5.assert.ok(true, "A [keydown] with iKey code " + iKey + " was triggered on " + oTarget.getId());
					},
					errorMessage: "Target with id " + sTarget + " was NOT found."
				});
			},
			iClickOnAColorSwatch: function (sColor) {
				return this.waitFor({
					searchOpenDialogs: true,
					actions: new SwatchColorPress(),
					matchers: new SwatchColor({
						color: sColor
					}),
					success: function () {
						Opa5.assert.ok(true, "Swatch color with value " + sColor + " was clicked");
						this.colorSelectEventParamsShouldMatch({
							defaultAction: false,
							value: sColor
						});
					},
					errorMessage: "ColorPalettePopover opener was not found"
				});
			},
			iPressKeyOnAColorSwatch: function (sColor, iKey) {
				return this.waitFor({
					searchOpenDialogs: true,
					controlType: "sap.m.ColorPalette",
					actions: function (oColor) {
						Opa5.getUtils().triggerKeydown(oColor, iKey);
						Opa5.getUtils().triggerKeyup(oColor, iKey);
					},
					matchers: new SwatchColor({
						color: sColor
					}),
					success: function () {
						Opa5.assert.ok(true, "A keydown with iKey code " + iKey + " was triggered on a " + sColor + " swatch");
					},
					errorMessage: "ColorPalettePopover opener was not found"
				});
			},
			iChangeTheColorPickerColor: function (sColor) {
				return this.waitFor({
					id: COMPLEX_CONTROLDEFAULTS_COLORPALETTEPOPOVER_COLORPICKER_HEXADECIMALINPUT_ID,
					actions: new EnterText({
						text: sColor
					}),
					success: function (oControl) {
						Opa5.assert.ok(true, sColor + " was entered in the hexadecimal input of ColorPalettePopover with id: " + oControl.getId());
					},
					errorMessage: "Element with id " + COMPLEX_CONTROLDEFAULTS_COLORPALETTEPOPOVER_COLORPICKER_HEXADECIMALINPUT_ID + " was not was NOT found"
				});
			},
			iConfirmNewColorSelection: function () {
				return this.waitFor({
					id: COMPLEX_CONTROLDEFAULTS_COLORPALETTEPOPOVER_COLORPICKER_OKBUTTON_ID,
					actions: [
						/*
						 * ToDo: Currently, the OPA build-in sap.ui.test.action.Press() action doesn't focus the target before firing the corresponding events (on IE only).
						 * ToDo: Adding an additional action (function) which focuses it works around this problem and should be removed when a fix is provided.
						 */
						function (oElement) {
							if (document.activeElement.id !== oElement.getId()) {
								oElement.focus();
							}
						}, new Press()],
					success: function () {
						Opa5.assert.ok(true, COMPLEX_CONTROLDEFAULTS_COLORPALETTEPOPOVER_COLORPICKER_OKBUTTON_ID + " was clicked");
					},
					errorMessage: "The 'OK' button of 'ColorPicker' was NOT found"
				});
			},
			//This is a repeated assertion block
			colorSelectEventParamsShouldMatch: colorSelectEventParamsShouldMatch
		}),
		assertions: new Opa5({
			complexControlDefaultsColorPalettePopoverShouldBeOpen: function () {
				var oComplexControlDefaultsColorPalettePopover = null;
				return this.waitFor({
					autoWait: false,
					viewName: "Home",
					check: function () {
						oComplexControlDefaultsColorPalettePopover = oCore.byId(COMPLEX_CONTROLDEFAULTS_COLORPALETTEPOPOVER_ID);
						//ComplexControlDefaultsColorPopoverPalette is rendered in UI area and visible
						return oComplexControlDefaultsColorPalettePopover.$().length === 1 && oComplexControlDefaultsColorPalettePopover.$().is(":visible");
					},
					success: function () {
						Opa5.assert.ok(true, "The ColorPalettePopover is opened");
						this.complexControlDefaultsColorPalettePopoverShouldRenderAllChildControls();
						this.documentActiveElementShouldBe(oComplexControlDefaultsColorPalettePopover.getAggregation("content")[0].getAggregation("_defaultColorButton").getId());
					},
					errorMessage: "ColorPalettePopover was NOT successfully opened."
				});
			},
			complexControlDefaultsColorPalettePopoverColorPickerShouldBeOpen: function () {
				var oComplexControlDefaultsColorPalettePopoverColorPicker = null;
				return this.waitFor({
					autoWait: false,
					viewName: "Home",
					check: function () {
						oComplexControlDefaultsColorPalettePopoverColorPicker = oCore.byId(COMPLEX_CONTROLDEFAULTS_COLORPALETTEPOPOVER_COLORPICKER_ID);
						//ComplexControlDefaultsColorPalettePopoverColorPicker is rendered in UI area and visible
						return oComplexControlDefaultsColorPalettePopoverColorPicker.$().length === 1 && oComplexControlDefaultsColorPalettePopoverColorPicker.$().is(":visible");
					},
					success: function () {
						Opa5.assert.ok(true, "The ColorPicker of the ColorPalettePopover is opened");
						this.complexControlDefaultsColorPalettePopoverShouldRenderAllChildControls();
						this.documentActiveElementShouldBe(COMPLEX_CONTROLDEFAULTS_COLORPALETTEPOPOVER_COLORPICKER_SLIDERHANDLE_ID + "-handle");
					},
					errorMessage: "ColorPalettePopover couldn't open its ColorPicker."
				});
			},
			complexControlDefaultsColorPalettePopoverShouldBeClosedAndFocusShouldBeOn: function (sExpectedIdToBeDocumentActiveElement) {
				var oComplexControlDefaultsColorPalettePopover = null;
				return this.waitFor({
					autoWait: false,
					check: function () {
						oComplexControlDefaultsColorPalettePopover = oCore.byId(COMPLEX_CONTROLDEFAULTS_COLORPALETTEPOPOVER_ID);
						//ComplexControlDefaultsColorPopoverPalette is rendered in UI area and hidden
						return oComplexControlDefaultsColorPalettePopover.$().length === 1 && oComplexControlDefaultsColorPalettePopover.$().is(":hidden");
					},
					success: function () {
						Opa5.assert.ok(true, "The ColorPalettePopover is closed");
						this.documentActiveElementShouldBe(sExpectedIdToBeDocumentActiveElement);
					},
					errorMessage: "ColorPalettePopover was NOT successfully closed."
				});
			},
			firstTwoColorsOfRecentColorsBlockShouldBe: function (aRecentColors){
				return this.waitFor({
					searchOpenDialogs: true,
					controlType: "sap.m.ColorPalette",
					check: function (aElements){
						if (JSON.stringify(aRecentColors) === JSON.stringify(aElements[0]._getRecentColors())){
							return true;
						} else {
							return false;
						}
					},
					success: function () {
						Opa5.assert.ok(true, "ColorPalette Recent colors section contains the right colors");
					},
					errorMessage: "ColorPalette doesn't contains the right colors"
				});
			},
			complexControlDefaultsColorPalettePopoverShouldRenderAllChildControls: function () {
				//Assuming that Complex ControlDefaults ColorPalettePopover is already opened
				return this.waitFor({
					searchOpenDialogs: true,
					controlType: "sap.m.Button",
					success: function (aButtons) {
						var oDefaultButton = aButtons[0],
							oMoreColorsButton = aButtons[1];

						Opa5.assert.ok(oDefaultButton && oMoreColorsButton, "ColorPalettePopover contains 'default color' and 'more colors' buttons");
						Opa5.assert.strictEqual(oDefaultButton.$().length, 1, '"Default Colors" button is rendered');
						Opa5.assert.strictEqual(oMoreColorsButton.$().length, 1, '"More Colors..." button is rendered');
					},
					errorMessage: "ColorPalettePopover opener was not found"
				});
			},
			colorSelectEventParamsShouldMatch: colorSelectEventParamsShouldMatch,
			documentActiveElementShouldBe: function (sTarget) {
				return this.waitFor({
					success: function () {
						Opa5.assert.strictEqual(document.activeElement.id, sTarget, "Element with id: " + sTarget + " was focused");
					},
					errorMessage: "Element with id='" + sTarget + "' was NOT found."
				});
			},
			documentActiveSwatchShouldBe: function (sColorName) {
				return this.waitFor({
					success: function () {
						var oComplexControlDefaultsColorPalettePopover = oCore.byId(COMPLEX_CONTROLDEFAULTS_COLORPALETTEPOPOVER_ID),
							oColor = oComplexControlDefaultsColorPalettePopover.$().find('[data-sap-ui-color="' + sColorName + '"]').get(0);

						Opa5.assert.strictEqual(document.activeElement, oColor, "Swatch with color: " + sColorName + " was focused");
					},
					errorMessage: "Swatch with color='" + sColorName + "' was NOT found."
				});
			}
		})
	});

});


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
	http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context
		http://www.springframework.org/schema/context/spring-context-3.0.xsd">

	<import resource="classpath*:META-INF/spring/docsreporter-context.xml" />

	<bean id="regTemplate" parent="reportTemplateBase">
		<property name="templatePath">
			<value>classpath:templates/registration_template.docx</value>
		</property>
		<property name="modelClass">
			<value>by.creepid.docgeneration.model.FirmReg</value>
		</property>
		<property name="modelName" value="reg" />
	</bean>

	<bean id="regHeaderManager" class="by.creepid.docgeneration.header.DocsHeaderManagerImpl">
		<constructor-arg value="#{regTemplate.templatePath}" />
	</bean>

</beans>


text:
//
//  Copyright (c) SRG SSR. All rights reserved.
//
//  License information is available from the LICENSE file.
//

@import AVFoundation;

NS_ASSUME_NONNULL_BEGIN

@class SRGPlayer;

/**
 *  Player delegate protocol.
 */
@protocol SRGPlayerDelegate <NSObject>

/**
 *  The player begins seeking to the given time.
 */
- (void)player:(SRGPlayer *)player willSeekToTime:(CMTime)time;

/**
 *  The player did finish seeking to the given time.
 *
 *  @discussion Not called if a seek has been interrupted.
 */
- (void)player:(SRGPlayer *)player didSeekToTime:(CMTime)time;

@end

/**
 *  Lightweight `AVPlayer` subclass tracking seek events and reporting them to its delegate.
 */
@interface SRGPlayer : AVPlayer

/**
 *  The player delegate.
 */
@property (nonatomic, weak, nullable) id<SRGPlayerDelegate> delegate;

/**
 *  The time at which the player started seeking, `kCMTimeIndefinite` if no seek is currently being made.
 */
@property (nonatomic, readonly) CMTime seekStartTime;

/**
 *  The current time to which the player is seeking, `kCMTimeIndefinite` if no seek is currently being made.
 */
@property (nonatomic, readonly) CMTime seekTargetTime;

/**
 *  Attempt to play the media immediately if possible (iOS 10 and greater), otherwise normally.
 */
- (void)playImmediatelyIfPossibleAtRate:(float)rate;

/**
 *  Seek to a given time with the provided tolerances, calling the specified handler on completion. The delegate
 *  methods are called iff `notify` is set to `YES`.
 *
 *  @discussion The parent `-seekToTime:toleranceBefore:toleranceAfter:completionHandler:` method always notifies
 *              the player delegate. Refer to this method documentation for more information about the parameters
 *              and their role.
 */
- (void)seekToTime:(CMTime)time toleranceBefore:(CMTime)toleranceBefore toleranceAfter:(CMTime)toleranceAfter notify:(BOOL)notify completionHandler:(void (^)(BOOL finished))completionHandler;

@end

NS_ASSUME_NONNULL_END


text:
package com.github.ambry.replication;

import com.codahale.metrics.Counter;
import com.codahale.metrics.Gauge;
import com.codahale.metrics.Histogram;
import com.codahale.metrics.Meter;
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.Timer;
import com.github.ambry.clustermap.DataNodeId;
import com.github.ambry.clustermap.PartitionId;
import com.github.ambry.clustermap.ReplicaId;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * Metrics for Replication
 */
public class ReplicationMetrics {

  public final Map<String, Meter> interColoReplicationBytesRate = new HashMap<String, Meter>();
  public final Meter intraColoReplicationBytesRate;
  public final Map<String, Meter> plainTextInterColoReplicationBytesRate = new HashMap<String, Meter>();
  public final Meter plainTextIntraColoReplicationBytesRate;
  public final Map<String, Meter> sslInterColoReplicationBytesRate = new HashMap<String, Meter>();
  public final Meter sslIntraColoReplicationBytesRate;
  public final Map<String, Counter> interColoMetadataExchangeCount = new HashMap<>();
  public final Map<String, Counter> interColoReplicationGetRequestCount = new HashMap<>();
  public final Counter intraColoMetadataExchangeCount;
  public final Counter intraColoReplicationGetRequestCount;
  public final Map<String, Counter> interColoBlobsReplicatedCount = new HashMap<String, Counter>();
  public final Counter intraColoBlobsReplicatedCount;
  public final Counter unknownRemoteReplicaRequestCount;
  public final Map<String, Counter> plainTextInterColoMetadataExchangeCount = new HashMap<String, Counter>();
  public final Counter plainTextIntraColoMetadataExchangeCount;
  public final Map<String, Counter> plainTextInterColoBlobsReplicatedCount = new HashMap<String, Counter>();
  public final Counter plainTextIntraColoBlobsReplicatedCount;
  public final Map<String, Counter> sslInterColoMetadataExchangeCount = new HashMap<String, Counter>();
  public final Counter sslIntraColoMetadataExchangeCount;
  public final Map<String, Counter> sslInterColoBlobsReplicatedCount = new HashMap<String, Counter>();
  public final Counter sslIntraColoBlobsReplicatedCount;
  public final Counter replicationErrors;
  public final Counter plainTextReplicationErrors;
  public final Counter sslReplicationErrors;
  public final Counter replicationTokenResetCount;
  public final Counter replicationInvalidMessageStreamErrorCount;
  public final Map<String, Timer> interColoReplicationLatency = new HashMap<String, Timer>();
  public final Timer intraColoReplicationLatency;
  public final Map<String, Timer> plainTextInterColoReplicationLatency = new HashMap<String, Timer>();
  public final Timer plainTextIntraColoReplicationLatency;
  public final Map<String, Timer> sslInterColoReplicationLatency = new HashMap<String, Timer>();
  public final Timer sslIntraColoReplicationLatency;
  public final Histogram remoteReplicaTokensPersistTime;
  public final Histogram remoteReplicaTokensRestoreTime;
  public final Map<String, Histogram> interColoExchangeMetadataTime = new HashMap<String, Histogram>();
  public final Histogram intraColoExchangeMetadataTime;
  public final Map<String, Histogram> plainTextInterColoExchangeMetadataTime = new HashMap<String, Histogram>();
  public final Histogram plainTextIntraColoExchangeMetadataTime;
  public final Map<String, Histogram> sslInterColoExchangeMetadataTime = new HashMap<String, Histogram>();
  public final Histogram sslIntraColoExchangeMetadataTime;
  public final Map<String, Histogram> interColoFixMissingKeysTime = new HashMap<String, Histogram>();
  public final Histogram intraColoFixMissingKeysTime;
  public final Map<String, Histogram> plainTextInterColoFixMissingKeysTime = new HashMap<String, Histogram>();
  public final Histogram plainTextIntraColoFixMissingKeysTime;
  public final Map<String, Histogram> sslInterColoFixMissingKeysTime = new HashMap<String, Histogram>();
  public final Histogram sslIntraColoFixMissingKeysTime;
  public final Map<String, Histogram> interColoReplicationMetadataRequestTime = new HashMap<String, Histogram>();
  public final Histogram intraColoReplicationMetadataRequestTime;
  public final Map<String, Histogram> plainTextInterColoReplicationMetadataRequestTime =
      new HashMap<String, Histogram>();
  public final Histogram plainTextIntraColoReplicationMetadataRequestTime;
  public final Map<String, Histogram> sslInterColoReplicationMetadataRequestTime = new HashMap<String, Histogram>();
  public final Histogram sslIntraColoReplicationMetadataRequestTime;
  public final Histogram intraColoReplicationWaitTime;
  public final Map<String, Histogram> interColoCheckMissingKeysTime = new HashMap<String, Histogram>();
  public final Histogram intraColoCheckMissingKeysTime;
  public final Map<String, Histogram> interColoProcessMetadataResponseTime = new HashMap<String, Histogram>();
  public final Histogram intraColoProcessMetadataResponseTime;
  public final Map<String, Histogram> interColoGetRequestTime = new HashMap<String, Histogram>();
  public final Histogram intraColoGetRequestTime;
  public final Map<String, Histogram> plainTextInterColoGetRequestTime = new HashMap<String, Histogram>();
  public final Histogram plainTextIntraColoGetRequestTime;
  public final Map<String, Histogram> sslInterColoGetRequestTime = new HashMap<String, Histogram>();
  public final Histogram sslIntraColoGetRequestTime;
  public final Map<String, Histogram> interColoBatchStoreWriteTime = new HashMap<String, Histogram>();
  public final Histogram intraColoBatchStoreWriteTime;
  public final Map<String, Histogram> plainTextInterColoBatchStoreWriteTime = new HashMap<String, Histogram>();
  public final Histogram plainTextIntraColoBatchStoreWriteTime;
  public final Map<String, Histogram> sslInterColoBatchStoreWriteTime = new HashMap<String, Histogram>();
  public final Histogram sslIntraColoBatchStoreWriteTime;
  public final Map<String, Histogram> interColoTotalReplicationTime = new HashMap<String, Histogram>();
  public final Histogram intraColoTotalReplicationTime;
  public final Map<String, Histogram> plainTextInterColoTotalReplicationTime = new HashMap<String, Histogram>();
  public final Histogram plainTextIntraColoTotalReplicationTime;
  public final Map<String, Histogram> sslInterColoTotalReplicationTime = new HashMap<String, Histogram>();
  public final Histogram sslIntraColoTotalReplicationTime;
  public final Counter blobDeletedOnGetCount;
  public final Counter blobAuthorizationFailureCount;
  public final Counter intraColoReplicaSyncedBackoffCount;
  public final Counter interColoReplicaSyncedBackoffCount;
  public final Counter intraColoReplicaThreadIdleCount;
  public final Counter interColoReplicaThreadIdleCount;
  public final Counter intraColoReplicaThreadThrottleCount;
  public final Counter interColoReplicaThreadThrottleCount;

  public List<Gauge<Long>> replicaLagInBytes;
  private MetricRegistry registry;
  private Map<String, Counter> metadataRequestErrorMap;
  private Map<String, Counter> getRequestErrorMap;
  private Map<String, Counter> localStoreErrorMap;
  private Map<PartitionId, Counter> partitionIdToInvalidMessageStreamErrorCounter;

  public ReplicationMetrics(MetricRegistry registry, List<? extends ReplicaId> replicaIds) {
    metadataRequestErrorMap = new HashMap<String, Counter>();
    getRequestErrorMap = new HashMap<String, Counter>();
    localStoreErrorMap = new HashMap<String, Counter>();
    partitionIdToInvalidMessageStreamErrorCounter = new HashMap<PartitionId, Counter>();
    intraColoReplicationBytesRate =
        registry.meter(MetricRegistry.name(ReplicaThread.class, "IntraColoReplicationBytesRate"));
    plainTextIntraColoReplicationBytesRate =
        registry.meter(MetricRegistry.name(ReplicaThread.class, "PlainTextIntraColoReplicationBytesRate"));
    sslIntraColoReplicationBytesRate =
        registry.meter(MetricRegistry.name(ReplicaThread.class, "SslIntraColoReplicationBytesRate"));
    intraColoMetadataExchangeCount =
        registry.counter(MetricRegistry.name(ReplicaThread.class, "IntraColoMetadataExchangeCount"));
    intraColoReplicationGetRequestCount =
        registry.counter(MetricRegistry.name(ReplicaThread.class, "IntraColoReplicationGetRequestCount"));
    intraColoBlobsReplicatedCount =
        registry.counter(MetricRegistry.name(ReplicaThread.class, "IntraColoBlobsReplicatedCount"));
    unknownRemoteReplicaRequestCount =
        registry.counter(MetricRegistry.name(ReplicaThread.class, "UnknownRemoteReplicaRequestCount"));
    plainTextIntraColoMetadataExchangeCount =
        registry.counter(MetricRegistry.name(ReplicaThread.class, "PlainTextIntraColoMetadataExchangeCount"));
    plainTextIntraColoBlobsReplicatedCount =
        registry.counter(MetricRegistry.name(ReplicaThread.class, "PlainTextIntraColoBlobsReplicatedCount"));
    sslIntraColoMetadataExchangeCount =
        registry.counter(MetricRegistry.name(ReplicaThread.class, "SslIntraColoMetadataExchangeCount"));
    sslIntraColoBlobsReplicatedCount =
        registry.counter(MetricRegistry.name(ReplicaThread.class, "SslIntraColoBlobsReplicatedCount"));
    replicationErrors = registry.counter(MetricRegistry.name(ReplicaThread.class, "ReplicationErrors"));
    plainTextReplicationErrors =
        registry.counter(MetricRegistry.name(ReplicaThread.class, "PlainTextReplicationErrors"));
    sslReplicationErrors = registry.counter(MetricRegistry.name(ReplicaThread.class, "SslReplicationErrors"));
    replicationTokenResetCount =
        registry.counter(MetricRegistry.name(ReplicaThread.class, "ReplicationTokenResetCount"));
    replicationInvalidMessageStreamErrorCount =
        registry.counter(MetricRegistry.name(ReplicaThread.class, "ReplicationInvalidMessageStreamErrorCount"));
    intraColoReplicationLatency =
        registry.timer(MetricRegistry.name(ReplicaThread.class, "IntraColoReplicationLatency"));
    plainTextIntraColoReplicationLatency =
        registry.timer(MetricRegistry.name(ReplicaThread.class, "PlainTextIntraColoReplicationLatency"));
    sslIntraColoReplicationLatency =
        registry.timer(MetricRegistry.name(ReplicaThread.class, "SslIntraColoReplicationLatency"));
    remoteReplicaTokensPersistTime =
        registry.histogram(MetricRegistry.name(ReplicaThread.class, "RemoteReplicaTokensPersistTime"));
    remoteReplicaTokensRestoreTime =
        registry.histogram(MetricRegistry.name(ReplicaThread.class, "RemoteReplicaTokensRestoreTime"));
    intraColoExchangeMetadataTime =
        registry.histogram(MetricRegistry.name(ReplicaThread.class, "IntraColoExchangeMetadataTime"));
    plainTextIntraColoExchangeMetadataTime =
        registry.histogram(MetricRegistry.name(ReplicaThread.class, "PlainTextIntraColoExchangeMetadataTime"));
    sslIntraColoExchangeMetadataTime =
        registry.histogram(MetricRegistry.name(ReplicaThread.class, "SslIntraColoExchangeMetadataTime"));
    intraColoFixMissingKeysTime =
        registry.histogram(MetricRegistry.name(ReplicaThread.class, "IntraColoFixMissingKeysTime"));
    plainTextIntraColoFixMissingKeysTime =
        registry.histogram(MetricRegistry.name(ReplicaThread.class, "PlainTextIntraColoFixMissingKeysTime"));
    sslIntraColoFixMissingKeysTime =
        registry.histogram(MetricRegistry.name(ReplicaThread.class, "SslIntraColoFixMissingKeysTime"));
    intraColoReplicationWaitTime =
        registry.histogram(MetricRegistry.name(ReplicaThread.class, "IntraColoReplicationWaitTime"));
    intraColoReplicationMetadataRequestTime =
        registry.histogram(MetricRegistry.name(ReplicaThread.class, "IntraColoReplicationMetadataRequestTime"));
    plainTextIntraColoReplicationMetadataRequestTime = registry.histogram(
        MetricRegistry.name(ReplicaThread.class, "PlainTextIntraColoReplicationMetadataRequestTime"));
    sslIntraColoReplicationMetadataRequestTime =
        registry.histogram(MetricRegistry.name(ReplicaThread.class, "SslIntraColoReplicationMetadataRequestTime"));
    intraColoCheckMissingKeysTime =
        registry.histogram(MetricRegistry.name(ReplicaThread.class, "IntraColoCheckMissingKeysTime"));
    intraColoProcessMetadataResponseTime =
        registry.histogram(MetricRegistry.name(ReplicaThread.class, "IntraColoProcessMetadataResponseTime"));
    intraColoGetRequestTime = registry.histogram(MetricRegistry.name(ReplicaThread.class, "IntraColoGetRequestTime"));
    plainTextIntraColoGetRequestTime =
        registry.histogram(MetricRegistry.name(ReplicaThread.class, "PlainTextIntraColoGetRequestTime"));
    sslIntraColoGetRequestTime =
        registry.histogram(MetricRegistry.name(ReplicaThread.class, "SslIntraColoGetRequestTime"));
    intraColoBatchStoreWriteTime =
        registry.histogram(MetricRegistry.name(ReplicaThread.class, "IntraColoBatchStoreWriteTime"));
    plainTextIntraColoBatchStoreWriteTime =
        registry.histogram(MetricRegistry.name(ReplicaThread.class, "PlainTextIntraColoBatchStoreWriteTime"));
    sslIntraColoBatchStoreWriteTime =
        registry.histogram(MetricRegistry.name(ReplicaThread.class, "SslIntraColoBatchStoreWriteTime"));
    intraColoTotalReplicationTime =
        registry.histogram(MetricRegistry.name(ReplicaThread.class, "IntraColoTotalReplicationTime"));
    plainTextIntraColoTotalReplicationTime =
        registry.histogram(MetricRegistry.name(ReplicaThread.class, "PlainTextIntraColoTotalReplicationTime"));
    sslIntraColoTotalReplicationTime =
        registry.histogram(MetricRegistry.name(ReplicaThread.class, "SslIntraColoTotalReplicationTime"));
    blobDeletedOnGetCount = registry.counter(MetricRegistry.name(ReplicaThread.class, "BlobDeletedOnGetCount"));
    blobAuthorizationFailureCount =
        registry.counter(MetricRegistry.name(ReplicaThread.class, "BlobAuthorizationFailureCount"));
    intraColoReplicaSyncedBackoffCount =
        registry.counter(MetricRegistry.name(ReplicaThread.class, "IntraColoReplicaSyncedBackoffCount"));
    interColoReplicaSyncedBackoffCount =
        registry.counter(MetricRegistry.name(ReplicaThread.class, "InterColoReplicaSyncedBackoffCount"));
    intraColoReplicaThreadIdleCount =
        registry.counter(MetricRegistry.name(ReplicaThread.class, "IntraColoReplicaThreadIdleCount"));
    interColoReplicaThreadIdleCount =
        registry.counter(MetricRegistry.name(ReplicaThread.class, "InterColoReplicaThreadIdleCount"));
    intraColoReplicaThreadThrottleCount =
        registry.counter(MetricRegistry.name(ReplicaThread.class, "IntraColoReplicaThreadThrottleCount"));
    interColoReplicaThreadThrottleCount =
        registry.counter(MetricRegistry.name(ReplicaThread.class, "InterColoReplicaThreadThrottleCount"));
    this.registry = registry;
    this.replicaLagInBytes = new ArrayList<Gauge<Long>>();
    populateInvalidMessageMetricForReplicas(replicaIds);
  }

  /**
   * Updates per colo metrics for each thread pool
   * @param datacenters List of datacenters to replicate from
   */
  public void populatePerColoMetrics(Set<String> datacenters) {
    for (String datacenter : datacenters) {
      Meter interColoReplicationBytesRatePerDC =
          registry.meter(MetricRegistry.name(ReplicaThread.class, "Inter-" + datacenter + "-ReplicationBytesRate"));
      interColoReplicationBytesRate.put(datacenter, interColoReplicationBytesRatePerDC);
      Meter plainTextInterColoReplicationBytesRatePerDC = registry.meter(
          MetricRegistry.name(ReplicaThread.class, "PlainTextInter-" + datacenter + "-ReplicationBytesRate"));
      plainTextInterColoReplicationBytesRate.put(datacenter, plainTextInterColoReplicationBytesRatePerDC);
      Meter sslInterColoReplicationBytesRatePerDC =
          registry.meter(MetricRegistry.name(ReplicaThread.class, "SslInter-" + datacenter + "-ReplicationBytesRate"));
      sslInterColoReplicationBytesRate.put(datacenter, sslInterColoReplicationBytesRatePerDC);
      Counter interColoMetadataExchangeCountPerDC =
          registry.counter(MetricRegistry.name(ReplicaThread.class, "Inter-" + datacenter + "-MetadataExchangeCount"));
      interColoMetadataExchangeCount.put(datacenter, interColoMetadataExchangeCountPerDC);
      Counter interColoReplicationGetRequestCountPerDC = registry.counter(
          MetricRegistry.name(ReplicaThread.class, "Inter-" + datacenter + "-ReplicationGetRequestCount"));
      interColoReplicationGetRequestCount.put(datacenter, interColoReplicationGetRequestCountPerDC);
      Counter interColoBlobsReplicatedCountPerDC =
          registry.counter(MetricRegistry.name(ReplicaThread.class, "Inter-" + datacenter + "-ReplicationBlobsCount"));
      interColoBlobsReplicatedCount.put(datacenter, interColoBlobsReplicatedCountPerDC);
      Counter plainTextInterColoMetadataExchangeCountPerDC = registry.counter(
          MetricRegistry.name(ReplicaThread.class, "PlainTextInter-" + datacenter + "-MetadataExchangeCount"));
      plainTextInterColoMetadataExchangeCount.put(datacenter, plainTextInterColoMetadataExchangeCountPerDC);
      Counter plainTextInterColoBlobsReplicatedCountPerDC = registry.counter(
          MetricRegistry.name(ReplicaThread.class, "PlainTextInter-" + datacenter + "-BlobsReplicatedCount"));
      plainTextInterColoBlobsReplicatedCount.put(datacenter, plainTextInterColoBlobsReplicatedCountPerDC);
      Counter sslInterColoMetadataExchangeCountPerDC = registry.counter(
          MetricRegistry.name(ReplicaThread.class, "SslInter-" + datacenter + "-MetadataExchangeCount"));
      sslInterColoMetadataExchangeCount.put(datacenter, sslInterColoMetadataExchangeCountPerDC);
      Counter sslInterColoBlobsReplicatedCountPerDC = registry.counter(
          MetricRegistry.name(ReplicaThread.class, "SslInter-" + datacenter + "-BlobsReplicatedCount"));
      sslInterColoBlobsReplicatedCount.put(datacenter, sslInterColoBlobsReplicatedCountPerDC);
      Timer interColoReplicationLatencyPerDC =
          registry.timer(MetricRegistry.name(ReplicaThread.class, "Inter-" + datacenter + "-ReplicationLatency"));
      interColoReplicationLatency.put(datacenter, interColoReplicationLatencyPerDC);
      Timer plainTextInterColoReplicationLatencyPerDC = registry.timer(
          MetricRegistry.name(ReplicaThread.class, "PlainTextInter-" + datacenter + "-ReplicationLatency"));
      plainTextInterColoReplicationLatency.put(datacenter, plainTextInterColoReplicationLatencyPerDC);
      Timer sslInterColoReplicationLatencyPerDC =
          registry.timer(MetricRegistry.name(ReplicaThread.class, "SslInter-" + datacenter + "-ReplicationLatency"));
      sslInterColoReplicationLatency.put(datacenter, sslInterColoReplicationLatencyPerDC);
      Histogram interColoExchangeMetadataTimePerDC =
          registry.histogram(MetricRegistry.name(ReplicaThread.class, "Inter-" + datacenter + "-ExchangeMetadataTime"));
      interColoExchangeMetadataTime.put(datacenter, interColoExchangeMetadataTimePerDC);
      Histogram plainTextInterColoExchangeMetadataTimePerDC = registry.histogram(
          MetricRegistry.name(ReplicaThread.class, "PlainTextInter-" + datacenter + "-ExchangeMetadataTime"));
      plainTextInterColoExchangeMetadataTime.put(datacenter, plainTextInterColoExchangeMetadataTimePerDC);
      Histogram sslInterColoExchangeMetadataTimePerDC = registry.histogram(
          MetricRegistry.name(ReplicaThread.class, "SslInter-" + datacenter + "-ExchangeMetadataTime"));
      sslInterColoExchangeMetadataTime.put(datacenter, sslInterColoExchangeMetadataTimePerDC);
      Histogram interColoFixMissingKeysTimePerDC =
          registry.histogram(MetricRegistry.name(ReplicaThread.class, "Inter-" + datacenter + "-FixMissingKeysTime"));
      interColoFixMissingKeysTime.put(datacenter, interColoFixMissingKeysTimePerDC);
      Histogram plainTextInterColoFixMissingKeysTimePerDC = registry.histogram(
          MetricRegistry.name(ReplicaThread.class, "PlainTextInter-" + datacenter + "-FixMissingKeysTime"));
      plainTextInterColoFixMissingKeysTime.put(datacenter, plainTextInterColoFixMissingKeysTimePerDC);
      Histogram sslInterColoFixMissingKeysTimePerDC = registry.histogram(
          MetricRegistry.name(ReplicaThread.class, "SslInter-" + datacenter + "-FixMissingKeysTime"));
      sslInterColoFixMissingKeysTime.put(datacenter, sslInterColoFixMissingKeysTimePerDC);
      Histogram interColoReplicationMetadataRequestTimePerDC = registry.histogram(
          MetricRegistry.name(ReplicaThread.class, "Inter-" + datacenter + "-ReplicationMetadataRequestTime"));
      interColoReplicationMetadataRequestTime.put(datacenter, interColoReplicationMetadataRequestTimePerDC);
      Histogram plainTextInterColoReplicationMetadataRequestTimePerDC = registry.histogram(
          MetricRegistry.name(ReplicaThread.class, "PlainTextInter-" + datacenter + "-ReplicationMetadataRequestTime"));
      plainTextInterColoReplicationMetadataRequestTime.put(datacenter,
          plainTextInterColoReplicationMetadataRequestTimePerDC);
      Histogram sslInterColoReplicationMetadataRequestTimePerDC = registry.histogram(
          MetricRegistry.name(ReplicaThread.class, "SslInter-" + datacenter + "-ReplicationMetadataRequestTime"));
      sslInterColoReplicationMetadataRequestTime.put(datacenter, sslInterColoReplicationMetadataRequestTimePerDC);
      Histogram interColoCheckMissingKeysTimePerDC =
          registry.histogram(MetricRegistry.name(ReplicaThread.class, "Inter-" + datacenter + "-CheckMissingKeysTime"));
      interColoCheckMissingKeysTime.put(datacenter, interColoCheckMissingKeysTimePerDC);
      Histogram interColoProcessMetadataResponseTimePerDC = registry.histogram(
          MetricRegistry.name(ReplicaThread.class, "Inter-" + datacenter + "-ProcessMetadataResponseTime"));
      interColoProcessMetadataResponseTime.put(datacenter, interColoProcessMetadataResponseTimePerDC);
      Histogram interColoGetRequestTimePerDC =
          registry.histogram(MetricRegistry.name(ReplicaThread.class, "Inter-" + datacenter + "-GetRequestTime"));
      interColoGetRequestTime.put(datacenter, interColoGetRequestTimePerDC);
      Histogram plainTextInterColoGetRequestTimePerDC = registry.histogram(
          MetricRegistry.name(ReplicaThread.class, "PlainTextInter-" + datacenter + "-GetRequestTime"));
      plainTextInterColoGetRequestTime.put(datacenter, plainTextInterColoGetRequestTimePerDC);
      Histogram sslInterColoGetRequestTimePerDC =
          registry.histogram(MetricRegistry.name(ReplicaThread.class, "SslInter-" + datacenter + "-GetRequestTime"));
      sslInterColoGetRequestTime.put(datacenter, sslInterColoGetRequestTimePerDC);
      Histogram interColoBatchStoreWriteTimePerDC =
          registry.histogram(MetricRegistry.name(ReplicaThread.class, "Inter-" + datacenter + "-BatchStoreWriteTime"));
      interColoBatchStoreWriteTime.put(datacenter, interColoBatchStoreWriteTimePerDC);
      Histogram plainTextInterColoBatchStoreWriteTimePerDC = registry.histogram(
          MetricRegistry.name(ReplicaThread.class, "PlainTextInter-" + datacenter + "-BatchStoreWriteTime"));
      plainTextInterColoBatchStoreWriteTime.put(datacenter, plainTextInterColoBatchStoreWriteTimePerDC);
      Histogram sslInterColoBatchStoreWriteTimePerDC = registry.histogram(
          MetricRegistry.name(ReplicaThread.class, "SslInter-" + datacenter + "-BatchStoreWriteTime"));
      sslInterColoBatchStoreWriteTime.put(datacenter, sslInterColoBatchStoreWriteTimePerDC);
      Histogram interColoTotalReplicationTimePerDC =
          registry.histogram(MetricRegistry.name(ReplicaThread.class, "Inter-" + datacenter + "-TotalReplicationTime"));
      interColoTotalReplicationTime.put(datacenter, interColoTotalReplicationTimePerDC);
      Histogram plainTextInterColoTotalReplicationTimePerDC = registry.histogram(
          MetricRegistry.name(ReplicaThread.class, "PlainTextInter-" + datacenter + "-TotalReplicationTime"));
      plainTextInterColoTotalReplicationTime.put(datacenter, plainTextInterColoTotalReplicationTimePerDC);
      Histogram sslInterColoTotalReplicationTimePerDC = registry.histogram(
          MetricRegistry.name(ReplicaThread.class, "SslInter-" + datacenter + "-TotalReplicationTime"));
      sslInterColoTotalReplicationTime.put(datacenter, sslInterColoTotalReplicationTimePerDC);
    }
  }

  /**
   * Register metrics for measuring the number of active intra and inter colo replica threads.
   *
   * @param replicaThreadPools A map of datacenter names to {@link ReplicaThread}s handling replication from that
   *                           datacenter
   * @param localDatacenter The datacenter on which the {@link ReplicationManager} is running
   */
  void trackLiveThreadsCount(final Map<String, List<ReplicaThread>> replicaThreadPools, String localDatacenter) {
    for (final String datacenter : replicaThreadPools.keySet()) {
      Gauge<Integer> liveThreadsPerDatacenter = () -> getLiveThreads(replicaThreadPools.get(datacenter));
      if (localDatacenter.equals(datacenter)) {
        registry.register(MetricRegistry.name(ReplicaThread.class, "NumberOfIntra-Colo-ReplicaThreads"),
            liveThreadsPerDatacenter);
      } else {
        registry.register(MetricRegistry.name(ReplicaThread.class, "NumberOfInter-" + datacenter + "-ReplicaThreads"),
            liveThreadsPerDatacenter);
      }
    }
  }

  private int getLiveThreads(List<ReplicaThread> replicaThreads) {
    int count = 0;
    for (ReplicaThread thread : replicaThreads) {
      if (thread.isThreadUp()) {
        count++;
      }
    }
    return count;
  }

  public void addRemoteReplicaToLagMetrics(final RemoteReplicaInfo remoteReplicaInfo) {
    ReplicaId replicaId = remoteReplicaInfo.getReplicaId();
    DataNodeId dataNodeId = replicaId.getDataNodeId();
    final String metricName =
        dataNodeId.getHostname() + "-" + dataNodeId.getPort() + "-" + replicaId.getPartitionId() + "-replicaLagInBytes";
    Gauge<Long> replicaLag = remoteReplicaInfo::getRemoteLagFromLocalInBytes;
    registry.register(MetricRegistry.name(ReplicationMetrics.class, metricName), replicaLag);
    replicaLagInBytes.add(replicaLag);
  }

  /**
   * Tracks the number of partitions for which replication is disabled.
   * @param replicaThreadPools A map of datacenter names to {@link ReplicaThread}s handling replication from that
   *                           datacenter
   */
  public void trackReplicationDisabledPartitions(final Map<String, List<ReplicaThread>> replicaThreadPools) {
    for (Map.Entry<String, List<ReplicaThread>> entry : replicaThreadPools.entrySet()) {
      String datacenter = entry.getKey();
      List<ReplicaThread> pool = entry.getValue();
      Gauge<Integer> disabledCount = () -> {
        Set<PartitionId> replicationDisabledPartitions = new HashSet<>();
        for (ReplicaThread replicaThread : pool) {
          replicationDisabledPartitions.addAll(replicaThread.getReplicationDisabledPartitions());
        }
        return replicationDisabledPartitions.size();
      };
      registry.register(MetricRegistry.name(ReplicaThread.class, "ReplicationDisabledPartitions-" + datacenter),
          disabledCount);
    }
  }

  private void populateInvalidMessageMetricForReplicas(List<? extends ReplicaId> replicaIds) {
    for (ReplicaId replicaId : replicaIds) {
      PartitionId partitionId = replicaId.getPartitionId();
      if (!partitionIdToInvalidMessageStreamErrorCounter.containsKey(partitionId)) {
        Counter partitionBasedCorruptionErrorCount =
            registry.counter(MetricRegistry.name(ReplicaThread.class, partitionId + "-CorruptionErrorCount"));
        partitionIdToInvalidMessageStreamErrorCounter.put(partitionId, partitionBasedCorruptionErrorCount);
      }
    }
  }

  public void incrementInvalidMessageError(PartitionId partitionId) {
    replicationInvalidMessageStreamErrorCount.inc();
    if (partitionIdToInvalidMessageStreamErrorCounter.containsKey(partitionId)) {
      partitionIdToInvalidMessageStreamErrorCounter.get(partitionId).inc();
    }
  }

  public void createRemoteReplicaErrorMetrics(RemoteReplicaInfo remoteReplicaInfo) {
    String metadataRequestErrorMetricName =
        remoteReplicaInfo.getReplicaId().getDataNodeId().getHostname() + "-" + remoteReplicaInfo.getReplicaId()
            .getDataNodeId()
            .getPort() + "-" + remoteReplicaInfo.getReplicaId().getPartitionId().toString() + "-metadataRequestError";
    Counter metadataRequestError =
        registry.counter(MetricRegistry.name(ReplicaThread.class, metadataRequestErrorMetricName));
    metadataRequestErrorMap.put(metadataRequestErrorMetricName, metadataRequestError);
    String getRequestErrorMetricName =
        remoteReplicaInfo.getReplicaId().getDataNodeId().getHostname() + "-" + remoteReplicaInfo.getReplicaId()
            .getDataNodeId()
            .getPort() + "-" + remoteReplicaInfo.getReplicaId().getPartitionId().toString() + "-getRequestError";
    Counter getRequestError = registry.counter(MetricRegistry.name(ReplicaThread.class, getRequestErrorMetricName));
    getRequestErrorMap.put(getRequestErrorMetricName, getRequestError);
    String localStoreErrorMetricName =
        remoteReplicaInfo.getReplicaId().getDataNodeId().getHostname() + "-" + remoteReplicaInfo.getReplicaId()
            .getDataNodeId()
            .getPort() + "-" + remoteReplicaInfo.getReplicaId().getPartitionId().toString() + "-localStoreError";
    Counter localStoreError = registry.counter(MetricRegistry.name(ReplicaThread.class, localStoreErrorMetricName));
    localStoreErrorMap.put(localStoreErrorMetricName, localStoreError);
  }

  public void updateMetadataRequestError(ReplicaId remoteReplica) {
    String metadataRequestErrorMetricName =
        remoteReplica.getDataNodeId().getHostname() + "-" + remoteReplica.getDataNodeId().getPort() + "-"
            + remoteReplica.getPartitionId().toString() + "-metadataRequestError";
    metadataRequestErrorMap.get(metadataRequestErrorMetricName).inc();
  }

  public void updateGetRequestError(ReplicaId remoteReplica) {
    String getRequestErrorMetricName =
        remoteReplica.getDataNodeId().getHostname() + "-" + remoteReplica.getDataNodeId().getPort() + "-"
            + remoteReplica.getPartitionId().toString() + "-getRequestError";
    getRequestErrorMap.get(getRequestErrorMetricName).inc();
  }

  public void updateLocalStoreError(ReplicaId remoteReplica) {
    String localStoreErrorMetricName =
        remoteReplica.getDataNodeId().getHostname() + "-" + remoteReplica.getDataNodeId().getPort() + "-"
            + remoteReplica.getPartitionId().toString() + "-localStoreError";
    localStoreErrorMap.get(localStoreErrorMetricName).inc();
  }

  public void incrementReplicationErrors(boolean sslEnabled) {
    replicationErrors.inc();
    if (sslEnabled) {
      sslReplicationErrors.inc();
    } else {
      plainTextReplicationErrors.inc();
    }
  }

  public void updateTotalReplicationTime(long totalReplicationTime, boolean remoteColo, boolean sslEnabled,
      String datacenter) {
    if (remoteColo) {
      interColoTotalReplicationTime.get(datacenter).update(totalReplicationTime);
      if (sslEnabled) {
        sslInterColoTotalReplicationTime.get(datacenter).update(totalReplicationTime);
      } else {
        plainTextInterColoTotalReplicationTime.get(datacenter).update(totalReplicationTime);
      }
    } else {
      intraColoTotalReplicationTime.update(totalReplicationTime);
      if (sslEnabled) {
        sslIntraColoTotalReplicationTime.update(totalReplicationTime);
      } else {
        plainTextIntraColoTotalReplicationTime.update(totalReplicationTime);
      }
    }
  }

  public void updateExchangeMetadataTime(long exchangeMetadataTime, boolean remoteColo, boolean sslEnabled,
      String datacenter) {
    if (remoteColo) {
      interColoMetadataExchangeCount.get(datacenter).inc();
      interColoExchangeMetadataTime.get(datacenter).update(exchangeMetadataTime);
      if (sslEnabled) {
        sslInterColoMetadataExchangeCount.get(datacenter).inc();
        sslInterColoExchangeMetadataTime.get(datacenter).update(exchangeMetadataTime);
      } else {
        plainTextInterColoMetadataExchangeCount.get(datacenter).inc();
        plainTextInterColoExchangeMetadataTime.get(datacenter).update(exchangeMetadataTime);
      }
    } else {
      intraColoMetadataExchangeCount.inc();
      intraColoExchangeMetadataTime.update(exchangeMetadataTime);
      if (sslEnabled) {
        sslIntraColoMetadataExchangeCount.inc();
        sslIntraColoExchangeMetadataTime.update(exchangeMetadataTime);
      } else {
        plainTextIntraColoMetadataExchangeCount.inc();
        plainTextIntraColoExchangeMetadataTime.update(exchangeMetadataTime);
      }
    }
  }

  public void updateCheckMissingKeysTime(long checkMissingKeyTime, boolean remoteColo, String datacenterName) {
    if (remoteColo) {
      interColoCheckMissingKeysTime.get(datacenterName).update(checkMissingKeyTime);
    } else {
      intraColoCheckMissingKeysTime.update(checkMissingKeyTime);
    }
  }

  public void updateFixMissingStoreKeysTime(long fixMissingStoreKeysTime, boolean remoteColo, boolean sslEnabled,
      String datacenter) {
    if (remoteColo) {
      interColoFixMissingKeysTime.get(datacenter).update(fixMissingStoreKeysTime);
      if (sslEnabled) {
        sslInterColoFixMissingKeysTime.get(datacenter).update(fixMissingStoreKeysTime);
      } else {
        plainTextInterColoFixMissingKeysTime.get(datacenter).update(fixMissingStoreKeysTime);
      }
    } else {
      intraColoFixMissingKeysTime.update(fixMissingStoreKeysTime);
      if (sslEnabled) {
        sslIntraColoFixMissingKeysTime.update(fixMissingStoreKeysTime);
      } else {
        plainTextIntraColoFixMissingKeysTime.update(fixMissingStoreKeysTime);
      }
    }
  }

  public void updateMetadataRequestTime(long metadataRequestTime, boolean remoteColo, boolean sslEnabled,
      String datacenter) {
    if (remoteColo) {
      interColoReplicationMetadataRequestTime.get(datacenter).update(metadataRequestTime);
      if (sslEnabled) {
        sslInterColoReplicationMetadataRequestTime.get(datacenter).update(metadataRequestTime);
      } else {
        plainTextInterColoReplicationMetadataRequestTime.get(datacenter).update(metadataRequestTime);
      }
    } else {
      intraColoReplicationMetadataRequestTime.update(metadataRequestTime);
      if (sslEnabled) {
        sslIntraColoReplicationMetadataRequestTime.update(metadataRequestTime);
      } else {
        plainTextIntraColoReplicationMetadataRequestTime.update(metadataRequestTime);
      }
    }
  }

  public void updateGetRequestTime(long getRequestTime, boolean remoteColo, boolean sslEnabled, String datacenter) {
    if (remoteColo) {
      interColoReplicationGetRequestCount.get(datacenter).inc();
      interColoGetRequestTime.get(datacenter).update(getRequestTime);
      if (sslEnabled) {
        sslInterColoGetRequestTime.get(datacenter).update(getRequestTime);
      } else {
        plainTextInterColoGetRequestTime.get(datacenter).update(getRequestTime);
      }
    } else {
      intraColoReplicationGetRequestCount.inc();
      intraColoGetRequestTime.update(getRequestTime);
      if (sslEnabled) {
        sslIntraColoGetRequestTime.update(getRequestTime);
      } else {
        plainTextIntraColoGetRequestTime.update(getRequestTime);
      }
    }
  }

  public void updateBatchStoreWriteTime(long batchStoreWriteTime, long totalBytesFixed, long totalBlobsFixed,
      boolean remoteColo, boolean sslEnabled, String datacenter) {
    if (remoteColo) {
      interColoReplicationBytesRate.get(datacenter).mark(totalBytesFixed);
      interColoBlobsReplicatedCount.get(datacenter).inc(totalBlobsFixed);
      interColoBatchStoreWriteTime.get(datacenter).update(batchStoreWriteTime);
      if (sslEnabled) {
        sslInterColoReplicationBytesRate.get(datacenter).mark(totalBytesFixed);
        sslInterColoBlobsReplicatedCount.get(datacenter).inc(totalBlobsFixed);
        sslInterColoBatchStoreWriteTime.get(datacenter).update(batchStoreWriteTime);
      } else {
        plainTextInterColoReplicationBytesRate.get(datacenter).mark(totalBytesFixed);
        plainTextInterColoBlobsReplicatedCount.get(datacenter).inc(totalBlobsFixed);
        plainTextInterColoBatchStoreWriteTime.get(datacenter).update(batchStoreWriteTime);
      }
    } else {
      intraColoReplicationBytesRate.mark(totalBytesFixed);
      intraColoBlobsReplicatedCount.inc(totalBlobsFixed);
      intraColoBatchStoreWriteTime.update(batchStoreWriteTime);
      if (sslEnabled) {
        sslIntraColoReplicationBytesRate.mark(totalBytesFixed);
        sslIntraColoBlobsReplicatedCount.inc(totalBlobsFixed);
        sslIntraColoBatchStoreWriteTime.update(batchStoreWriteTime);
      } else {
        plainTextIntraColoReplicationBytesRate.mark(totalBytesFixed);
        plainTextIntraColoBlobsReplicatedCount.inc(totalBlobsFixed);
        plainTextIntraColoBatchStoreWriteTime.update(batchStoreWriteTime);
      }
    }
  }
}


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Annls mycol. 3(2): 163 (1905)

#### Original name
Corticium roseocremeum Bres., 1905

### Remarks
null


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using CommandLineParser;
using VMLab.Graph;
using VMLab.Helpers;
using VMLab.Hypervisor;
using VMLab.Session;

namespace VMLab.CommandLineHandlers
{
    public class Status : CommandHandlerBase
    {
        private readonly ISessionManager _sessionManager;
        private readonly IGraphManager _graphManager;
        private readonly IHypervisor _hypervisor;
        private readonly IConsole _console;

        public Status(ISessionManager sessionManager, IGraphManager graphManager, IConsole console)
        {
            _sessionManager = sessionManager;
            _graphManager = graphManager;
            _console = console;
            _hypervisor = sessionManager.GetHypervisor();
        }

        public override void ProcessCommand(string[] args)
        {
            try
            {

            _sessionManager.StartWithoutAction();

            _console.Information("Current Lab Virtual Machines:");

                foreach (var vm in _graphManager.VMs)
                {
                    var status = "Not Checked!";

                    var control = _hypervisor.GetVM(vm);

                    if (control == null)
                    {
                        status = "Unprovisioned";
                    }
                    else
                    {
                        switch (control.Status)
                        {
                            case VMStaus.Off:
                                status = "Off";
                                break;
                            case VMStaus.Pending:
                                status = "Pending";
                                break;
                            case VMStaus.Ready:
                                status = "Ready";
                                break;
                            default:
                                throw new ArgumentOutOfRangeException();
                        }
                    }

                    _console.Information("{vm} => {status}", vm.Name, status);
                }
            }
            catch (Exception e)
            {
                _console.Error("There was an error while checking the status: {error}", e);
            }
        }

        public override string PrimaryName => "status";
        public override IEnumerable<string> Names => new[] {"status", "state", "stat", "info", "inf", "nfo"};
        public override string UsageText => "Displays the state of Virtual machines in the lab";
    }
}


text:
module AsCombinedMetrics::Cli::Poller
  def poll(interval)
    logger.progname = "#{Module.nesting.first.to_s} #{__method__}"

    if options[:scalein_only]
      modes = [:ScaleIn]
    elsif  options[:scaleout_only]
      modes = [:ScaleOut]
    else
      modes = [:ScaleIn, :ScaleOut]
    end

    loop do
      @combined_metrics = {}
      modes.each do |mode|
        @config[:autoscale_group_name].each do |autoscale_group|
        logger.info "Polling metrics for #{autoscale_group} AutoScale Group on #{mode}"

          @config[mode].each do |metric|
            logger.debug "Getting stats for #{autoscale_group} AutoScale Group on metric #{metric}"
            @combined_metrics[metric[:metric_name]] ||= {}

            if metric.has_key?(:aggregate_as_group)
              logger.debug "Aggregating autoscale group metrics"
              @combined_metrics[metric[:metric_name]][:measure] = aggregate_instances_per_as_group(metric)
            else
              metric[:dimensions] = [{ name: "AutoScalingGroupName", value: autoscale_group}]
              @combined_metrics[metric[:metric_name]][:measure] = fetch_metric(metric) unless @combined_metrics[metric[:metric_name]].has_key?(:measure)
            end

            @combined_metrics[metric[:metric_name]][:threshold] = metric[:threshold]
            @combined_metrics[metric[:metric_name]][:comparison_operator] = metric[:comparison_operator]
          end

          logger.info { set_color  "Combined metrics attributes for #{autoscale_group} AutoScale Group on #{mode}: #{@combined_metrics}", :cyan }
          combined_metric_value = check_combined_metrics(mode)

          logger.info { set_color "Combined metrics value for #{autoscale_group} AutoScale Group: #{combined_metric_value} => [0 = Do Not #{mode}, 1 = OK To #{mode}]", :yellow, :bold }

          publish_metric(mode, autoscale_group, combined_metric_value)
        end
      end

        if options[:once]
          logger.info { set_color "Ran Once - Exiting now..." }
          exit 0
        else
          logger.info { set_color "Next metrics check in #{interval} seconds..." }
          sleep interval
        end
     end
  end
end


text:
angular.module('aaron.homepage.directives.navBar', [

])
.directive('navBar', function($location, $document) {
    return {
        restrict: 'E',
        templateUrl: 'src/components/directives/navBar/navBar.tpl.html',
        scope: {
            currentItem: '='
        },
        link: function($scope, element, attrs) {
            $scope.mobileMenuOpen = false;

            $scope.toggleMobileMenu = function($event) {
                $scope.mobileMenuOpen = !$scope.mobileMenuOpen;
                $event.stopPropagation();
            };

            $scope.hideMobileMenu = function(url) {
                $scope.mobileMenuOpen = false;

                if(url) {
                    $location.url(url);
                }

            };

            var hideOnOutsideClick = function(event) {
                var targetElement = angular.element(event.target);
                var hideMenu = true;

                for(var currentElement = targetElement; currentElement.length > 0; currentElement = currentElement.parent()) {
                    //console.log('currentElement[0].nodeName = %o', currentElement[0].nodeName);

                    if(currentElement[0].nodeName === 'NAV') {
                        hideMenu = false;
                        break;
                    }
                }

                if(hideMenu && $scope.mobileMenuOpen) {

                    $scope.hideMobileMenu();
                }
            };

            $document.bind('click', function() {
                $scope.$apply(function() { hideOnOutsideClick(event); });
            });

            $document.bind('touchstart', function() {
                $scope.$apply(function() { hideOnOutsideClick(event); });
            });

            $document.bind('touchmove', function() {
                $scope.$apply(function() { hideOnOutsideClick(event); });
            });

            $document.bind('pointerdown', function() {
                $scope.$apply(function() { hideOnOutsideClick(event); });
            });

            $document.bind('pointermove', function() {
                $scope.$apply(function() { hideOnOutsideClick(event); });
            });

        }
    };
});


text:
package com.hmkcode.android;

import java.io.File;
import java.util.List;

import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

public class MainActivity extends Activity implements OnClickListener {

	Button btnTackPic;
	TextView tvHasCamera, tvHasCameraApp;
	ImageView ivThumbnailPhoto;
	Bitmap bitMap;
	static int TAKE_PICTURE = 1;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		// Get reference to views
		tvHasCamera = (TextView) findViewById(R.id.tvHasCamera);
		tvHasCameraApp = (TextView) findViewById(R.id.tvHasCameraApp);
		btnTackPic = (Button) findViewById(R.id.btnTakePic);
		ivThumbnailPhoto = (ImageView) findViewById(R.id.ivThumbnailPhoto);

		// Does your device have a camera?
		if(hasCamera()){
			tvHasCamera.setBackgroundColor(0xFF00CC00);
			tvHasCamera.setText("You have Camera");
		}

		// Do you have Camera Apps?
		if(hasDefualtCameraApp(MediaStore.ACTION_IMAGE_CAPTURE)){
			tvHasCameraApp.setBackgroundColor(0xFF00CC00);
			tvHasCameraApp.setText("You have Camera Apps");
		}

		// add onclick listener to the button
		btnTackPic.setOnClickListener(this);

	}

	// on button "btnTackPic" is clicked
	@Override
	public void onClick(View view) {

		// create intent with ACTION_IMAGE_CAPTURE action
		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

		// to save picture remove comment
		/*File file = new File(Environment.getExternalStorageDirectory(),
		"my-photo.jpg");
		Uri photoPath = Uri.fromFile(file);
		intent.putExtra(MediaStore.EXTRA_OUTPUT, photoPath); */

		// start camera activity
	    startActivityForResult(intent, TAKE_PICTURE);

	}

	// The Android Camera application encodes the photo in the return Intent delivered to onActivityResult()
	// as a small Bitmap in the extras, under the key "data"
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent intent) {

		if (requestCode == TAKE_PICTURE && resultCode== RESULT_OK && intent != null){
			// get bundle
			Bundle extras = intent.getExtras();

			// get
			bitMap = (Bitmap) extras.get("data");
			ivThumbnailPhoto.setImageBitmap(bitMap);

		}
	}

	// method to check you have a Camera
	private boolean hasCamera(){
		return getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA);
	}

	// method to check you have Camera Apps
	private boolean hasDefualtCameraApp(String action){
		final PackageManager packageManager = getPackageManager();
	    final Intent intent = new Intent(action);
	    List<ResolveInfo> list = packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);

	    return list.size() > 0;

	}
}


text:
Smart-TextArea
==============

A greasemonkey script that makes textareas have smarter features


text:
using NUnit.Framework;
using Proteomics;
using Proteomics.ProteolyticDigestion;
using Proteomics.RetentionTimePrediction;
using System.Collections.Generic;

namespace Test
{
    [TestFixture]
    public sealed class RetentionTimeTest
    {
        [Test]
        public static void SimpleReversePhaseRetentionTimeTest()
        {
            Dictionary<string, double> peptidesAndHyrophobicities = new Dictionary<string, double>
            {
                { "QSHFANAEPEQK", 11.27 },
                { "SDLFENLQNYR", 30.44 },
                { "SLPSEFEPINLR", 33.12 }
            };

            SSRCalc3 calc = new SSRCalc3("SSRCalc 3.0 (300A)", SSRCalc3.Column.A300);

            foreach (string peptideSequence in peptidesAndHyrophobicities.Keys)
            {
                var peptide = new PeptideWithSetModifications(peptideSequence, new Dictionary<string, Modification>());
                double expected = peptidesAndHyrophobicities[peptideSequence];
                double actual = calc.ScoreSequence(peptide);

                Assert.That(expected, Is.EqualTo(actual).Within(0.01));
            }
        }
    }
}


text:
import debug from '../../debug'
import promptForDatasetName from './datasetNamePrompt'

export default async (context, options = {}) => {
  const {apiClient, prompt} = context
  const {message, allowCreation} = options
  const client = apiClient()

  const datasets = await client.datasets.list()
  const hasProduction = datasets.find((dataset) => dataset.name === 'production')
  const datasetChoices = datasets.map((dataset) => ({value: dataset.name}))
  const selected = await prompt.single({
    message: message || 'Select dataset to use',
    type: 'list',
    choices: allowCreation
      ? [{value: 'new', name: 'Create new dataset'}, new prompt.Separator(), ...datasetChoices]
      : datasetChoices,
  })

  if (selected === 'new') {
    debug('User wants to create a new dataset, prompting for name')
    const newDatasetName = await promptForDatasetName(prompt, {
      message: 'Name your dataset:',
      default: hasProduction ? undefined : 'production',
    })
    await client.datasets.create(newDatasetName)
    return newDatasetName
  }

  return selected
}


text:
namespace llvm {

class AssumptionCache;
class BlockFrequencyInfo;
class DemandedBits;
class DominatorTree;
class Function;
class Loop;
class LoopAccessInfo;
class LoopInfo;
class OptimizationRemarkEmitter;
class ProfileSummaryInfo;
class ScalarEvolution;
class TargetLibraryInfo;
class TargetTransformInfo;

extern cl::opt<bool> EnableLoopInterleaving;
extern cl::opt<bool> EnableLoopVectorization;

struct LoopVectorizeOptions {
  /// If false, consider all loops for interleaving.
  /// If true, only loops that explicitly request interleaving are considered.
  bool InterleaveOnlyWhenForced;

  /// If false, consider all loops for vectorization.
  /// If true, only loops that explicitly request vectorization are considered.
  bool VectorizeOnlyWhenForced;

  /// The current defaults when creating the pass with no arguments are:
  /// EnableLoopInterleaving = true and EnableLoopVectorization = true. This
  /// means that interleaving default is consistent with the cl::opt flag, while
  /// vectorization is not.
  /// FIXME: The default for EnableLoopVectorization in the cl::opt should be
  /// set to true, and the corresponding change to account for this be made in
  /// opt.cpp. The initializations below will become:
  /// InterleaveOnlyWhenForced(!EnableLoopInterleaving)
  /// VectorizeOnlyWhenForced(!EnableLoopVectorization).
  LoopVectorizeOptions()
      : InterleaveOnlyWhenForced(false), VectorizeOnlyWhenForced(false) {}
  LoopVectorizeOptions(bool InterleaveOnlyWhenForced,
                       bool VectorizeOnlyWhenForced)
      : InterleaveOnlyWhenForced(InterleaveOnlyWhenForced),
        VectorizeOnlyWhenForced(VectorizeOnlyWhenForced) {}

  LoopVectorizeOptions &setInterleaveOnlyWhenForced(bool Value) {
    InterleaveOnlyWhenForced = Value;
    return *this;
  }

  LoopVectorizeOptions &setVectorizeOnlyWhenForced(bool Value) {
    VectorizeOnlyWhenForced = Value;
    return *this;
  }
};

/// The LoopVectorize Pass.
struct LoopVectorizePass : public PassInfoMixin<LoopVectorizePass> {
  /// If false, consider all loops for interleaving.
  /// If true, only loops that explicitly request interleaving are considered.
  bool InterleaveOnlyWhenForced;

  /// If false, consider all loops for vectorization.
  /// If true, only loops that explicitly request vectorization are considered.
  bool VectorizeOnlyWhenForced;

  LoopVectorizePass(LoopVectorizeOptions Opts = {})
      : InterleaveOnlyWhenForced(Opts.InterleaveOnlyWhenForced),
        VectorizeOnlyWhenForced(Opts.VectorizeOnlyWhenForced) {}

  ScalarEvolution *SE;
  LoopInfo *LI;
  TargetTransformInfo *TTI;
  DominatorTree *DT;
  BlockFrequencyInfo *BFI;
  TargetLibraryInfo *TLI;
  DemandedBits *DB;
  AliasAnalysis *AA;
  AssumptionCache *AC;
  std::function<const LoopAccessInfo &(Loop &)> *GetLAA;
  OptimizationRemarkEmitter *ORE;
  ProfileSummaryInfo *PSI;

  PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM);

  // Shim for old PM.
  bool runImpl(Function &F, ScalarEvolution &SE_, LoopInfo &LI_,
               TargetTransformInfo &TTI_, DominatorTree &DT_,
               BlockFrequencyInfo &BFI_, TargetLibraryInfo *TLI_,
               DemandedBits &DB_, AliasAnalysis &AA_, AssumptionCache &AC_,
               std::function<const LoopAccessInfo &(Loop &)> &GetLAA_,
               OptimizationRemarkEmitter &ORE_, ProfileSummaryInfo *PSI_);

  bool processLoop(Loop *L);
};

} // end namespace llvm

#endif // LLVM_TRANSFORMS_VECTORIZE_LOOPVECTORIZE_H