text:
package org.apache.ambari.server.controller.internal;

import static org.easymock.EasyMock.anyObject;
import static org.easymock.EasyMock.capture;
import static org.easymock.EasyMock.createMock;
import static org.easymock.EasyMock.createNiceMock;
import static org.easymock.EasyMock.createStrictMock;
import static org.easymock.EasyMock.expect;
import static org.easymock.EasyMock.expectLastCall;
import static org.easymock.EasyMock.replay;
import static org.easymock.EasyMock.resetToStrict;
import static org.easymock.EasyMock.verify;
import static org.junit.Assert.assertEquals;

import java.io.File;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

import org.apache.ambari.server.controller.AmbariManagementController;
import org.apache.ambari.server.controller.spi.Predicate;
import org.apache.ambari.server.controller.spi.Request;
import org.apache.ambari.server.controller.spi.Resource;
import org.apache.ambari.server.controller.utilities.PredicateBuilder;
import org.apache.ambari.server.controller.utilities.PropertyHelper;
import org.apache.ambari.server.metadata.ActionMetadata;
import org.apache.ambari.server.orm.InMemoryDefaultTestModule;
import org.apache.ambari.server.orm.dao.AlertDefinitionDAO;
import org.apache.ambari.server.orm.entities.AlertDefinitionEntity;
import org.apache.ambari.server.orm.entities.ClusterEntity;
import org.apache.ambari.server.orm.entities.ResourceEntity;
import org.apache.ambari.server.security.TestAuthenticationFactory;
import org.apache.ambari.server.security.authorization.AuthorizationException;
import org.apache.ambari.server.security.authorization.AuthorizationHelperInitializer;
import org.apache.ambari.server.state.Cluster;
import org.apache.ambari.server.state.Clusters;
import org.apache.ambari.server.state.alert.AlertDefinition;
import org.apache.ambari.server.state.alert.AlertDefinitionFactory;
import org.apache.ambari.server.state.alert.AlertDefinitionHash;
import org.apache.ambari.server.state.alert.MetricSource;
import org.apache.ambari.server.state.alert.Scope;
import org.apache.ambari.server.state.alert.Source;
import org.apache.ambari.server.state.alert.SourceType;
import org.easymock.Capture;
import org.easymock.EasyMock;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

import com.google.gson.Gson;
import com.google.inject.Binder;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Module;
import com.google.inject.util.Modules;

/**
 * AlertDefinition tests
 */
public class AlertDefinitionResourceProviderTest {

  private AlertDefinitionDAO dao = null;
  private AlertDefinitionHash definitionHash = null;
  private AlertDefinitionFactory m_factory = new AlertDefinitionFactory();
  private Injector m_injector;

  private static String DEFINITION_UUID = UUID.randomUUID().toString();

  @Before
  public void before() {
    dao = createStrictMock(AlertDefinitionDAO.class);
    definitionHash = createNiceMock(AlertDefinitionHash.class);

    m_injector = Guice.createInjector(Modules.override(
        new InMemoryDefaultTestModule()).with(new MockModule()));

    m_injector.injectMembers(m_factory);
    AuthorizationHelperInitializer.viewInstanceDAOReturningNull();
  }

  @After
  public void clearAuthentication() {
    SecurityContextHolder.getContext().setAuthentication(null);
  }

  /**
   * @throws Exception
   */
  @Test
  public void testGetResourcesNoPredicate() throws Exception {
    AlertDefinitionResourceProvider provider = createProvider(null);

    Request request = PropertyHelper.getReadRequest("AlertDefinition/cluster_name",
        "AlertDefinition/id");

    Set<Resource> results = provider.getResources(request, null);

    assertEquals(0, results.size());
  }

  @Test
  public void testGetResourcesClusterPredicateAsAdministrator() throws Exception {
    testGetResourcesClusterPredicate(TestAuthenticationFactory.createAdministrator(), true);
  }

  @Test
  public void testGetResourcesClusterPredicateAsClusterAdministrator() throws Exception {
    testGetResourcesClusterPredicate(TestAuthenticationFactory.createClusterAdministrator(), true);
  }

  @Test
  public void testGetResourcesClusterPredicateAsServiceAdministrator() throws Exception {
    testGetResourcesClusterPredicate(TestAuthenticationFactory.createServiceAdministrator(), true);
  }

  @Test
  public void testGetResourcesClusterPredicateAsClusterUser() throws Exception {
    testGetResourcesClusterPredicate(TestAuthenticationFactory.createClusterUser(), true);
  }

  @Test
  public void testGetResourcesClusterPredicateAsViewUser() throws Exception {
    testGetResourcesClusterPredicate(TestAuthenticationFactory.createViewUser(99L), false);
  }

  /**
   * @throws Exception
   */
  private void testGetResourcesClusterPredicate(Authentication authentication, boolean expectResults) throws Exception {
    Request request = PropertyHelper.getReadRequest(
        AlertDefinitionResourceProvider.ALERT_DEF_CLUSTER_NAME,
        AlertDefinitionResourceProvider.ALERT_DEF_ID,
        AlertDefinitionResourceProvider.ALERT_DEF_NAME,
        AlertDefinitionResourceProvider.ALERT_DEF_LABEL);

    AmbariManagementController amc = createMock(AmbariManagementController.class);
    Clusters clusters = createMock(Clusters.class);
    Cluster cluster = createMock(Cluster.class);
    expect(amc.getClusters()).andReturn(clusters).atLeastOnce();
    expect(clusters.getCluster((String) anyObject())).andReturn(cluster).atLeastOnce();
    expect(cluster.getClusterId()).andReturn(1L).anyTimes();
    expect(cluster.getResourceId()).andReturn(4L).anyTimes();

    Predicate predicate = new PredicateBuilder().property(
        AlertDefinitionResourceProvider.ALERT_DEF_CLUSTER_NAME).equals("c1").toPredicate();

    expect(dao.findAll(1L)).andReturn(getMockEntities());

    replay(amc, clusters, cluster, dao);

    SecurityContextHolder.getContext().setAuthentication(authentication);

    AlertDefinitionResourceProvider provider = createProvider(amc);
    Set<Resource> results = provider.getResources(request, predicate);

    assertEquals(expectResults ? 1 : 0, results.size());

    if(expectResults) {
      Resource r = results.iterator().next();

      Assert.assertEquals("my_def", r.getPropertyValue(AlertDefinitionResourceProvider.ALERT_DEF_NAME));

      Assert.assertEquals("Mock Label",
          r.getPropertyValue(AlertDefinitionResourceProvider.ALERT_DEF_LABEL));
    }

    verify(amc, clusters, cluster, dao);
  }

  @Test
  public void testGetSingleResourceAsAdministrator() throws Exception {
    testGetSingleResource(TestAuthenticationFactory.createAdministrator());
  }

  @Test
  public void testGetSingleResourceAsClusterAdministrator() throws Exception {
    testGetSingleResource(TestAuthenticationFactory.createClusterAdministrator());
  }

  @Test
  public void testGetSingleResourceAsServiceAdministrator() throws Exception {
    testGetSingleResource(TestAuthenticationFactory.createServiceAdministrator());
  }

  @Test
  public void testGetSingleResourceAsClusterUser() throws Exception {
    testGetSingleResource(TestAuthenticationFactory.createClusterUser());
  }

  @Test(expected = AuthorizationException.class)
  public void testGetSingleResourceAsViewUser() throws Exception {
    testGetSingleResource(TestAuthenticationFactory.createViewUser(99L));
  }

  /**
   * @throws Exception
   */
  private void testGetSingleResource(Authentication authentication) throws Exception {
    Request request = PropertyHelper.getReadRequest(
        AlertDefinitionResourceProvider.ALERT_DEF_CLUSTER_NAME,
        AlertDefinitionResourceProvider.ALERT_DEF_ID,
        AlertDefinitionResourceProvider.ALERT_DEF_NAME,
        AlertDefinitionResourceProvider.ALERT_DEF_LABEL,
        AlertDefinitionResourceProvider.ALERT_DEF_DESCRIPTION,
        AlertDefinitionResourceProvider.ALERT_DEF_IGNORE_HOST,
        AlertDefinitionResourceProvider.ALERT_DEF_SOURCE,
        AlertDefinitionResourceProvider.ALERT_DEF_SOURCE_TYPE,
        AlertDefinitionResourceProvider.ALERT_DEF_HELP_URL);

    AmbariManagementController amc = createMock(AmbariManagementController.class);
    Clusters clusters = createMock(Clusters.class);
    Cluster cluster = createMock(Cluster.class);
    expect(amc.getClusters()).andReturn(clusters).atLeastOnce();
    expect(clusters.getCluster((String) anyObject())).andReturn(cluster).atLeastOnce();
    expect(cluster.getClusterId()).andReturn(Long.valueOf(1)).anyTimes();

    Predicate predicate = new PredicateBuilder().property(
        AlertDefinitionResourceProvider.ALERT_DEF_CLUSTER_NAME).equals("c1")
          .and().property(AlertDefinitionResourceProvider.ALERT_DEF_ID).equals("1").toPredicate();

    expect(dao.findById(1L)).andReturn(getMockEntities().get(0));

    replay(amc, clusters, cluster, dao);

    SecurityContextHolder.getContext().setAuthentication(authentication);

    AlertDefinitionResourceProvider provider = createProvider(amc);
    Set<Resource> results = provider.getResources(request, predicate);

    assertEquals(1, results.size());

    Resource r = results.iterator().next();

    Assert.assertEquals("my_def", r.getPropertyValue(AlertDefinitionResourceProvider.ALERT_DEF_NAME));

    Assert.assertEquals(
        SourceType.METRIC.name(),
        r.getPropertyValue(AlertDefinitionResourceProvider.ALERT_DEF_SOURCE_TYPE));

    Source source = getMockSource();
    String okJson = source.getReporting().getOk().getText();
    Object reporting = r.getPropertyValue("AlertDefinition/source/reporting");

    Assert.assertTrue(reporting.toString().contains(okJson));

    Assert.assertEquals("Mock Label",
        r.getPropertyValue(AlertDefinitionResourceProvider.ALERT_DEF_LABEL));

    Assert.assertEquals(
        "Mock Description",
        r.getPropertyValue(AlertDefinitionResourceProvider.ALERT_DEF_DESCRIPTION));

    Assert.assertEquals(
        Boolean.FALSE,
        r.getPropertyValue(AlertDefinitionResourceProvider.ALERT_DEF_IGNORE_HOST));

    Assert.assertEquals(
            "http://test-help-url",
            r.getPropertyValue(AlertDefinitionResourceProvider.ALERT_DEF_HELP_URL));

    Assert.assertNotNull(r.getPropertyValue("AlertDefinition/source/type"));
  }

  @Test
  public void testGetResourcesAssertSourceTypeAsAdministrator() throws Exception {
    testGetResourcesAssertSourceType(TestAuthenticationFactory.createAdministrator(), true);
  }

  @Test
  public void testGetResourcesAssertSourceTypeAsClusterAdministrator() throws Exception {
    testGetResourcesAssertSourceType(TestAuthenticationFactory.createClusterAdministrator(), true);
  }

  @Test
  public void testGetResourcesAssertSourceTypeAsServiceAdministrator() throws Exception {
    testGetResourcesAssertSourceType(TestAuthenticationFactory.createServiceAdministrator(), true);
  }

  @Test
  public void testGetResourcesAssertSourceTypeAsClusterUser() throws Exception {
    testGetResourcesAssertSourceType(TestAuthenticationFactory.createClusterUser(), true);
  }

  @Test
  public void testGetResourcesAssertSourceTypeAsViewUser() throws Exception {
    testGetResourcesAssertSourceType(TestAuthenticationFactory.createViewUser(99L), false);
  }

/**
   * Tests that the source structure returned has the entire set of
   * subproperties on it (such as reporting)
   *
   * @throws Exception
   */
  private void testGetResourcesAssertSourceType(Authentication authentication, boolean expectResults) throws Exception {
    Request request = PropertyHelper.getReadRequest(
        AlertDefinitionResourceProvider.ALERT_DEF_CLUSTER_NAME,
        AlertDefinitionResourceProvider.ALERT_DEF_ID,
        AlertDefinitionResourceProvider.ALERT_DEF_NAME,
        AlertDefinitionResourceProvider.ALERT_DEF_LABEL,
        AlertDefinitionResourceProvider.ALERT_DEF_DESCRIPTION,
        AlertDefinitionResourceProvider.ALERT_DEF_SOURCE_TYPE);

    AmbariManagementController amc = createMock(AmbariManagementController.class);
    Clusters clusters = createMock(Clusters.class);
    Cluster cluster = createMock(Cluster.class);
    expect(amc.getClusters()).andReturn(clusters).atLeastOnce();
    expect(clusters.getCluster((String) anyObject())).andReturn(cluster).atLeastOnce();
    expect(cluster.getClusterId()).andReturn(1L).anyTimes();
    expect(cluster.getResourceId()).andReturn(4L).anyTimes();

    Predicate predicate = new PredicateBuilder().property(
        AlertDefinitionResourceProvider.ALERT_DEF_CLUSTER_NAME).equals("c1").toPredicate();

    expect(dao.findAll(1L)).andReturn(getMockEntities()).atLeastOnce();

    replay(amc, clusters, cluster, dao);

    SecurityContextHolder.getContext().setAuthentication(authentication);

    AlertDefinitionResourceProvider provider = createProvider(amc);
    Set<Resource> results = provider.getResources(request, predicate);

    assertEquals(expectResults ? 1 : 0, results.size());

    if(expectResults) {
      Resource resource = results.iterator().next();

      Assert.assertEquals("my_def",
          resource.getPropertyValue(AlertDefinitionResourceProvider.ALERT_DEF_NAME));

      Map<?, ?> reporting = (Map<?, ?>) resource.getPropertyValue("AlertDefinition/source/reporting");

      Assert.assertTrue(reporting.containsKey("ok"));
      Assert.assertTrue(reporting.containsKey("critical"));
    }

    verify(amc, clusters, cluster, dao);

    // make another request, this time without the source and ensure that no
    // source properties come back
    request = PropertyHelper.getReadRequest(
        AlertDefinitionResourceProvider.ALERT_DEF_CLUSTER_NAME,
        AlertDefinitionResourceProvider.ALERT_DEF_ID,
        AlertDefinitionResourceProvider.ALERT_DEF_NAME);

    results = provider.getResources(request, predicate);

    if(!results.isEmpty()) {
      Resource resource = results.iterator().next();

      Assert.assertEquals(
          "my_def",
          resource.getPropertyValue(AlertDefinitionResourceProvider.ALERT_DEF_NAME));

      Map<?, ?> reporting = (Map<?, ?>) resource.getPropertyValue("AlertDefinition/source/reporting");

      Assert.assertNull(reporting);
    }
  }

  @Test
  public void testCreateResourcesAsAdministrator() throws Exception {
    testCreateResources(TestAuthenticationFactory.createAdministrator());
  }

  @Test(expected = AuthorizationException.class)
  public void testCreateResourcesAsClusterAdministrator() throws Exception {
    testCreateResources(TestAuthenticationFactory.createClusterAdministrator());
  }

  @Test(expected = AuthorizationException.class)
  public void testCreateResourcesAsServiceAdministrator() throws Exception {
    testCreateResources(TestAuthenticationFactory.createServiceAdministrator());
  }

  @Test(expected = AuthorizationException.class)
  public void testCreateResourcesAsClusterUser() throws Exception {
    testCreateResources(TestAuthenticationFactory.createClusterUser());
  }

  @Test(expected = AuthorizationException.class)
  public void testCreateResourcesAsViewUser() throws Exception {
    testCreateResources(TestAuthenticationFactory.createViewUser(99L));
  }

  /**
   * @throws Exception
   */
  public void testCreateResources(Authentication authentication) throws Exception {
    AmbariManagementController amc = createMock(AmbariManagementController.class);
    Clusters clusters = createMock(Clusters.class);
    Cluster cluster = createMock(Cluster.class);
    expect(amc.getClusters()).andReturn(clusters).atLeastOnce();
    expect(clusters.getCluster((String) anyObject())).andReturn(cluster).atLeastOnce();
    expect(cluster.getClusterId()).andReturn(Long.valueOf(1)).anyTimes();

    Capture<AlertDefinitionEntity> entityCapture = EasyMock.newCapture();
    dao.create(capture(entityCapture));
    expectLastCall();

    // creating a single definition should invalidate hosts of the definition
    expect(
        definitionHash.invalidateHosts(EasyMock.anyObject(AlertDefinitionEntity.class))).andReturn(
      new HashSet<>()).once();

    replay(amc, clusters, cluster, dao, definitionHash);

    SecurityContextHolder.getContext().setAuthentication(authentication);

    Gson gson = m_factory.getGson();
    MetricSource source = (MetricSource)getMockSource();
    AlertDefinitionResourceProvider provider = createProvider(amc);

    Map<String, Object> requestProps = new HashMap<>();
    requestProps.put(AlertDefinitionResourceProvider.ALERT_DEF_CLUSTER_NAME, "c1");
    requestProps.put(AlertDefinitionResourceProvider.ALERT_DEF_INTERVAL, "1");
    requestProps.put(AlertDefinitionResourceProvider.ALERT_DEF_NAME, "my_def");

    requestProps.put(AlertDefinitionResourceProvider.ALERT_DEF_SERVICE_NAME,
        "HDFS");

    requestProps.put(AlertDefinitionResourceProvider.ALERT_DEF_LABEL,
        "Mock Label (Create)");

    requestProps.put(AlertDefinitionResourceProvider.ALERT_DEF_DESCRIPTION,
        "Mock Description (Create)");

    requestProps.put(AlertDefinitionResourceProvider.ALERT_DEF_SOURCE_TYPE,
        SourceType.METRIC.name());

    // JMX
    requestProps.put("AlertDefinition/source/jmx/value",
        source.getJmxInfo().getValue());
    requestProps.put("AlertDefinition/source/jmx/property_list",
        source.getJmxInfo().getPropertyList());

    // URI
    requestProps.put("AlertDefinition/source/uri/http",
        source.getUri().getHttpUri());
    requestProps.put("AlertDefinition/source/uri/https",
        source.getUri().getHttpsUri());
    requestProps.put("AlertDefinition/source/uri/https_property",
        source.getUri().getHttpsProperty());
    requestProps.put("AlertDefinition/source/uri/https_property_value",
        source.getUri().getHttpsPropertyValue());

    // reporting
    requestProps.put("AlertDefinition/source/reporting/critical/text",
        source.getReporting().getCritical().getText());
    requestProps.put("AlertDefinition/source/reporting/critical/value",
        source.getReporting().getCritical().getValue());
    requestProps.put("AlertDefinition/source/reporting/ok/text",
        source.getReporting().getOk().getText());
    requestProps.put("AlertDefinition/source/reporting/warning/text",
        source.getReporting().getWarning().getText());
    requestProps.put("AlertDefinition/source/reporting/warning/value",
        source.getReporting().getWarning().getValue());
    requestProps.put("AlertDefinition/source/reporting/units", "Gigabytes");

    Request request = PropertyHelper.getCreateRequest(Collections.singleton(requestProps), null);
    provider.createResources(request);

    Assert.assertTrue(entityCapture.hasCaptured());
    AlertDefinitionEntity entity = entityCapture.getValue();
    Assert.assertNotNull(entity);

    Assert.assertEquals(Long.valueOf(1), entity.getClusterId());
    Assert.assertNull(entity.getComponentName());
    Assert.assertEquals("my_def", entity.getDefinitionName());
    Assert.assertTrue(entity.getEnabled());
    Assert.assertNotNull(entity.getHash());
    Assert.assertEquals(Integer.valueOf(1), entity.getScheduleInterval());
    Assert.assertEquals(Scope.ANY, entity.getScope());
    Assert.assertEquals("HDFS", entity.getServiceName());
    Assert.assertEquals(SourceType.METRIC, entity.getSourceType());
    Assert.assertEquals("Mock Label (Create)", entity.getLabel());
    Assert.assertEquals("Mock Description (Create)", entity.getDescription());
    Assert.assertEquals(false, entity.isHostIgnored());

    // verify Source
    Assert.assertNotNull(entity.getSource());
    MetricSource actualSource = gson.fromJson(entity.getSource(),
        MetricSource.class);

    Assert.assertNotNull(actualSource);

    assertEquals(source.getReporting().getOk().getText(),
        actualSource.getReporting().getOk().getText());

    assertEquals(source.getReporting().getWarning().getText(),
        actualSource.getReporting().getWarning().getText());

    assertEquals(source.getReporting().getCritical().getText(),
        actualSource.getReporting().getCritical().getText());

    assertEquals("Gigabytes", actualSource.getReporting().getUnits());

    Assert.assertNotNull(source.getUri().getHttpUri());
    Assert.assertNotNull(source.getUri().getHttpsUri());

    assertEquals(source.getUri().getHttpUri(),
        actualSource.getUri().getHttpUri());

    assertEquals(source.getUri().getHttpsUri(),
        actualSource.getUri().getHttpsUri());

    verify(amc, clusters, cluster, dao);
  }

  @Test
  public void testUpdateResourcesAsAdministrator() throws Exception {
    testUpdateResources(TestAuthenticationFactory.createAdministrator());
  }

  @Test(expected = AuthorizationException.class)
  public void testUpdateResourcesAsClusterAdministrator() throws Exception {
    testUpdateResources(TestAuthenticationFactory.createClusterAdministrator());
  }

  @Test(expected = AuthorizationException.class)
  public void testUpdateResourcesAsServiceAdministrator() throws Exception {
    testUpdateResources(TestAuthenticationFactory.createServiceAdministrator());
  }

  @Test(expected = AuthorizationException.class)
  public void testUpdateResourcesAsClusterUser() throws Exception {
    testUpdateResources(TestAuthenticationFactory.createClusterUser());
  }

  @Test(expected = AuthorizationException.class)
  public void testUpdateResourcesAsViewUser() throws Exception {
    testUpdateResources(TestAuthenticationFactory.createViewUser(99L));
  }

  /**
   * @throws Exception
   */
  private void testUpdateResources(Authentication authentication) throws Exception {
    AmbariManagementController amc = createMock(AmbariManagementController.class);
    Clusters clusters = createMock(Clusters.class);
    Cluster cluster = createMock(Cluster.class);
    expect(amc.getClusters()).andReturn(clusters).atLeastOnce();
    expect(clusters.getCluster((String) anyObject())).andReturn(cluster).atLeastOnce();
    expect(cluster.getClusterId()).andReturn(Long.valueOf(1)).atLeastOnce();

    Capture<AlertDefinitionEntity> entityCapture = EasyMock.newCapture();
    dao.create(capture(entityCapture));
    expectLastCall();

    // updateing a single definition should invalidate hosts of the definition
    expect(
        definitionHash.invalidateHosts(EasyMock.anyObject(AlertDefinitionEntity.class))).andReturn(
      new HashSet<>()).atLeastOnce();

    replay(amc, clusters, cluster, dao, definitionHash);

    SecurityContextHolder.getContext().setAuthentication(authentication);

    MetricSource source = (MetricSource) getMockSource();

    Map<String, Object> requestProps = new HashMap<>();
    requestProps.put(AlertDefinitionResourceProvider.ALERT_DEF_CLUSTER_NAME, "c1");
    requestProps.put(AlertDefinitionResourceProvider.ALERT_DEF_INTERVAL, "1");
    requestProps.put(AlertDefinitionResourceProvider.ALERT_DEF_NAME, "my_def");
    requestProps.put(AlertDefinitionResourceProvider.ALERT_DEF_LABEL, "Label");
    requestProps.put(AlertDefinitionResourceProvider.ALERT_DEF_DESCRIPTION,"Description");
    requestProps.put(AlertDefinitionResourceProvider.ALERT_DEF_SERVICE_NAME, "HDFS");
    requestProps.put(AlertDefinitionResourceProvider.ALERT_DEF_SOURCE_TYPE, "METRIC");

    requestProps.put(AlertDefinitionResourceProvider.ALERT_DEF_ENABLED,
        Boolean.TRUE.toString());

    // JMX
    requestProps.put("AlertDefinition/source/jmx/value",
        source.getJmxInfo().getValue());
    requestProps.put("AlertDefinition/source/jmx/property_list",
        source.getJmxInfo().getPropertyList());

    // URI
    requestProps.put("AlertDefinition/source/uri/http",
        source.getUri().getHttpUri());
    requestProps.put("AlertDefinition/source/uri/https",
        source.getUri().getHttpsUri());
    requestProps.put("AlertDefinition/source/uri/https_property",
        source.getUri().getHttpsProperty());
    requestProps.put("AlertDefinition/source/uri/https_property_value",
        source.getUri().getHttpsPropertyValue());

    // reporting
    requestProps.put("AlertDefinition/source/reporting/critical/text",
        source.getReporting().getCritical().getText());
    requestProps.put("AlertDefinition/source/reporting/critical/value",
        source.getReporting().getCritical().getValue());
    requestProps.put("AlertDefinition/source/reporting/ok/text",
        source.getReporting().getOk().getText());
    requestProps.put("AlertDefinition/source/reporting/warning/text",
        source.getReporting().getWarning().getText());
    requestProps.put("AlertDefinition/source/reporting/warning/value",
        source.getReporting().getWarning().getValue());

    Request request = PropertyHelper.getCreateRequest(Collections.singleton(requestProps), null);

    AlertDefinitionResourceProvider provider = createProvider(amc);

    provider.createResources(request);

    Assert.assertTrue(entityCapture.hasCaptured());
    AlertDefinitionEntity entity = entityCapture.getValue();
    Assert.assertNotNull(entity);

    Predicate p = new PredicateBuilder().property(AlertDefinitionResourceProvider.ALERT_DEF_ID).equals(
        "1").and().property(AlertDefinitionResourceProvider.ALERT_DEF_CLUSTER_NAME).equals("c1").toPredicate();

    // everything is mocked, there is no DB
    entity.setDefinitionId(Long.valueOf(1));

    String oldName = entity.getDefinitionName();
    String oldHash = entity.getHash();
    Integer oldInterval = entity.getScheduleInterval();
    boolean oldEnabled = entity.getEnabled();
    boolean oldHostIgnore = entity.isHostIgnored();
    String oldSource = entity.getSource();
    String oldDescription = entity.getDescription();

    resetToStrict(dao);
    expect(dao.findById(1L)).andReturn(entity).anyTimes();
    expect(dao.merge((AlertDefinitionEntity) anyObject())).andReturn(entity).anyTimes();
    replay(dao);

    requestProps = new HashMap<>();
    requestProps.put(AlertDefinitionResourceProvider.ALERT_DEF_ID, "1");
    requestProps.put(AlertDefinitionResourceProvider.ALERT_DEF_CLUSTER_NAME, "c1");
    requestProps.put(AlertDefinitionResourceProvider.ALERT_DEF_INTERVAL, "2");
    requestProps.put(AlertDefinitionResourceProvider.ALERT_DEF_NAME, "my_def2");
    requestProps.put(AlertDefinitionResourceProvider.ALERT_DEF_LABEL, "Label 2");
    requestProps.put(AlertDefinitionResourceProvider.ALERT_DEF_DESCRIPTION, "Description 2");
    requestProps.put(AlertDefinitionResourceProvider.ALERT_DEF_SERVICE_NAME, "HDFS");
    requestProps.put(AlertDefinitionResourceProvider.ALERT_DEF_SOURCE_TYPE, "METRIC");

    // new URI
    requestProps.put("AlertDefinition/source/uri/http", source.getUri().getHttpUri() + "_foobarbaz");
    requestProps.put("AlertDefinition/source/uri/https", source.getUri().getHttpsUri()
        + "_foobarbaz");
    requestProps.put("AlertDefinition/source/uri/https_property",
        source.getUri().getHttpsProperty() + "_foobarbaz");
    requestProps.put("AlertDefinition/source/uri/https_property_value",
        source.getUri().getHttpsPropertyValue() + "_foobarbaz");

    requestProps.put(AlertDefinitionResourceProvider.ALERT_DEF_ENABLED, Boolean.FALSE.toString());

    requestProps.put(AlertDefinitionResourceProvider.ALERT_DEF_IGNORE_HOST, Boolean.TRUE.toString());

    request = PropertyHelper.getUpdateRequest(requestProps, null);

    provider.updateResources(request, p);

    Assert.assertFalse(oldHash.equals(entity.getHash()));
    Assert.assertFalse(oldName.equals(entity.getDefinitionName()));
    Assert.assertFalse(oldDescription.equals(entity.getDescription()));
    Assert.assertFalse(oldInterval.equals(entity.getScheduleInterval()));
    Assert.assertFalse(oldEnabled == entity.getEnabled());
    Assert.assertFalse(oldHostIgnore == entity.isHostIgnored());
    Assert.assertFalse(oldSource.equals(entity.getSource()));
    Assert.assertTrue(entity.getSource().contains("_foobarbaz"));

    verify(amc, clusters, cluster, dao);
  }

  /**
   * @throws Exception
   */
  @Test
  public void testUpdateResourcesWithNumbersAsStrings() throws Exception {
    AmbariManagementController amc = createMock(AmbariManagementController.class);
    Clusters clusters = createMock(Clusters.class);
    Cluster cluster = createMock(Cluster.class);
    expect(amc.getClusters()).andReturn(clusters).atLeastOnce();
    expect(clusters.getCluster((String) anyObject())).andReturn(cluster).atLeastOnce();
    expect(cluster.getClusterId()).andReturn(Long.valueOf(1)).atLeastOnce();

    Capture<AlertDefinitionEntity> entityCapture = EasyMock.newCapture();
    dao.create(capture(entityCapture));
    expectLastCall();

    // updateing a single definition should invalidate hosts of the definition
    expect(definitionHash.invalidateHosts(EasyMock.anyObject(AlertDefinitionEntity.class))).andReturn(
      new HashSet<>()).atLeastOnce();

    replay(amc, clusters, cluster, dao, definitionHash);

    SecurityContextHolder.getContext().setAuthentication(TestAuthenticationFactory.createAdministrator());

    MetricSource source = (MetricSource) getMockSource();
    Map<String, Object> requestProps = new HashMap<>();
    requestProps.put(AlertDefinitionResourceProvider.ALERT_DEF_CLUSTER_NAME, "c1");
    requestProps.put(AlertDefinitionResourceProvider.ALERT_DEF_INTERVAL, "1");
    requestProps.put(AlertDefinitionResourceProvider.ALERT_DEF_NAME, "my_def");
    requestProps.put(AlertDefinitionResourceProvider.ALERT_DEF_SERVICE_NAME, "HDFS");
    requestProps.put(AlertDefinitionResourceProvider.ALERT_DEF_SOURCE_TYPE, "METRIC");

    // Ambari converts all request bodies into Map<String,String>, even they are
    // numbers - this will ensure that we can convert a string to a number
    // properly
    requestProps.put("AlertDefinition/source/reporting/critical/text",
        source.getReporting().getCritical().getText());

    requestProps.put("AlertDefinition/source/reporting/critical/value", "1234.5");

    Request request = PropertyHelper.getCreateRequest(
        Collections.singleton(requestProps), null);

    AlertDefinitionResourceProvider provider = createProvider(amc);
    provider.createResources(request);

    Assert.assertTrue(entityCapture.hasCaptured());
    AlertDefinitionEntity entity = entityCapture.getValue();
    Assert.assertNotNull(entity);

    String sourceJson = entity.getSource();
    Gson gson = new Gson();
    source = gson.fromJson(sourceJson, MetricSource.class);

    // ensure it's actually a double and NOT a string
    assertEquals(new Double(1234.5d), source.getReporting().getCritical().getValue());
    verify(amc, clusters, cluster, dao);
  }

  @Test
  public void testDeleteResourcesAsAdministrator() throws Exception {
    testDeleteResources(TestAuthenticationFactory.createAdministrator());
  }

  @Test(expected = AuthorizationException.class)
  public void testDeleteResourcesAsClusterAdministrator() throws Exception {
    testDeleteResources(TestAuthenticationFactory.createClusterAdministrator());
  }

  @Test(expected = AuthorizationException.class)
  public void testDeleteResourcesAsServiceAdministrator() throws Exception {
    testDeleteResources(TestAuthenticationFactory.createServiceAdministrator());
  }

  @Test(expected = AuthorizationException.class)
  public void testDeleteResourcesAsClusterUser() throws Exception {
    testDeleteResources(TestAuthenticationFactory.createClusterUser());
  }

  @Test(expected = AuthorizationException.class)
  public void testDeleteResourcesAsViewUser() throws Exception {
    testDeleteResources(TestAuthenticationFactory.createViewUser(99L));
  }

  /**
   * @throws Exception
   */
  public void testDeleteResources(Authentication authentication) throws Exception {
    AmbariManagementController amc = createMock(AmbariManagementController.class);
    Clusters clusters = createMock(Clusters.class);
    Cluster cluster = createMock(Cluster.class);
    expect(amc.getClusters()).andReturn(clusters).atLeastOnce();
    expect(clusters.getCluster((String) anyObject())).andReturn(cluster).atLeastOnce();
    expect(cluster.getClusterId()).andReturn(Long.valueOf(1)).anyTimes();

    Capture<AlertDefinitionEntity> entityCapture = EasyMock.newCapture();
    dao.create(capture(entityCapture));
    expectLastCall();

    // deleting a single definition should invalidate hosts of the definition
    expect(
        definitionHash.invalidateHosts(EasyMock.anyObject(AlertDefinitionEntity.class))).andReturn(
      new HashSet<>()).atLeastOnce();

    replay(amc, clusters, cluster, dao, definitionHash);

    SecurityContextHolder.getContext().setAuthentication(authentication);

    AlertDefinitionResourceProvider provider = createProvider(amc);

    Map<String, Object> requestProps = new HashMap<>();
    requestProps.put(AlertDefinitionResourceProvider.ALERT_DEF_CLUSTER_NAME, "c1");
    requestProps.put(AlertDefinitionResourceProvider.ALERT_DEF_INTERVAL, "1");
    requestProps.put(AlertDefinitionResourceProvider.ALERT_DEF_NAME, "my_def");
    requestProps.put(AlertDefinitionResourceProvider.ALERT_DEF_SERVICE_NAME, "HDFS");
    requestProps.put(AlertDefinitionResourceProvider.ALERT_DEF_SOURCE_TYPE, "METRIC");

    Request request = PropertyHelper.getCreateRequest(Collections.singleton(requestProps), null);

    provider.createResources(request);

    Assert.assertTrue(entityCapture.hasCaptured());
    AlertDefinitionEntity entity = entityCapture.getValue();
    Assert.assertNotNull(entity);

    Predicate p = new PredicateBuilder().property(
        AlertDefinitionResourceProvider.ALERT_DEF_ID).equals("1").and().property(
            AlertDefinitionResourceProvider.ALERT_DEF_CLUSTER_NAME).equals("c1").toPredicate();
    // everything is mocked, there is no DB
    entity.setDefinitionId(Long.valueOf(1));

    resetToStrict(dao);
    expect(dao.findById(1L)).andReturn(entity).anyTimes();
    dao.remove(capture(entityCapture));
    expectLastCall();
    replay(dao);

    provider.deleteResources(new RequestImpl(null, null, null, null), p);

    AlertDefinitionEntity entity1 = entityCapture.getValue();
    Assert.assertEquals(Long.valueOf(1), entity1.getDefinitionId());

    verify(amc, clusters, cluster, dao);
  }

  /**
   * @param amc
   * @return
   */
  private AlertDefinitionResourceProvider createProvider(AmbariManagementController amc) {
    return new AlertDefinitionResourceProvider(amc);
  }

  /**
   * @return
   */
  private List<AlertDefinitionEntity> getMockEntities() throws Exception {
    Source source = getMockSource();
    String sourceJson = new Gson().toJson(source);

    ResourceEntity clusterResourceEntity = new ResourceEntity();
    clusterResourceEntity.setId(4L);

    ClusterEntity clusterEntity = new ClusterEntity();
    clusterEntity.setResource(clusterResourceEntity);

    AlertDefinitionEntity entity = new AlertDefinitionEntity();
    entity.setClusterId(Long.valueOf(1L));
    entity.setComponentName(null);
    entity.setDefinitionId(Long.valueOf(1L));
    entity.setDefinitionName("my_def");
    entity.setLabel("Mock Label");
    entity.setDescription("Mock Description");
    entity.setEnabled(true);
    entity.setHash(DEFINITION_UUID);
    entity.setScheduleInterval(Integer.valueOf(2));
    entity.setServiceName(null);
    entity.setSourceType(SourceType.METRIC);
    entity.setSource(sourceJson);
    entity.setCluster(clusterEntity);
    entity.setHelpURL("http://test-help-url");
    return Arrays.asList(entity);
  }

  /**
   * @return
   */
  private Source getMockSource() throws Exception {
    File alertsFile = new File(
        "src/test/resources/stacks/HDP/2.0.5/services/HDFS/alerts.json");

    Assert.assertTrue(alertsFile.exists());

    Set<AlertDefinition> set = m_factory.getAlertDefinitions(alertsFile, "HDFS");
    AlertDefinition nameNodeCpu = null;
    Iterator<AlertDefinition> definitions = set.iterator();
    while (definitions.hasNext()) {
      AlertDefinition definition = definitions.next();

      if (definition.getName().equals("namenode_cpu")) {
        nameNodeCpu = definition;
      }
    }

    Assert.assertNotNull(nameNodeCpu.getSource());
    return nameNodeCpu.getSource();
  }

  /**
  *
  */
  private class MockModule implements Module {
    /**
    *
    */
    @Override
    public void configure(Binder binder) {
      binder.bind(AlertDefinitionDAO.class).toInstance(dao);
      binder.bind(AlertDefinitionHash.class).toInstance(definitionHash);
      binder.bind(Clusters.class).toInstance(
          EasyMock.createNiceMock(Clusters.class));
      binder.bind(Cluster.class).toInstance(
          EasyMock.createNiceMock(Cluster.class));
      binder.bind(ActionMetadata.class);
    }
  }
}


text:
import unittest
from test import test_pyquat, test_random
from test import test_wahba_esoq, test_wahba_valenti

def pyquat_test_suite():
    """
    Load unit tests from each file for automatic running using
    `python setup.py test`.
    """
    loader = unittest.TestLoader()
    suite  = unittest.TestSuite()
    suite.addTests(loader.loadTestsFromModule(test_pyquat))
    suite.addTests(loader.loadTestsFromModule(test_random))
    suite.addTests(loader.loadTestsFromModule(test_wahba_esoq))
    suite.addTests(loader.loadTestsFromModule(test_wahba_valenti))

    return suite

redpajama_set_name: RedPajamaGithub


text:
"""Version-agnostic abstractions around FHIR primitive datatypes."""

import abc
from typing import Any, List, Optional, Type, cast

from google.protobuf import message
from google.fhir.core.internal import _primitive_time_utils
from google.fhir.core.internal.json_format.wrappers import _primitive_wrappers

class PrimitiveHandler(abc.ABC):
  """An abstract base class to return FHIR primitive wrappers."""

  @property
  @abc.abstractmethod
  def base64_binary_cls(self) -> Type[message.Message]:
    """A stream of bytes, base64 encoded (https://tools.ietf.org/html/rfc4648).

    See more at: https://www.hl7.org/fhir/datatypes.html#base64Binary.
    """
    raise NotImplementedError('Subclasses *must* implement base64_binary_cls.')

  @property
  @abc.abstractmethod
  def boolean_cls(self) -> Type[message.Message]:
    """true | false.

    See more at: https://www.hl7.org/fhir/datatypes.html#boolean.
    """
    raise NotImplementedError('Subclasses *must* implement boolean_cls.')

  @property
  def canonical_cls(self) -> Type[message.Message]:
    """A URI that refers to a resource by its canonical URL.

    See more at: https://www.hl7.org/fhir/datatypes.html#canonical.

    Returns:
      A FHIR R4 Canonical primitive class.
    """
    raise NotImplementedError('Subclasses *must* implement canonical_cls.')

  @property
  @abc.abstractmethod
  def code_cls(self) -> Type[message.Message]:
    """A value taken from a set of controlled strings defined elsewhere.

    See more at: https://www.hl7.org/fhir/datatypes.html#code.
    """
    raise NotImplementedError('Subclasses *must* implement code_cls.')

  # TODO(b/163349112): Find more appropriate location for contained_resource_cls
  @property
  @abc.abstractmethod
  def contained_resource_cls(self) -> Type[message.Message]:
    """A reference to a resource associated with some record.

    The contained resource is a reference to content that does not have an
    independent existence apart from the resource that contains it. It cannot
    be identified independently, nor can it have its own independent transaction
    scope.

    See more at: https://www.hl7.org/fhir/references.html#contained.
    """
    raise NotImplementedError(
        'Subclasses *must* implement contained_resource_cls.')

  @property
  @abc.abstractmethod
  def date_cls(self) -> Type[message.Message]:
    """A date, or partial date.

    See more at: https://www.hl7.org/fhir/datatypes.html#date.
    """
    raise NotImplementedError('Subclasses *must* implement date_cls.')

  @property
  @abc.abstractmethod
  def date_time_cls(self) -> Type[message.Message]:
    """A date, date-time, or partial date.

    See more at: https://www.hl7.org/fhir/datatypes.html#datetime.
    """
    raise NotImplementedError('Subclasses *must* implement date_time_cls.')

  @property
  @abc.abstractmethod
  def decimal_cls(self) -> Type[message.Message]:
    """Rational numbers that have a decimal representation.

    See more at: https://www.hl7.org/fhir/datatypes.html#decimal.
    """
    raise NotImplementedError('Subclasses *must* implement decimal_cls.')

  @property
  @abc.abstractmethod
  def id_cls(self) -> Type[message.Message]:
    """64 character alphanumeric identifier with '-' and '.' allowed.

    See more at: https://www.hl7.org/fhir/datatypes.html#id.
    """
    raise NotImplementedError('Subclasses *must* implement id_cls.')

  @property
  @abc.abstractmethod
  def instant_cls(self) -> Type[message.Message]:
    """An instant in time.

    See more at: https://www.hl7.org/fhir/datatypes.html#instant.
    """
    raise NotImplementedError('Subclasses *must* implement instant_cls.')

  @property
  @abc.abstractmethod
  def integer_cls(self) -> Type[message.Message]:
    """A signed 32-bit integer.

    See more at: https://www.hl7.org/fhir/datatypes.html#integer.
    """
    raise NotImplementedError('Subclasses *must* implement integer_cls.')

  @property
  @abc.abstractmethod
  def markdown_cls(self) -> Type[message.Message]:
    """A FHIR String that may contain markdown syntax for optional processing.

    See more at: https://www.hl7.org/fhir/datatypes.html#markdown.
    """
    raise NotImplementedError('Subclasses *must* implement markdown_cls.')

  @property
  @abc.abstractmethod
  def oid_cls(self) -> Type[message.Message]:
    """An OID represented as a URI (https://www.ietf.org/rfc/rfc3001.txt).

    See more at: https://www.hl7.org/fhir/datatypes.html#oid.
    """
    raise NotImplementedError('Subclasses *must* implement oid_cls.')

  @property
  @abc.abstractmethod
  def positive_int_cls(self) -> Type[message.Message]:
    """An unsigned 32-bit integer.

    See more at: https://www.hl7.org/fhir/datatypes.html#positiveInt.
    """
    raise NotImplementedError('Subclasses *must* implement positive_int_cls.')

  @property
  @abc.abstractmethod
  def string_cls(self) -> Type[message.Message]:
    """A sequence of Unicode characters.

    See more at: https://www.hl7.org/fhir/datatypes.html#string.
    """
    raise NotImplementedError('Subclasses *must* implement string_cls.')

  @property
  @abc.abstractmethod
  def time_cls(self) -> Type[message.Message]:
    """A time during the day.

    See more at: https://www.hl7.org/fhir/datatypes.html#time.
    """
    raise NotImplementedError('Subclasses *must* implement time_cls.')

  @property
  @abc.abstractmethod
  def unsigned_int_cls(self) -> Type[message.Message]:
    """An unsigned 32-bit integer.

    See more at: https://www.hl7.org/fhir/datatypes.html#unsignedInt.
    """
    raise NotImplementedError('Subclasses *must* implement unsigned_int_cls.')

  @property
  @abc.abstractmethod
  def uri_cls(self) -> Type[message.Message]:
    """A Uniform Resource Identifier (https://tools.ietf.org/html/rfc3986).

    See more at: https://www.hl7.org/fhir/datatypes.html#uri.
    """
    raise NotImplementedError('Subclasses *must* implement uri_cls.')

  @property
  @abc.abstractmethod
  def url_cls(self) -> Type[message.Message]:
    """A Uniform Resource Locator (https://tools.ietf.org/html/rfc1738).

    See more at: https://www.hl7.org/fhir/datatypes.html#url.

    Returns:
      A FHIR R4 URL primitive class.
    """
    raise NotImplementedError('Subclasses *must* implement url_cls.')

  @property
  @abc.abstractmethod
  def uuid_cls(self) -> Type[message.Message]:
    """A UUID represented as a URI.

    See more at: https://www.hl7.org/fhir/datatypes.html#uuid.

    Returns:
      A FHIR R4 UUID primitive class.
    """
    raise NotImplementedError('Subclasses *must* implement uuid_cls.')

  @property
  @abc.abstractmethod
  def xhtml_cls(self) -> Type[message.Message]:
    """XHTML content."""
    raise NotImplementedError('Subclasses *must* implement xhtml_cls.')

  @abc.abstractmethod
  def get_primitive_wrapper_cls_for_primitive_cls(
      self, primitive_cls: Type[message.Message]
  ) -> Type[_primitive_wrappers.PrimitiveWrapper]:
    """Returns the primitive wrapper for the corresponding primitive_cls.

    Subclasses should override and provide logic to return their own wrappers
    for primitives specific to a particular version of FHIR. The base
    implementation provides handling for all primitives included in FHIR version
    >= stu3.

    Args:
      primitive_cls: The type of primitive for which to return a wrapper.

    Returns:
      A PrimitiveWrapper for parsing/printing types of primitive_cls.
    """
    raise NotImplementedError('Subclasses *must* implement '
                              'get_primitive_wrapper_cls_for_primitive_cls.')

  def new_base64_binary(
      self,
      value: bytes = b'',
      id_: Optional[message.Message] = None,
      extension: Optional[List[message.Message]] = None) -> message.Message:
    return cast(Any, self.base64_binary_cls)(
        value=value, id=id_, extension=extension)

  def new_boolean(
      self,
      value: bool = False,
      id_: Optional[message.Message] = None,
      extension: Optional[List[message.Message]] = None) -> message.Message:
    return cast(Any, self.boolean_cls)(value=value, id=id_, extension=extension)

  def new_canonical(
      self,
      value: str = '',
      id_: Optional[message.Message] = None,
      extension: Optional[List[message.Message]] = None) -> message.Message:
    return cast(Any, self.canonical_cls)(
        value=value, id=id_, extension=extension)

  def new_code(
      self,
      value: str = '',
      id_: Optional[message.Message] = None,
      extension: Optional[List[message.Message]] = None) -> message.Message:
    return cast(Any, self.code_cls)(value=value, id=id_, extension=extension)

  def new_contained_resource(self) -> message.Message:
    return self.contained_resource_cls()

  def new_date(
      self,
      value_us: int = 0,
      timezone: str = '',
      precision: int = 0,
      id_: Optional[message.Message] = None,
      extension: Optional[List[message.Message]] = None) -> message.Message:
    return cast(Any, self.date_cls)(
        value_us=value_us,
        timezone=timezone,
        precision=precision,
        id=id_,
        extension=extension)

  def new_date_time(
      self,
      value_us: int = 0,
      timezone: str = '',
      precision: int = 0,
      id_: Optional[message.Message] = None,
      extension: Optional[List[message.Message]] = None) -> message.Message:
    return cast(Any, self.date_time_cls)(
        value_us=value_us,
        timezone=timezone,
        precision=precision,
        id=id_,
        extension=extension)

  def new_decimal(
      self,
      value: str = '',
      id_: Optional[message.Message] = None,
      extension: Optional[List[message.Message]] = None) -> message.Message:
    return cast(Any, self.decimal_cls)(value=value, id=id_, extension=extension)

  def new_id(
      self,
      value: str = '',
      id_: Optional[message.Message] = None,
      extension: Optional[List[message.Message]] = None) -> message.Message:
    return cast(Any, self.id_cls)(value=value, id=id_, extension=extension)

  def new_instant(
      self,
      value_us: int = 0,
      timezone: str = '',
      precision: int = 0,
      id_: Optional[message.Message] = None,
      extension: Optional[List[message.Message]] = None) -> message.Message:
    return cast(Any, self.instant_cls)(
        value_us=value_us,
        timezone=timezone,
        precision=precision,
        id=id_,
        extension=extension)

  def new_integer(
      self,
      value: int = 0,
      id_: Optional[message.Message] = None,
      extension: Optional[List[message.Message]] = None) -> message.Message:
    return cast(Any, self.integer_cls)(value=value, id=id_, extension=extension)

  def new_markdown(
      self,
      value: str = '',
      id_: Optional[message.Message] = None,
      extension: Optional[List[message.Message]] = None) -> message.Message:
    return cast(Any, self.markdown_cls)(
        value=value, id=id_, extension=extension)

  def new_oid(
      self,
      value: str = '',
      id_: Optional[message.Message] = None,
      extension: Optional[List[message.Message]] = None) -> message.Message:
    return cast(Any, self.oid_cls)(value=value, id=id_, extension=extension)

  def new_positive_int(
      self,
      value: int = 0,
      id_: Optional[message.Message] = None,
      extension: Optional[List[message.Message]] = None) -> message.Message:
    return cast(Any, self.positive_int_cls)(
        value=value, id=id_, extension=extension)

  def new_string(
      self,
      value: str = '',
      id_: Optional[message.Message] = None,
      extension: Optional[List[message.Message]] = None) -> message.Message:
    return cast(Any, self.string_cls)(value=value, id=id_, extension=extension)

  def new_time(
      self,
      value_us: int = 0,
      precision: int = 0,
      id_: Optional[message.Message] = None,
      extension: Optional[List[message.Message]] = None) -> message.Message:
    return cast(Any, self.time_cls)(
        value_us=value_us, precision=precision, id=id_, extension=extension)

  def new_unsigned_int(
      self,
      value: int = 0,
      id_: Optional[message.Message] = None,
      extension: Optional[List[message.Message]] = None) -> message.Message:
    return cast(Any, self.unsigned_int_cls)(
        value=value, id=id_, extension=extension)

  def new_uri(
      self,
      value: str = '',
      id_: Optional[message.Message] = None,
      extension: Optional[List[message.Message]] = None) -> message.Message:
    return cast(Any, self.uri_cls)(value=value, id=id_, extension=extension)

  def new_url(
      self,
      value: str = '',
      id_: Optional[message.Message] = None,
      extension: Optional[List[message.Message]] = None) -> message.Message:
    return cast(Any, self.url_cls)(value=value, id=id_, extension=extension)

  def new_uuid(
      self,
      value: str = '',
      id_: Optional[message.Message] = None,
      extension: Optional[List[message.Message]] = None) -> message.Message:
    return cast(Any, self.uuid_cls)(value=value, id=id_, extension=extension)

  def new_xhtml(
      self,
      value: str = '',
      id_: Optional[message.Message] = None,
  ) -> message.Message:
    return cast(Any, self.xhtml_cls)(value=value, id=id_)

  @abc.abstractmethod
  def primitive_wrapper_from_primitive(
      self, primitive_message: message.Message
  ) -> _primitive_wrappers.PrimitiveWrapper:
    """Wraps the FHIR protobuf primitive_message to handle parsing/printing.

    The wrapped FHIR protobuf primitive provides necessary state for printing
    to the FHIR JSON spec.

    Args:
      primitive_message: The FHIR primitive to wrap.

    Raises:
      ValueError: In the event that primitive_message is not actually a
      primitive FHIR type.

    Returns: A wrapper around primitive_message.
    """
    raise NotImplementedError(
        'Subclasses *must* implement primitive_wrapper_from_primitive.')

  @abc.abstractmethod
  def primitive_wrapper_from_json_value(
      self,
      json_value: Optional[Any],
      primitive_cls: Type[message.Message],
      *,
      default_timezone: str = _primitive_time_utils.SIMPLE_ZULU
  ) -> _primitive_wrappers.PrimitiveWrapper:
    """Parses json_value into a FHIR protobuf primitive and wraps.

    The wrapper provides necessary information on how to parse json_value into
    a corresponding FHIR protobuf message. Afterwards, this is wrapped to
    provide stateful information to the parent parser and/or printer.

    Args:
      json_value: The FHIR json value to parse and wrap.
      primitive_cls: The type of FHIR primitive to parse json_value into.
      default_timezone: The default timezone string to use when parsing date/
        time-like primitives when there is no timezone information available.
        Defaults to 'Z'.

    Raises:
      ValueError: In the event that primitive_cls is not actually a primitive
      FHIR type.

    Returns:
      A wrapper around an instance of primitive_cls parsed from json_value.
    """
    raise NotImplementedError(
        'Subclasses *must* implement primitive_wrapper_from_json_value.')


text:
package com.upside.echo.dao;

import com.upside.echo.model.Greeting;
import com.upside.echo.test.util.AbstractServiceIntTest;
import static com.upside.echo.test.util.Fixtures.GREETING_1;
import static com.upside.echo.test.util.Fixtures.GREETING_2;
import java.util.Collection;
import java.util.UUID;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import org.junit.Before;
import org.junit.Test;

/**
 *
Tests our GreetingDAO

 */
public class IntTestGreetingDAO extends AbstractServiceIntTest {

    private GreetingDAO dao;

    @Before
    public void setup() {
        this.dao = super.injector.getInstance(GreetingDAO.class);
    }

    @Test
    public void testUpsertAndFindAll() {
        this.dao.upsert(GREETING_1);
        this.dao.upsert(GREETING_2);
        Collection<Greeting> allGreetings = this.dao.findGreetings();

        assertTrue("Expected 2 or more greetings, but got " + allGreetings.size(), allGreetings.size() >= 2);
        assertTrue(allGreetings.contains(GREETING_1));
        assertTrue(allGreetings.contains(GREETING_2));
    }

    @Test
    public void testUpsertAndFindByUuid() {
        this.dao.upsert(GREETING_1);

        assertEquals(GREETING_1, this.dao.findByUuid(GREETING_1.getUuid()));
    }

    @Test
    public void testGreetingNotFound() {
        assertNull(this.dao.findByUuid(UUID.randomUUID()));
    }
}


text:
from collections import Counter

def rank_and_file():
    N = input()
    cnt = Counter()
    for _ in xrange(2 * N - 1):
        cnt += Counter(list(raw_input().strip().split()))

    file = []
    for k, v in cnt.iteritems():
        # The count of the missing number must be odd.
        if v % 2 == 1:
            file.append(k)
    # The order of the missing numbers must be sorted.
    file.sort(key=int)

    return " ".join(file)

for case in xrange(input()):
    print 'Case #%d: %s' % (case+1, rank_and_file())


text:
<?php

namespace PHPExiftool\Driver\Tag\XMPMediapro;

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

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

    protected $Id = 'CatalogSets';

    protected $Name = 'CatalogSets';

    protected $FullName = 'XMP::MediaPro';

    protected $GroupName = 'XMP-mediapro';

    protected $g0 = 'XMP';

    protected $g1 = 'XMP-mediapro';

    protected $g2 = 'Image';

    protected $Type = 'string';

    protected $Writable = true;

    protected $Description = 'Catalog Sets';

    protected $flag_List = true;

    protected $flag_Bag = true;
}


text:
<?php
include_once("clases/Categoria.php");
include_once("clases/Usuario.php");

if($_POST)
{
	//si id==1 se guarda en la bd, de lo contrario se muestra el formulario de ingreso
	//si id == 2 se elimina de la bd, de lo contrario se muestra el formulario de ingreso
	$id=$_POST['id'];
	if($id==1)
	{
		//variables POST
		$idUsuario=$_POST['idUsuario'];
		$nombre=$_POST['nombre'];
		$apellidopaterno=$_POST['apellidopaterno'];
		$apellidomaterno=$_POST['apellidomaterno'];
		$clave=$_POST['clave'];
		$idCategoria=$_POST['idCategoria'];

		// Aquí falta una comprobación pero no hay comprobación en la función de buscar categoría.
		//$categoria = Categoria::obtenerPorId($idCategoria);

		$categoria = Categoria::obtenerPorId($idCategoria);
		if($categoria)
		{
			$usuario = new Usuario($idUsuario, $nombre, $apellidopaterno, $apellidomaterno, $clave, $categoria);
			if($usuario->insertar())
			{
				echo "OK";
			}
			else
			{
				echo "No se pudo guardar el usuario, por favor intente nuevamente.";
			}
		}
		else
		{
			echo "$idCategoria no existe";
		}
	}//fin if id=1
	else if ($id == 2)
	{
		$idUsuario = $_POST['idUsuario'];
		$usuario = Usuario::obtenerPorId($idUsuario);
		if ($usuario->eliminar())
		{
			echo "OK";
		}
		else
		{
			echo "No se pudo eliminar el usuario, por favor intente nuevamente.";
		}
	}
	else if ($id == 3 )
	{
		$idUsuario = $_POST['idUsuario'];
		$nombre	= $_POST['nombre'];
		$apellidopaterno = $_POST['apellidopaterno'];
		$apellidomaterno = $_POST['apellidomaterno'];
		$clave = $_POST['clave'];
		$idCategoria = $_POST['idCategoria'];

		$categoria = Categoria::obtenerPorId($idCategoria);

		$usuario = Usuario::obtenerPorId($idUsuario);
		$usuario->Nombre = $nombre;
		$usuario->ApellidoPaterno = $apellidopaterno;
		$usuario->ApellidoMaterno = $apellidomaterno;
		$usuario->Categoria = $categoria;

		if ($clave != "")
		{
			$usuario->Clave = $clave;
		}
		if ($usuario->modificar())
		{
			echo "OK";
		}
		else
		{
			echo "No se pudo modificar el usuario, por favor intente nuevamente";
		}
	}
}
else
{
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Paciente :: Ingresar</title>
<link rel="stylesheet" type="text/css" href="estilos/estilo.css">

		<form id="formulario">

aaaaaaaaaaaa

						EDITAR USUARIO

						Usuario
						Nombre
						Apellido Paterno
						Apellido Materno
						Categoria
						Acción

					<?php
					$usuarios = Usuario::listarUsuarios();
					foreach($usuarios as $usuario)
					{
					?>

						<?php echo $usuario->IdUsuario; ?>

						<?php echo $usuario->Nombre; ?>
						<?php echo $usuario->ApellidoPaterno; ?>
						<?php echo $usuario->ApellidoMaterno; ?>
						<?php echo $usuario->Categoria->NombreCategoria; ?>
						<button id="botonEliminar" onClick="eliminarUsuario('<?php echo $usuario->IdUsuario; ?>')" type="button">Eliminar</button>
						<button id="botonModificar" onClick="llenarFormularioModificar('<?php echo $usuario->IdUsuario; ?>','<?php echo $usuario->Nombre;?>','<?php echo $usuario->ApellidoPaterno; ?>','<?php echo $usuario->ApellidoMaterno; ?>','<?php echo $usuario->Categoria->IdCategoria;?>')" type="button">Modificar</button>

				  <?php }?>

DERMOSALUD USUARIO

						AGREGAR USUARIO

						Usuario
						<input class="inputNormal" id="idUsuario" name="idUsuario" type="text">

						Nombre
						<input class="inputNormal" type="text" id="nombre" name="nombre" size="30" />

						Apellido Paterno
						<input class="inputNormal" type="text" id="apellidopaterno" name="apellidopaterno" size="30">

						Apellido Materno
						<input class="inputNormal" type="text" id="apellidomaterno" name="apellidomaterno" size="30">

						Categoria
						<select name="idCategoria" class="inputNormal" id="idCategoria">
							<?php
						$categorias = Categoria::listar();
						foreach($categorias as $categoria)
						{
							echo "<option value='$categoria->IdCategoria'>$categoria->NombreCategoria</option>";
						}
						?>
						</select>

						Clave
						<input class="inputNormal" type="password" id="clave" name="clave"/>

						Re ingrese Clave
						<input class="inputNormal" type="password" id="ReingresoClave" />

					<button id="botonEnviar" onClick="validaForm()" type="button">Enviar</button>
					<button type="reset">Limpiar</button>
					<button id="mostrarModificar" onClick="modificarUsuario()" type="button">Modificar</button>

	  </form>

<?php }?>


text:
using System.Linq;

namespace Orchard.Projections.Settings {
    public class SValue : ISItem {
        public object Value { get; set; }

        public SValue(object value) {
            Value = value;
        }

        #region ICloneable Members

        public object Clone() {
            return new SValue(Value);
        }

        public static SValue operator &(SValue o1, SValue o2) {
            return o2;
        }

        public static SArray operator &(SValue o1, SArray o2) {
            // concatenate the value with the array
            return new SArray(new[] { o1 }.Union(o2.Values).ToArray());
        }

        public static SObject operator &(SValue o1, SObject o2) {
            return o2;
        }

        #endregion
    }
}


text:
package org.wso2.balana.cond;

/**
 * A simple proxy interface used to install new FunctionFactorys. The three kinds of
 * factory (Target, Condition, and General) are tied together in this interface because implementors
 * writing new factories should always implement all three types and provide them together.
 *
 * @since 1.2
 * @author Seth Proctor
 */
public interface FunctionFactoryProxy {

    /**
     * Returns the Target version of an instance of the FunctionFactory for which this
     * is a proxy.
     *
     * @return a FunctionFactory instance
     */
    public FunctionFactory getTargetFactory();

    /**
     * Returns the Condition version of an instance of the FunctionFactory for which
     * this is a proxy.
     *
     * @return a FunctionFactory instance
     */
    public FunctionFactory getConditionFactory();

    /**
     * Returns the General version of an instance of the FunctionFactory for which this
     * is a proxy.
     *
     * @return a FunctionFactory instance
     */
    public FunctionFactory getGeneralFactory();

}


text:
package sub

import "fmt"

// BUG(natefinch) This is a bug description. Bugs are an exception to the rule
// about only attached comments getting displayed in godoc.  Simply make a
// comment that starts with BUG(foo) where foo is the name of the person
// responsible for the bug, and it'll show up in the list of bugs in godoc.
// Note that bug descriptions are plaintext only.  You can click on the link at
// the beginning of the bug description to go right to the place where the BUG
// comment is located in the code.

// BUG(godoc.org) Note that bugs in the command (application) package do not
// show up on godoc.org.  This appears to be a bug in godoc.org, as they do show
// up in local godoc.

// Constants are sorted to the top of the code documentation.
//
// Formatting
//
// Because it is declared on its own and not in a const() block, AppleName gets
// full formatting support.
const AppleName = "apple"

// This text is a doc comment on the const block as a whole.  Unlike the
// comments inside the block, this text has full formatting.
//
// This can be a nice way to write a single comment about a group of variables.
const (
	// PearName is an exported constant used to create pear foods. Docs on
	// constants and variables enclosed in a block like this one get printed out
	// as-is.
	PearName = "pear"

	// PineappleName is the name of a pineapple.
	PineappleName = "pineapple"
)

// Apple is a global variable in the package.
//
// Because apple is declared on its own, rather in a block of var (), its
// documentation gets full formatting support.
var Apple = NewFood(AppleName)

// This is a block of variables with a formatted comment.
//
// Pretty nice.
var (
	// Pear is another global variable in the package.
	Pear = NewFood(PearName)
)

// Favorite is a global variable in the package.
//
// Because it is declared with a type defined within the package, it is
// sorted with the type definition in the documentation.
//
// Below is the auto-embedded example from the function ExampleFood in
// more_examples_test.go.
var Favorite Food = Pear

// Food is a type to show how type documentation works.
//
// Formatting
//
// You always get full formatting on type, function, and method docs.
type Food struct {
	// Name holds the common name of the food.
	//
	// Alas, no formatting here.
	Name string

	// weight is an unexported field that won't show up in documentation.
	weight int
}

// NewFood creates a new Food with the given name and a calculated weight.
//
// Godoc sorts "constructor" style functions like this, that return a type
// defined in the package, under the type itself.
//
// Note that you do not need to (and should not) make separate lines describing
// each parameter to the function.  Simply refer to the parameters by their name
// when you need to reference them in the rest of the documentation.
func NewFood(name string) Food {
	return Food{name, len(name)}
}

// Weight reports the weight of the food in letters.
//
// When decribing a function without parameters that simply returns data, it is
// traditional to write the doc saying the function reports foo, rather than
// *returns* foo.
//
// The example below intentionally fails during go test, to show you what that
// looks like.  The test will report:
//
//   --- FAIL: ExampleFood_Weight (4.933us)
//   got:
//   9
//   want:
//   10
//   FAIL
//   exit status 1
func (f Food) Weight() int {
	return f.weight
}

// Zap consumes the food and prints out a nasty message.
//
// This is just another top level function to show how the alphabetical sorting
// works.
func Zap(f Food) {
	fmt.Printf("I hate %ss!", f.Name)

}

// Eat consumes the food and prints out a nice message.
//
// This is an example of a function that isn't a "constructor" style function,
// so it will be sorted at the top level of the documentation.
//
// Functions get sorted before types.
func Eat(f Food) {
	fmt.Printf("I love %ss!", f.Name)
}

// Weight is a type to show how type-associated const and var documentation works.
type Weight int

// Constant declarations are sorted with their type definition when all the
// constant types match.
//
// This works with elided type definition using iota, but does not work when
// the constant type is deduced from the constant expression.
const (
	Small Weight = 1  // This much fruit is not enough.
	Big   Weight = 20 // This is way too much fruit.
)

// Variable declarations of a specific type are also associated with their type
// declaration in the documentation.
var WeightPreference Weight


text:
<merge xmlns:android="http://schemas.android.com/apk/res/android">

        <LinearLayout
            xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:tools="http://schemas.android.com/tools"
            android:padding="0dp"
            android:keepScreenOn="true"
            android:orientation="vertical"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            tools:context=".EditLegacyModuleControllerActivity" >

            <TextView
                android:id="@+id/portNumber"
                android:textSize="12sp"
                android:layout_height="wrap_content"
                android:layout_width="wrap_content"
                android:text="@string/default_port"
                android:visibility="invisible"/>

            <!-- ****************************************************** Module ******************************************************-->
            <RelativeLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:id="@+id/dropdown_layout">
                <Spinner
                    android:id="@+id/choiceSpinner_legacyModule"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:background="@android:drawable/btn_dropdown"
                    android:entries="@array/choice_array"
                    android:prompt="@string/choice_prompt"
                    android:spinnerMode="dropdown" />
            </RelativeLayout>

            <RelativeLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content">

                <EditText
                    android:id="@+id/editTextResult_name"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:inputType="text"
                    android:maxLength="200"
                    android:hint="@string/name_prompt_text">
                </EditText>

                <TextView
                    android:id="@+id/titleTextView_analogInput7"
                    android:layout_marginBottom="5dp"
                    android:paddingLeft="10dp"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_below="@id/editTextResult_name"
                    android:text="@string/name_prompt_undertext">
                </TextView>

                <Button
                    android:id="@+id/edit_controller_btn"
                    android:layout_width="wrap_content"
                    android:layout_below="@id/titleTextView_analogInput7"
                    android:layout_height="wrap_content"
                    android:layout_gravity="end"
                    android:paddingRight="10dp"
                    android:paddingLeft="10dp"
                    android:layout_marginTop="0dp"
                    android:text="@string/edit_controller"
                    android:onClick="editController_portALL"
                    android:visibility="invisible"/>
            </RelativeLayout>
        </LinearLayout>
</merge>
<!-- From: file:/Users/tom/Documents/workspace/ftc_sdk/lib/FtcCommon/src/main/res/layout/simple_device.xml -->


text:
@interface MyEarningViewCell : UITableViewCell

@property (nonatomic, strong) UILabel *lbqiandao; //签到
@property (nonatomic, strong) UILabel *lbtime; //时间
@property (nonatomic, strong) UILabel *lbjifen; //积分

@end


text:
package chordsOverLyrics

import (
	"fmt"
	"io"
	"strings"

	"github.com/songtools/songtools"
)

// WriteSong writes a single song to the writer.
func WriteSong(w io.Writer, s *songtools.Song) error {

	if s.Title != "" {
		_, err := fmt.Fprintln(w, "#"+titleDirectiveName+"="+s.Title)
		if err != nil {
			return err
		}
	}
	for _, st := range s.Subtitles {
		_, err := fmt.Fprintln(w, "#"+subtitleDirectiveName+"="+st)
		if err != nil {
			return err
		}
	}
	for _, a := range s.Authors {
		_, err := fmt.Fprintln(w, "#"+authorDirectiveName+"="+a)
		if err != nil {
			return err
		}
	}
	if s.Key != "" {
		_, err := fmt.Fprintln(w, "#"+keyDirectiveName+"="+string(s.Key))
		if err != nil {
			return err
		}
	}

	for _, n := range s.Nodes {
		err := writeSongNode(w, n)
		if err != nil {
			return err
		}
	}

	return nil
}

func writeSongNode(w io.Writer, n songtools.SongNode) error {
	switch typedN := n.(type) {
	case *songtools.Comment:
		return writeComment(w, typedN)
	case *songtools.Directive:
		return writeDirective(w, typedN)
	case *songtools.Section:
		if typedN.Kind != "" {
			_, err := fmt.Fprint(w, fmt.Sprintf("[%v]", typedN.Kind))
			if err != nil {
				return err
			}
		} else {
			// need to make sure we have an extra line here cause nothing
			// other than space is separating this from the previous
			// section
			_, err := fmt.Fprintln(w)
			if err != nil {
				return err
			}
		}

		anyChords := len(typedN.Chords()) > 0

		for i, sn := range typedN.Nodes {
			if i == 0 {
				if c, ok := sn.(*songtools.Comment); ok {
					_, err := fmt.Fprintln(w, c.Text)
					if err != nil {
						return err
					}
					continue
				} else {
					_, err := fmt.Fprintln(w)
					if err != nil {
						return err
					}
				}
			}
			err := writeSectionNode(w, sn, anyChords)
			if err != nil {
				return err
			}
		}

		_, err := fmt.Fprintln(w)
		if err != nil {
			return err
		}
	default:
		panic("Unknown node")
	}

	return nil
}

func writeSectionNode(w io.Writer, n songtools.SectionNode, blankLineForNoChords bool) error {
	switch typedN := n.(type) {
	case *songtools.Comment:
		return writeComment(w, typedN)
	case *songtools.Directive:
		return writeDirective(w, typedN)
	case *songtools.Line:
		return writeLine(w, typedN, blankLineForNoChords)
	default:
		panic("Unknown node")
	}
}

func writeComment(w io.Writer, c *songtools.Comment) error {
	_, err := fmt.Fprintln(w, fmt.Sprintf("{%v}", c.Text))
	return err
}

func writeDirective(w io.Writer, d *songtools.Directive) error {
	_, err := fmt.Fprintln(w, fmt.Sprintf("#%v=%v", d.Name, d.Value))
	return err
}

func writeLine(w io.Writer, l *songtools.Line, blankLineForNoChords bool) error {
	if l.Chords != nil {
		pos := 0
		for i := 0; i < len(l.Chords); i++ {

			diff := l.ChordPositions[i] - pos
			if i > 0 && diff <= 0 {
				diff = l.ChordPositions[i] - l.ChordPositions[i-1]
			}
			_, err := fmt.Fprint(w, strings.Repeat(" ", diff))
			if err != nil {
				return err
			}
			_, err = fmt.Fprint(w, l.Chords[i].Name)
			if err != nil {
				return err
			}
			pos = l.ChordPositions[i] + len(l.Chords[i].Name)
		}
		_, err := fmt.Fprintln(w)
		if err != nil {
			return err
		}
	} else if blankLineForNoChords {
		_, err := fmt.Fprintln(w)
		if err != nil {
			return err
		}
	}

	_, err := fmt.Fprintln(w, l.Text)
	return err
}


text:
package archvariant

func osAVX512Supported(ax uint32) bool {
	return ax&v4OSSupport == v4OSSupport
}


text:
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
module Data.Monoid.Bounds where

import Data.Monoid

newtype Minimum n = Minimum { getMinimum :: n } deriving (Eq, Ord, Bounded)
newtype Maximum n = Maximum { getMaximum :: n } deriving (Eq, Ord, Bounded)

instance (Ord n, Bounded n) => Monoid (Minimum n) where
  mempty  = maxBound
  mappend = min

instance (Ord n, Bounded n) => Monoid (Maximum n) where
  mempty  = minBound
  mappend = max


text:
var DealPlyEdenCommonCls;

var DealPlyEdenCommon;

if (typeof DealPlyEdenCommonCls === "undefined") {
	DealPlyEdenCommonCls = function() {
	};

	DealPlyEdenCommon = new DealPlyEdenCommonCls();

	/*
		convert time offset from UTC to millis and invert since getTimezoneOffset() is negative if local time zone is after UTC, which is counter  intuitive
	*/
	DealPlyEdenCommonCls.prototype.LocalOffsetInMillis = new Date().getTimezoneOffset() * 60 * 1000 * -1;

	/*
		this function accepts a utc
	*/
	DealPlyEdenCommonCls.prototype.toLocalTimeInMillis = function(timeSinceEpochInMillis, timezone) {
			if (timezone > 14 || timezone < -12)
				throw "illegal timezone: " + timezone;

			var otherOffset = timezone * 60 * 60 * 1000;

			return timeSinceEpochInMillis + (this.LocalOffsetInMillis - otherOffset);
	};

	DealPlyEdenCommonCls.prototype.reportError = function(dealplyErr) {

	};

	DealPlyEdenCommonCls.prototype.htmlspecialchars = function(dealplyHtml) {
		try {
			return dealplyHtml.replace(/&/g, "&").replace(/</g, "<")
					.replace(/>/g, ">").replace(/"/g, """).replace(
							/'/g, "'");
		} catch (dealplyE) {
			DealPlyEdenCommon.reportError(dealplyE);
			return dealplyHtml;
		}
	};

	DealPlyEdenCommonCls.prototype.openWindowEx = function(dealplyUrl,
			dealplyWindowName) {
		try {
			var dealplyWin = null;

			if (typeof dealplyWindowName === "undefined"
					|| dealplyWindowName === null) {
				dealplyWin = window.open(dealplyUrl);
			} else {
				dealplyWin = window.open(dealplyUrl, dealplyWindowName);
			}
		} catch (dealplyE) {
			DealPlyEdenCommon.reportError(dealplyE);

			try {
				window.open(dealplyUrl);
			} catch (dealplyE2) {

			}
		}
	};

	DealPlyEdenCommonCls.prototype.getJsonObjectAsHttpParameters = function(
			dealplyObj) {
		try {
			var dealplyParams = "";

			for (dealplyProp in dealplyObj) {
				if (!dealplyObj.hasOwnProperty(dealplyProp)) {
					continue;
				}

				if (typeof dealplyObj[dealplyProp] === "undefined") {
					continue;
				}

				var dealplyVal = encodeURIComponent(dealplyObj[dealplyProp]);

				if (dealplyParams.length !== 0) {
					dealplyParams = dealplyParams + "&";
				}

				dealplyParams = dealplyParams + encodeURIComponent(dealplyProp)
						+ "=" + dealplyVal;
			}

			return dealplyParams;
		} catch (dealplyE) {
			DealPlyEdenCommon.reportError(dealplyE);
			return null;
		}
	};

		DealPlyEdenCommonCls.prototype.addCommonEventData = function(dealplyJsonObj) {
		try {

			dealplyJsonObj["cb"] = "" + Math.random();

			dealplyJsonObj["localDate"] = "" + new Date().getTime();

			if (typeof dpVariables.ltime !== "undefined") {

				var roundTripStart = dpVariables.ltime+"";
				var roundTripEnd = "" + new Date().getTime();

				var roundTripTime = parseInt(roundTripEnd)
						- parseInt(roundTripStart);

				dealplyJsonObj["roundTripTime"] = roundTripTime;

				return;
			}

		} catch (dealplyE) {

			DealPlyEdenCommon.reportError(dealplyE);
			return null;
		}
	};

	DealPlyEdenCommonCls.prototype.reportQuick = function(jsonData){

		try {

			var url = DealPlyEdenCommon.getQuickURL(jsonData);

			DealPlyEdenCommon.reportEventUrl(url);

		} catch (dealplyE) {
			DealPlyEdenCommon.reportError(dealplyE);
		}
	};
	DealPlyEdenCommonCls.prototype.reportBadImage = function(jsonData){

		try {

			var url = DealPlyEdenCommon.getBadImageURL(jsonData);
			DealPlyEdenCommon.reportEventUrl(url);

		} catch (dealplyE) {
			DealPlyEdenCommon.reportError(dealplyE);
		}
	};

	DealPlyEdenCommonCls.prototype.getBadImageURL = function(jsonData){
		var baseTrackingUrl = DealPlyOpDom.getServedbyBaseUrlWithSuffix();
		var url =baseTrackingUrl + "/dealdo/bad-img-report?";
		var dealplyParams = DealPlyEdenCommon.getJsonObjectAsHttpParameters(jsonData);

		url += dealplyParams;

		return url;
	};

	DealPlyEdenCommonCls.prototype.getQuickURL = function(jsonData){
		var baseTrackingUrl = "";
		var eventName = "quick";
		baseTrackingUrl = DealPlyOpDom.getQuickDomain();
		var url = "//" + baseTrackingUrl + "/dealdo/event-report?type=quick&sessionid="+dpVariables.sessionid+"&";
		if(typeof ChickenApp !== "undefined" || typeof ChickenBoss !== "undefined" ){

			url = "//" + baseTrackingUrl + "/e?type=offb&sessionid="+dpVariables.sessionid+"&";
		}

		var dealplyParams = DealPlyEdenCommon
				.getJsonObjectAsHttpParameters(jsonData);

		var cb = Math.random();

		url += dealplyParams +"&cb="+ cb;

		return url;
	};

	DealPlyEdenCommonCls.prototype.reportEventEx = function(eventName,
			dealplyJsonObj) {
		try {
			if(typeof dpVariables !== "undefined" && dpVariables.documentUri.search("selftest.html") !== -1){
				return;
			}
			var baseTrackingUrl = "";
			if (eventName === "click") {

				try{
					//three days
					DealPlyEdenPersistencyHttpCookies.setCookie("clkdpid", dealplyJsonObj.clkid, 60*1000*60*24*3);
				}catch(e){

				}
				baseTrackingUrl = dpVariables.baseTrackingUrlClick;
			} else if (eventName === "impression") {
				DealPlyInteropInner.sendCommand("try{DealPly.reportYesPresentation();}catch(e){}");
				if(typeof DealPlyEdenPersistencyHttpCookies !== "undefined") {

					// Skip impression if currently in Suspend mode - this should
					// never happen due to supression in ShoppingJS
					var isSuspended = DealPlyEdenPersistencyHttpCookies
							.isSuspendedAccordingToHttpCookie();
					if (isSuspended) {
						return;
					}
				}

				baseTrackingUrl = dpVariables.baseTrackingUrlImpression;
			} else if (eventName === "access") {

				baseTrackingUrl = dpVariables.baseTrackingUrlAccess;
			} else if (eventName === "suspend") {
				baseTrackingUrl = dpVariables.baseTrackingUrlSuspend;
			} else if (eventName === "quick") {

				baseTrackingUrl = dpVariables.baseTrackingUrlQuick;
			}

			DealPlyEdenCommon.addCommonEventData(dealplyJsonObj);

			var dealplyParams = DealPlyEdenCommon
					.getJsonObjectAsHttpParameters(dealplyJsonObj);

			var cb = Math.random();

			var url = baseTrackingUrl + "&cb=" + cb + "&" + dealplyParams;

			if(typeof DealPlyEdenPersistencyHttpCookies === "undefined") {
				url = url.replace("%USER_UID%", "99");
			} else {
				url = url.replace("%USER_UID%", DealPlyEdenPersistencyHttpCookies
						.getPersistentIdAccordingToHttpCookies());
			}

			DealPlyEdenCommon.reportEventUrl(url);

			// timing quick event

		} catch (dealplyE) {
			DealPlyEdenCommon.reportError(dealplyE);
		}

		setTimeout(function(){DealPlyEdenCommon.googleAnalytics(eventName);},1500);
	};

	var _gaq;

/*	try {
		_gaq = _gaq || [];
		_gaq.push(['_setAccount', 'UA-21242672-5']);
		_gaq.push(['_trackPageview']);
	} catch(dealplyEee6) {

	}	*/

	DealPlyEdenCommonCls.prototype.googleAnalytics = function(event ) {
		try {
			var templateGroup = undefined;

		    _gaq.push(['_setAccount', 'UA-21242672-9']);
			var firstUseDate = DealPlyEdenPersistencyHttpCookies.getCookie("firstUseDate");
			if(typeof firstUseDate === "undefined" || firstUseDate === null || firstUseDate === false) {
				firstUseDate = "undef";
			}

			if(typeof dealPlyUtils === "undefined"){
				templateGroup = "Green";

			}else{
				templateGroup = dealPlyUtils.templateGroup;

			}

			var fud_long = new Date(parseInt(firstUseDate));
			var day = fud_long.getDate();
			var month = fud_long.getMonth() + 1; //months are zero based
			var year = fud_long.getFullYear();
			var fud =  day+ "-" + month + "-" + year;

/*			var today_long = new Date();
			var today_day = today_long.getDate();
			var today_month = today_long.getMonth() + 1; //months are zero based
			var today_year = today_long.getFullYear();
			var today_fud =  today_day+ "-" + today_month + "-" + today_year;*/
			if (event === "click" )
				_gaq.push(['_trackEvent', "event_"+event+"_"+templateGroup , event, fud]);
			else if (Math.random()*10000 <= 10)

				_gaq.push(['_trackEvent', "event_"+event+"_"+templateGroup , event, fud]);
		} catch (ee) {

		}
	};

	DealPlyEdenCommonCls.prototype.reportEventUrl = function(url) {

		try {
			var element2insert = typeof ChickenBoss !== 'undefined' ? "img" : "iframe";
			var dpFrameId = undefined;
			if(url.match(/impression/) == null || typeof ChickenBoss !== 'undefined'){

				dpiframe = document.createElement(element2insert);
				dpQuery(dpiframe).attr("width", "1");
				dpQuery(dpiframe).attr("height", "1");
				dpQuery(dpiframe).css("top", "-10000px");
				dpQuery(dpiframe).css("left", "-10000px");
				dpQuery(dpiframe).css("position", "absolute");
				dpQuery(dpiframe).css("visibility", "visible");
				dpQuery("body").append(dpiframe);

				dpQuery(dpiframe).attr("src", url);
			}else{
				if(typeof dpFrameId === 'undefined'){
					dpFrameId = "."+dpVariables.self;
				}
				var cmd = "var dpiframe=document.createElement(\"iframe\");dpQuery(dpiframe).attr(\"width\",\"1\");dpQuery(dpiframe).attr(\"height\",\"1\");dpQuery(dpiframe).css(\"top\",\"-10000px\");dpQuery(dpiframe).css(\"left\",\"-10000px\");dpQuery(dpiframe).css(\"position\",\"absolute\");dpQuery(dpiframe).css(\"visibility\",\"visible\");dpQuery(\"body\").append(dpiframe);dpQuery(dpiframe).attr(\"src\",\""+url+"\");";
				var randStr = ""+ Math.random();
				if(dpFrameId.indexOf("popeye")<0){
					cmd = 'if(typeof dpQuery("'+dpFrameId+'").attr("a'+randStr+'") ==="undefined") { dpQuery("'+dpFrameId+'").attr("a'+randStr+'","1");'+
					' if(typeof DealPly.impinjected === "undefined" || DealPly.impinjected == false  ) {'  + cmd + 'DealPly.impinjected = true;}}';
				}else{
					cmd = 'if(typeof dpQuery("'+dpFrameId+'").attr("a'+randStr+'") ==="undefined") { dpQuery("'+dpFrameId+'").attr("a'+randStr+'","1");'+
					' if(typeof dpQuery("'+dpFrameId+'").attr("ii") != "undefined" && dpQuery("'+dpFrameId+'").attr("ii") != pitchy.getImpressionInjected()  ) {'  + cmd + 'DealPly.impinjected = true;}}';
				}
				dpVariables.debug = cmd;
				DealPlyInteropInner.sendCommandInLoop(cmd);
				var count = 0;
				/*var t = setInterval(function(){
					count++;
					DealPlyInteropInner.sendCommand(cmd);

					if(count > 40){
						clearInterval(t);
					}

				},300);*/

			}

		} catch (dealplyE) {
			DealPlyEdenCommon.reportError(dealplyE);
		}
	};

	DealPlyEdenCommonCls.prototype.ellipsis = function(s, maxLength) {
		try {
			if (maxLength < 4) {
				return null;
			}

			if (s.length <= maxLength) {
				return s;
			} else {
				return s.substring(0, (maxLength - 3)) + "...";
			}
		} catch (dealplyE) {
			DealPlyEdenCommon.reportError(dealplyE);
			return s;
		}
	};

	DealPlyEdenCommonCls.prototype.truncate = function(s, maxLength) {
		try {
			if (s == null) {
				return s;
			}

			if (s.length <= maxLength) {
				return s;
			} else {
				return s.substring(0, maxLength);
			}
		} catch (dealplyE) {
			DealPlyEdenCommon.reportError(dealplyE);
			return s;
		}
	};

	DealPlyEdenCommonCls.prototype.createCookie = function(name,value,days) {
		var expires = undefined;
		if (days) {
		        var date = new Date();
		        date.setTime(date.getTime()+(days*24*60*60*1000));
		        expires = "; expires="+date.toGMTString();
		}
		else expires = "";
		document.cookie = escape(name)+"="+escape(value)+expires+"; path=/";
	};

	DealPlyEdenCommonCls.prototype.readCookie = function(name) {
		var nameEQ = escape(name) + "=";
		var ca = document.cookie.split(';');
		for(var i=0;i < ca.length;i++) {
		        var c = ca[i];
		        while (c.charAt(0)==' ') c = c.substring(1,c.length);
		        if (c.indexOf(nameEQ) == 0) return unescape(c.substring(nameEQ.length,c.length));
		}
		return null;
	};

	DealPlyEdenCommonCls.prototype.eraseCookie = function(name) {
		createCookie(name,"",-1);
	};

	if(typeof String.prototype.trim !== 'function') {
	  String.prototype.trim = function() {
	    return this.replace(/^\s+|\s+$/g, '');
	  };
	}

}


text:
<?php

namespace AmberSdk\Client\Model;

class ConstantElement
{
    /**
     * @var string
     */
    public $dataTypeCode;

    /**
     * @var string
     */
    public $value;

    /**
     * @param string $dataTypeCode
     * @param string $value
     */
    function __construct($dataTypeCode, $value)
    {
        $this->dataTypeCode = $dataTypeCode;
        $this->value = $value;
    }
}


text:
<?php

namespace PiPHP\GPIO\Pin;

use PiPHP\GPIO\FileSystem\FileSystemInterface;

final class InputPin extends Pin implements InputPinInterface
{
    public const GPIO_PIN_FILE_EDGE = 'edge';

    /**
     * Constructor.
     *
     * @param FileSystemInterface $fileSystem An object that provides file system access
     * @param int                 $number     The number of the pin
     */
    public function __construct(FileSystemInterface $fileSystem, $number)
    {
        parent::__construct($fileSystem, $number);

        $this->setDirection(self::DIRECTION_IN);
    }

    /**
     * {@inheritdoc}
     */
    public function getEdge()
    {
        $edgeFile = $this->getPinFile(self::GPIO_PIN_FILE_EDGE);
        return trim($this->fileSystem->getContents($edgeFile));
    }

    /**
     * {@inheritdoc}
     */
    public function setEdge($edge)
    {
        $edgeFile = $this->getPinFile(self::GPIO_PIN_FILE_EDGE);
        $this->fileSystem->putContents($edgeFile, $edge);
    }
}


text:
Python Glasgow
==============

.. image:: https://secure.travis-ci.org/python-glasgow/pythonglasgow.png
   :alt: Build Status
   :target: https://travis-ci.org/python-glasgow/pythonglasgow

This is the code for www.pythonglasgow.org

The site is hosted on Heroku and uses Flask.

Setup Instructions
==================

To setup and start the website locally, use the following commands. This
assumes you are using virtualenv wrapper, if you need other help then
get in touch with @d0ugal ::

    mkvirtualenv pythonglasgow
    pip install -r requirements/dev.txt
    honcho start

If that all worked, you should be able to head to http://localhost:5000/

Note that some features (namely Twitter) wont work unless you can
provide API access keys.


text:
<?php

class JoppyHelper
{
    private $viewName;
    private $layoutName;
    private $outputData;

    private $viewContent;

    private $stringHelper;
    private $fileHelper;

    public function __construct($viewName, $layoutName, $outputData)
    {
        $this->viewName = $viewName;
        $this->layoutName = $layoutName;
        $this->outputData = $outputData;

        $this->stringHelper = new StringHelper();
        $this->fileHelper = new FileHelper();
    }

    public function ProcessPage()
    {
        $this->viewContent = $this->fileHelper->LoadAndGetProcessedContent('Application/Views/'.$this->viewName.'.phtml', $this->outputData);
        $layoutTemplate = $this->fileHelper->LoadAndGetProcessedContent('Application/Views/Layouts/'.$this->layoutName.'.phtml', $this->outputData);

        echo($this->TranslateLayout($layoutTemplate));
    }

    public function TranslateLayout($layoutTemplate)
    {
        $translatedLayout = $this->CheckForElements($layoutTemplate, 'section', 'PullCurrentSection');
        $translatedLayout = $this->CheckForElements($translatedLayout, 'component', 'PullCurrentComponent');
        $translatedLayout = $this->CheckForVariableMarkers($translatedLayout);

        return $translatedLayout;
    }

    private function CheckForElements($document, $nameOfElement, $contentPullingMethod)
    {
        $checkedElement = '';

        $isReadingElementName = false;
        $nameOfCurrentElement = '';
        $idOfElementStart = 0;

        extract((array)$this->outputData);

        for ($i = 0; $i < strlen($document); $i++)
        {
            if ($isReadingElementName)
            {
                if ($document[$i] == ')')
                {
                    $isReadingElementName = false;

                    $checkedElement .= call_user_func_array(array($this, $contentPullingMethod), array($nameOfCurrentElement));

                    $nameOfCurrentElement = '';
                }
                else if (strlen($nameOfCurrentElement) + 1 > 50)
                {
                    /*$isReadingElementName = false;
                    $i = $idOfElementStart;
                    $translatedLayout .= '#';

                    $nameOfCurrentElement = "";*/

                    throw new Exception('Name of '.$nameOfElement.' \''.$nameOfCurrentElement.'\' is too long, or you forgot to close the quotes.', E_PARSE);
                }
                else
                    $nameOfCurrentElement .= $document[$i];
            }
            else if ($document[$i] == '#' && substr($document, $i + 1, strlen($nameOfElement) + 1) == $nameOfElement.'(')
            {
                $idOfElementStart = $i;
                $i += strlen($nameOfElement) + 1;
                $isReadingElementName = true;
            }
            else
                $checkedElement .= $document[$i];
        }

        return $checkedElement;
    }

    private function CheckForVariableMarkers($element)
    {
        $checkedElement = '';

        $isReadingVariableName = false;
        $nameOfCurrentVariable = '';
        $idOfVariableStart = 0;

        extract((array)$this->outputData);

        for ($i = 0; $i < strlen($element); $i++)
        {
            if ($isReadingVariableName)
            {
                if ($element[$i] == '#' && $element[$i + 1] == '#')
                {
                    $checkedElement .= ${trim($nameOfCurrentVariable)};

                    $isReadingVariableName = false;
                    $i++;

                    $nameOfCurrentVariable = "";
                }
                else if (strlen($nameOfCurrentVariable) + 1 > 30 || $i + 1 == strlen($element))
                {
                    /*$isReadingVariableName = false;
                    $i = $idOfVariableStart;
                    $checkedElement .= '#';

                    $nameOfCurrentVariable = "";*/

                    throw new Exception('Name of variable is too long, or you forgot to close variable markers. There is also an option, you used two # near to each other.', E_PARSE);
                }
                else
                    $nameOfCurrentVariable .= $element[$i];
            }
            else if ($element[$i] == '#' && $element[$i + 1] == '#')
            {
                $idOfVariableStart = $i;
                $i++;
                $isReadingVariableName = true;
            }
            else
                $checkedElement .= $element[$i];
        }

        return $checkedElement;
    }

    private function PullCurrentSection($nameOfCurrentSection)
    {
        $currentSection = $this->stringHelper->GetSubstringUsingStartAndUniqueEndFragments(
            $this->viewContent,
            '#section('.$nameOfCurrentSection.')',
            '#end('.$nameOfCurrentSection.')'
        );

        return $currentSection;
    }

    private function PullCurrentComponent($nameOfCurrentComponent)
    {
        $currentComponent = '';
        $splitComponentDefinition = $this->stringHelper->Split(str_replace(' ', '', $nameOfCurrentComponent), ',');//return '/'.$splitComponentDefinition[0].'/';

        $componentFile = $this->fileHelper->LoadAndGetProcessedContent('Application/Views/Components/'.$splitComponentDefinition[0].'.phtml', $this->outputData);

        if (count($splitComponentDefinition) == 1)
        {
            if (strpos($componentFile, '#component(default)') !== false)
               $currentComponent = $this->stringHelper->GetSubstringUsingStartAndUniqueEndFragments(
                   $componentFile,
                   '#component(default)',
                   '#end(default)'
               );
            else
                $currentComponent = $componentFile;
        }
        else
            $currentComponent = $this->stringHelper->GetSubstringUsingStartAndUniqueEndFragments(
                $componentFile,
                '#component('.$splitComponentDefinition[1].')',
                '#end('.$splitComponentDefinition[1].')'
            );

        return $currentComponent;
    }
}


text:
var crypto = require('crypto'),
    Utils = require('./utils.js'),
    utils = new Utils();

var Client = function(socket) {
	// Constructor
	this.connections = [];

    this.ID = crypto.randomBytes(64).toString('hex');

    this.addConnection(socket);

    // Send MOTD
    socket.emit('message', {'message': 'Hello world'});
}

Client.prototype.addConnection = function(socket) {
    this.connections.push(socket);

    // Set up handlers for new connection
    this.addHandlers(socket);

    // Acknowledge client
    socket.emit('registered', this.ID);
}

Client.prototype.openConnections = function() {
    return this.connections.length;
}

Client.prototype.addHandlers = function(socket) {
    var self = this;

    socket.on('disconnect', function() {
        console.log('[%s] %s [%s]', utils.shortID(socket.id), 'Disconnecting'.white, utils.shortID(self.ID));

        // Find this connection in the list of open connections
        var connectionsLength = self.connections.length;
        for (i = 0; i < connectionsLength; i++) {
            if (self.connections[i].id == socket.id) {
                delete self.connections.splice(i, 1);

                console.log('[%s] %s [%s](%d)', utils.shortID(socket.id), 'Disconnected'.magenta, utils.shortID(self.ID), self.openConnections());

                break;
            }
        }

        self.checkChildlessness();
    });
}

Client.prototype.checkChildlessness = function() {
    var self = this;
    if (this.childlessnessTimeout) {
        clearTimeout(this.childlessnessTimeout);
    }

    this.childlessnessTimeout = setTimeout(function() {
        // Are there any open connections, remove client
        if (self.connections.length === 0) {
            global.removeClient(self.ID);
            console.log('%s [%s]', 'Removed childless client'.magenta, utils.shortID(self.ID));
        }
    }, 5000);
}

module.exports = Client;


text:
package org.apache.hadoop.yarn.api.protocolrecords.impl.pb;

import java.util.EnumSet;
import java.util.Iterator;
import java.util.List;

import org.apache.hadoop.classification.InterfaceAudience.Private;
import org.apache.hadoop.classification.InterfaceStability.Unstable;
import org.apache.hadoop.yarn.api.protocolrecords.GetClusterNodesRequest;
import org.apache.hadoop.yarn.api.records.NodeState;
import org.apache.hadoop.yarn.api.records.impl.pb.ProtoUtils;
import org.apache.hadoop.yarn.proto.YarnProtos.NodeStateProto;
import org.apache.hadoop.yarn.proto.YarnServiceProtos.GetClusterNodesRequestProto;
import org.apache.hadoop.yarn.proto.YarnServiceProtos.GetClusterNodesRequestProtoOrBuilder;

import org.apache.hadoop.thirdparty.protobuf.TextFormat;

@Private
@Unstable
public class GetClusterNodesRequestPBImpl extends GetClusterNodesRequest {

  GetClusterNodesRequestProto proto = GetClusterNodesRequestProto.getDefaultInstance();
  GetClusterNodesRequestProto.Builder builder = null;
  boolean viaProto = false;

  private EnumSet<NodeState> states = null;

  public GetClusterNodesRequestPBImpl() {
    builder = GetClusterNodesRequestProto.newBuilder();
  }

  public GetClusterNodesRequestPBImpl(GetClusterNodesRequestProto proto) {
    this.proto = proto;
    viaProto = true;
  }

  public synchronized GetClusterNodesRequestProto getProto() {
    mergeLocalToProto();
    proto = viaProto ? proto : builder.build();
    viaProto = true;
    return proto;
  }

  @Override
  public synchronized EnumSet<NodeState> getNodeStates() {
    initNodeStates();
    return this.states;
  }

  @Override
  public synchronized void setNodeStates(final EnumSet<NodeState> states) {
    initNodeStates();
    this.states.clear();
    if (states == null) {
      return;
    }
    this.states.addAll(states);
  }

  private void mergeLocalToProto() {
    if (viaProto) {
      maybeInitBuilder();
    }
    mergeLocalToBuilder();
    proto = builder.build();
    viaProto = true;
  }

  private void maybeInitBuilder() {
    if (viaProto || builder == null) {
      builder = GetClusterNodesRequestProto.newBuilder(proto);
    }
    viaProto = false;
  }

  private void mergeLocalToBuilder() {
    if (this.states != null) {
      maybeInitBuilder();
      builder.clearNodeStates();
      Iterable<NodeStateProto> iterable = new Iterable<NodeStateProto>() {
        @Override
        public Iterator<NodeStateProto> iterator() {
          return new Iterator<NodeStateProto>() {

            Iterator<NodeState> iter = states.iterator();

            @Override
            public boolean hasNext() {
              return iter.hasNext();
            }

            @Override
            public NodeStateProto next() {
              return ProtoUtils.convertToProtoFormat(iter.next());
            }

            @Override
            public void remove() {
              throw new UnsupportedOperationException();

            }
          };

        }
      };
      builder.addAllNodeStates(iterable);
    }
  }

  private void initNodeStates() {
    if (this.states != null) {
      return;
    }
    GetClusterNodesRequestProtoOrBuilder p = viaProto ? proto : builder;
    List<NodeStateProto> list = p.getNodeStatesList();
    this.states = EnumSet.noneOf(NodeState.class);

    for (NodeStateProto c : list) {
      this.states.add(ProtoUtils.convertFromProtoFormat(c));
    }
  }

  @Override
  public int hashCode() {
    return getProto().hashCode();
  }

  @Override
  public boolean equals(Object other) {
    if (other == null)
      return false;
    if (other.getClass().isAssignableFrom(this.getClass())) {
      return this.getProto().equals(this.getClass().cast(other).getProto());
    }
    return false;
  }

  @Override
  public String toString() {
    return TextFormat.shortDebugString(getProto());
  }
}