text:
package org.apache.hadoop.yarn.server.resourcemanager.scheduler.fair.converter;

import static org.apache.hadoop.yarn.server.resourcemanager.scheduler.capacity.CapacitySchedulerConfiguration.PREFIX;
import static org.apache.hadoop.yarn.server.resourcemanager.scheduler.fair.converter.FSConfigToCSConfigRuleHandler.DYNAMIC_MAX_ASSIGN;
import static org.apache.hadoop.yarn.server.resourcemanager.scheduler.fair.converter.FSConfigToCSConfigRuleHandler.MAX_CAPACITY_PERCENTAGE;
import static org.apache.hadoop.yarn.server.resourcemanager.scheduler.fair.converter.FSConfigToCSConfigRuleHandler.MAX_CHILD_CAPACITY;
import static org.apache.hadoop.yarn.server.resourcemanager.scheduler.fair.converter.FSConfigToCSConfigRuleHandler.QUEUE_AUTO_CREATE;
import static org.apache.hadoop.yarn.server.resourcemanager.scheduler.fair.converter.FSConfigToCSConfigRuleHandler.RESERVATION_SYSTEM;
import static org.apache.hadoop.yarn.server.resourcemanager.scheduler.fair.converter.FSConfigToCSConfigRuleHandler.CHILD_STATIC_DYNAMIC_CONFLICT;
import static org.apache.hadoop.yarn.server.resourcemanager.scheduler.fair.converter.FSConfigToCSConfigRuleHandler.PARENT_CHILD_CREATE_DIFFERS;
import static org.apache.hadoop.yarn.server.resourcemanager.scheduler.fair.converter.FSConfigToCSConfigRuleHandler.FAIR_AS_DRF;
import static org.apache.hadoop.yarn.server.resourcemanager.scheduler.fair.converter.FSConfigToCSConfigRuleHandler.MAX_RESOURCES;
import static org.apache.hadoop.yarn.server.resourcemanager.scheduler.fair.converter.FSConfigToCSConfigRuleHandler.MIN_RESOURCES;
import static org.apache.hadoop.yarn.server.resourcemanager.scheduler.fair.converter.FSConfigToCSConfigRuleHandler.PARENT_DYNAMIC_CREATE;

import static org.apache.hadoop.yarn.server.resourcemanager.scheduler.fair.converter.FSConfigToCSConfigRuleHandler.RuleAction.ABORT;
import static org.apache.hadoop.yarn.server.resourcemanager.scheduler.fair.converter.FSConfigToCSConfigRuleHandler.RuleAction.WARNING;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyZeroInteractions;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.util.Map;

import org.apache.commons.io.FileUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.service.ServiceStateException;
import org.apache.hadoop.yarn.api.records.Resource;
import org.apache.hadoop.yarn.conf.YarnConfiguration;
import org.apache.hadoop.yarn.server.resourcemanager.placement.PlacementManager;
import org.apache.hadoop.yarn.server.resourcemanager.scheduler.capacity.CapacitySchedulerConfiguration;
import org.apache.hadoop.yarn.server.resourcemanager.scheduler.capacity.placement.schema.MappingRulesDescription;
import org.apache.hadoop.yarn.server.resourcemanager.scheduler.fair.FairSchedulerConfiguration;
import org.apache.hadoop.yarn.util.resource.DominantResourceCalculator;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;

import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * Unit tests for FSConfigToCSConfigConverter.
 *
 */
@RunWith(MockitoJUnitRunner.class)
public class TestFSConfigToCSConfigConverter {
  private static final String CLUSTER_RESOURCE_STRING =
      "vcores=20, memory-mb=240";
  private static final Resource CLUSTER_RESOURCE =
      Resource.newInstance(16384, 16);
  private static final String FILE_PREFIX = "file:";
  private static final String FAIR_SCHEDULER_XML =
      prepareFileName("fair-scheduler-conversion.xml");
  private static final String FS_INVALID_PLACEMENT_RULES_XML =
      prepareFileName("fair-scheduler-invalidplacementrules.xml");
  private static final String FS_ONLY_FAIR_POLICY_XML =
      prepareFileName("fair-scheduler-onlyfairpolicy.xml");
  private static final String FS_MIXED_POLICY_XML =
      prepareFileName("fair-scheduler-orderingpolicy-mixed.xml");
  private static final String FS_NO_PLACEMENT_RULES_XML =
      prepareFileName("fair-scheduler-noplacementrules.xml");
  private static final String FS_MAX_AM_SHARE_DISABLED_XML =
      prepareFileName("fair-scheduler-defaultMaxAmShareDisabled.xml");

  @Mock
  private FSConfigToCSConfigRuleHandler ruleHandler;

  @Mock
  private DryRunResultHolder dryRunResultHolder;

  @Mock
  private QueuePlacementConverter placementConverter;

  private FSConfigToCSConfigConverter converter;
  private Configuration config;

  @Rule
  public ExpectedException expectedException = ExpectedException.none();
  private FSConfigConverterTestCommons converterTestCommons;

  private static String prepareFileName(String f) {
    return FILE_PREFIX + new File("src/test/resources/" + f).getAbsolutePath();
  }

  private static final String FAIR_SCHEDULER_XML_INVALID =
      prepareFileName("fair-scheduler-invalid.xml");
  private static final String YARN_SITE_XML =
      prepareFileName("yarn-site-with-allocation-file-ref.xml");
  private static final String YARN_SITE_XML_NO_REF_TO_FS_XML =
      prepareFileName("yarn-site.xml");
  private static final String YARN_SITE_XML_INVALID =
      prepareFileName("yarn-site-with-invalid-allocation-file-ref.xml");
  private static final String CONVERSION_RULES_FILE =
      new File("src/test/resources/conversion-rules.properties")
        .getAbsolutePath();

  private ConversionOptions createDefaultConversionOptions() {
    return new ConversionOptions(new DryRunResultHolder(), false);
  }

  @Before
  public void setup() throws IOException {
    config = new Configuration(false);
    config.set(FairSchedulerConfiguration.ALLOCATION_FILE, FAIR_SCHEDULER_XML);
    config.setBoolean(FairSchedulerConfiguration.MIGRATION_MODE, true);
    config.setBoolean(FairSchedulerConfiguration.USER_AS_DEFAULT_QUEUE, true);
    createConverter();
    converterTestCommons = new FSConfigConverterTestCommons();
    converterTestCommons.setUp();
  }

  @After
  public void tearDown() {
    converterTestCommons.tearDown();
  }

  private void createConverter() {
    converter = new FSConfigToCSConfigConverter(ruleHandler,
        createDefaultConversionOptions());
    converter.setClusterResource(CLUSTER_RESOURCE);
    converter.setConvertPlacementRules(false);
  }

  private FSConfigToCSConfigConverterParams.Builder
      createDefaultParamsBuilder() {
    return FSConfigToCSConfigConverterParams.Builder.create()
        .withYarnSiteXmlConfig(YARN_SITE_XML)
        .withOutputDirectory(FSConfigConverterTestCommons.OUTPUT_DIR);
  }

  private FSConfigToCSConfigConverterParams.Builder
      createParamsBuilder(String yarnSiteConfig) {
    return FSConfigToCSConfigConverterParams.Builder.create()
        .withYarnSiteXmlConfig(yarnSiteConfig)
        .withOutputDirectory(FSConfigConverterTestCommons.OUTPUT_DIR);
  }

  @Test
  public void testDefaultMaxAMShare() throws Exception {
    converter.convert(config);

    Configuration conf = converter.getCapacitySchedulerConfig();
    String maxAmShare =
        conf.get(CapacitySchedulerConfiguration.
            MAXIMUM_APPLICATION_MASTERS_RESOURCE_PERCENT);

    assertEquals("Default max AM share", "0.16", maxAmShare);

    assertEquals("root.admins.alice max-am-resource-percent", "0.15",
        conf.get(PREFIX + "root.admins.alice.maximum-am-resource-percent"));

    assertNull("root.users.joe maximum-am-resource-percent should be null",
        conf.get(PREFIX + "root.users.joe maximum-am-resource-percent"));
  }

  @Test
  public void testDefaultMaxAMShareDisabled() throws Exception {
    FSConfigToCSConfigConverterParams params = createDefaultParamsBuilder()
        .withClusterResource(CLUSTER_RESOURCE_STRING)
        .withFairSchedulerXmlConfig(FS_MAX_AM_SHARE_DISABLED_XML)
        .build();

    converter.convert(params);

    Configuration conf = converter.getCapacitySchedulerConfig();

    // -1.0 means disabled ==> 1.0 in CS
    assertEquals("Default max-am-resource-percent", "1.0",
        conf.get(CapacitySchedulerConfiguration.
            MAXIMUM_APPLICATION_MASTERS_RESOURCE_PERCENT));

    // root.admins.bob -1.0 equals to the default -1.0
    assertNull("root.admins.bob maximum-am-resource-percent should be null",
        conf.get(PREFIX + "root.admins.bob.maximum-am-resource-percent"));

    // root.admins.alice 0.15 != -1.0
    assertEquals("root.admins.alice max-am-resource-percent", "0.15",
        conf.get(PREFIX + "root.admins.alice.maximum-am-resource-percent"));

    // root.users.joe is unset, inherits -1.0
    assertNull("root.users.joe maximum-am-resource-percent should be null",
        conf.get(PREFIX + "root.users.joe.maximum-am-resource-percent"));
  }

  @Test
  public void testConvertACLs() throws Exception {
    converter.convert(config);

    Configuration conf = converter.getCapacitySchedulerConfig();

    // root
    assertEquals("root submit ACL", "alice,bob,joe,john hadoop_users",
        conf.get(PREFIX + "root.acl_submit_applications"));
    assertEquals("root admin ACL", "alice,bob,joe,john hadoop_users",
        conf.get(PREFIX + "root.acl_administer_queue"));

    // root.admins.bob
    assertEquals("root.admins.bob submit ACL", "bob ",
        conf.get(PREFIX + "root.admins.bob.acl_submit_applications"));
    assertEquals("root.admins.bob admin ACL", "bob ",
        conf.get(PREFIX + "root.admins.bob.acl_administer_queue"));

    // root.admins.alice
    assertEquals("root.admins.alice submit ACL", "alice ",
        conf.get(PREFIX + "root.admins.alice.acl_submit_applications"));
    assertEquals("root.admins.alice admin ACL", "alice ",
        conf.get(PREFIX + "root.admins.alice.acl_administer_queue"));

    // root.users.john
    assertEquals("root.users.john submit ACL", "john ",
        conf.get(PREFIX + "root.users.john.acl_submit_applications"));
    assertEquals("root.users.john admin ACL", "john ",
        conf.get(PREFIX + "root.users.john.acl_administer_queue"));

    // root.users.joe
    assertEquals("root.users.joe submit ACL", "joe ",
        conf.get(PREFIX + "root.users.joe.acl_submit_applications"));
    assertEquals("root.users.joe admin ACL", "joe ",
        conf.get(PREFIX + "root.users.joe.acl_administer_queue"));
  }

  @Test
  public void testDefaultQueueMaxParallelApps() throws Exception {
    converter.convert(config);

    Configuration conf = converter.getCapacitySchedulerConfig();

    assertEquals("Default max parallel apps", 15,
        conf.getInt(PREFIX + "max-parallel-apps", -1));
  }

  @Test
  public void testSpecificQueueMaxParallelApps() throws Exception {
    converter.convert(config);

    Configuration conf = converter.getCapacitySchedulerConfig();

    assertEquals("root.admins.alice max parallel apps", 2,
        conf.getInt(PREFIX + "root.admins.alice.max-parallel-apps", -1));
  }

  @Test
  public void testDefaultUserMaxParallelApps() throws Exception {
    converter.convert(config);

    Configuration conf = converter.getCapacitySchedulerConfig();
    int userMaxParallelApps =
        conf.getInt(
            PREFIX + "user.max-parallel-apps", -1);

    assertEquals("Default user max parallel apps", 10,
        userMaxParallelApps);
  }

  @Test
  public void testSpecificUserMaxParallelApps() throws Exception {
    converter.convert(config);

    Configuration conf = converter.getCapacitySchedulerConfig();

    assertEquals("Max parallel apps for alice", 30,
        conf.getInt(PREFIX + "user.alice.max-parallel-apps", -1));
    assertNull("Max parallel apps should be undefined for user bob",
        conf.get(PREFIX + "user.bob.max-parallel-apps"));
    assertNull("Max parallel apps should be undefined for user joe",
        conf.get(PREFIX + "user.joe.max-parallel-apps"));
    assertNull("Max parallel apps should be undefined for user john",
        conf.get(PREFIX + "user.john.max-parallel-apps"));
  }

  @Test
  public void testQueueMaxChildCapacityNotSupported() throws Exception {
    expectedException.expect(UnsupportedPropertyException.class);
    expectedException.expectMessage("test");

    Mockito.doThrow(new UnsupportedPropertyException("test"))
      .when(ruleHandler).handleMaxChildCapacity();

    converter.convert(config);
  }

  @Test
  public void testReservationSystemNotSupported() throws Exception {
    expectedException.expect(UnsupportedPropertyException.class);
    expectedException.expectMessage("maxCapacity");

    Mockito.doThrow(new UnsupportedPropertyException("maxCapacity"))
      .when(ruleHandler).handleMaxChildCapacity();
    config.setBoolean(YarnConfiguration.RM_RESERVATION_SYSTEM_ENABLE, true);

    converter.convert(config);
  }

  @Test
  public void testConvertFSConfigurationClusterResource() throws Exception {
    FSConfigToCSConfigConverterParams params = createDefaultParamsBuilder()
        .withClusterResource(CLUSTER_RESOURCE_STRING)
        .build();
    converter.convert(params);
    assertEquals("Resource", Resource.newInstance(240, 20),
        converter.getClusterResource());
  }

  @Test
  public void testConvertFSConfigPctModeUsedAndClusterResourceDefined()
      throws Exception {
    FSConfigToCSConfigConverterParams params = createDefaultParamsBuilder()
            .withClusterResource(CLUSTER_RESOURCE_STRING)
            .build();
    converter.convert(params);
    assertEquals("Resource", Resource.newInstance(240, 20),
        converter.getClusterResource());
  }

  @Test
  public void testConvertFSConfigurationClusterResourceInvalid()
      throws Exception {
    FSConfigToCSConfigConverterParams params = createDefaultParamsBuilder()
            .withClusterResource("vcores=20, memory-mb=240G")
            .build();

    expectedException.expect(ConversionException.class);
    expectedException.expectMessage("Error while parsing resource");

    converter.convert(params);
  }

  @Test
  public void testConvertFSConfigurationClusterResourceInvalid2()
      throws Exception {
    FSConfigToCSConfigConverterParams params = createDefaultParamsBuilder()
        .withClusterResource("vcores=20, memmmm=240")
        .build();

    expectedException.expect(ConversionException.class);
    expectedException.expectMessage("Error while parsing resource");

    converter.convert(params);
  }

  @Test
  public void testConvertFSConfigurationRulesFile() throws Exception {
    ruleHandler = new FSConfigToCSConfigRuleHandler(
        createDefaultConversionOptions());
    createConverter();

    FSConfigToCSConfigConverterParams params =
        createDefaultParamsBuilder()
            .withConversionRulesConfig(CONVERSION_RULES_FILE)
            .withClusterResource("vcores=20, memory-mb=2400")
            .build();

    try {
      converter.convert(params);
      fail("Should have thrown UnsupportedPropertyException!");
    } catch (UnsupportedPropertyException e) {
      //need to catch exception so we can check the rules
    }

    ruleHandler = converter.getRuleHandler();
    Map<String, FSConfigToCSConfigRuleHandler.RuleAction> actions =
        ruleHandler.getActions();

    assertEquals("maxCapacityPercentage",
        ABORT, actions.get(MAX_CAPACITY_PERCENTAGE));
    assertEquals("maxChildCapacity",
        ABORT, actions.get(MAX_CHILD_CAPACITY));
    assertEquals("dynamicMaxAssign",
        ABORT, actions.get(DYNAMIC_MAX_ASSIGN));
    assertEquals("reservationSystem",
        ABORT, actions.get(RESERVATION_SYSTEM));
    assertEquals("queueAutoCreate",
        ABORT, actions.get(QUEUE_AUTO_CREATE));
  }

  @Test
  public void testConvertFSConfigurationWithoutRulesFile() throws Exception {
    ruleHandler = new FSConfigToCSConfigRuleHandler(
        createDefaultConversionOptions());
    createConverter();

    FSConfigToCSConfigConverterParams params =
        createDefaultParamsBuilder()
            .withClusterResource(CLUSTER_RESOURCE_STRING)
            .build();

    converter.convert(params);

    ruleHandler = converter.getRuleHandler();
    Map<String, FSConfigToCSConfigRuleHandler.RuleAction> actions =
        ruleHandler.getActions();

    assertEquals("maxCapacityPercentage",
        WARNING, actions.get(MAX_CAPACITY_PERCENTAGE));
    assertEquals("maxChildCapacity",
        WARNING, actions.get(MAX_CHILD_CAPACITY));
    assertEquals("dynamicMaxAssign",
        WARNING, actions.get(DYNAMIC_MAX_ASSIGN));
    assertEquals("reservationSystem",
        WARNING, actions.get(RESERVATION_SYSTEM));
    assertEquals("queueAutoCreate",
        WARNING, actions.get(QUEUE_AUTO_CREATE));
    assertEquals("childStaticDynamicConflict",
        WARNING, actions.get(CHILD_STATIC_DYNAMIC_CONFLICT));
    assertEquals("parentChildCreateDiffers",
        WARNING, actions.get(PARENT_CHILD_CREATE_DIFFERS));
    assertEquals("fairAsDrf",
        WARNING, actions.get(FAIR_AS_DRF));
    assertEquals("maxResources",
        WARNING, actions.get(MAX_RESOURCES));
    assertEquals("minResources",
        WARNING, actions.get(MIN_RESOURCES));
    assertEquals("parentDynamicCreate",
        WARNING, actions.get(PARENT_DYNAMIC_CREATE));
  }

  @Test
  public void testConvertFSConfigurationUndefinedYarnSiteConfig()
      throws Exception {
    FSConfigToCSConfigConverterParams params =
        FSConfigToCSConfigConverterParams.Builder.create()
            .withYarnSiteXmlConfig(null)
            .withOutputDirectory(FSConfigConverterTestCommons.OUTPUT_DIR)
            .build();

    expectedException.expect(PreconditionException.class);
    expectedException.expectMessage(
        "yarn-site.xml configuration is not defined");

    converter.convert(params);
  }

  @Test
  public void testConvertCheckOutputDir() throws Exception {
    FSConfigToCSConfigConverterParams params = createDefaultParamsBuilder()
        .withClusterResource(CLUSTER_RESOURCE_STRING)
        .withConvertPlacementRules(true)
        .withPlacementRulesToFile(true)
        .build();

    converter.convert(params);

    Configuration conf =
        getConvertedCSConfig(FSConfigConverterTestCommons.OUTPUT_DIR);

    File capacityFile = new File(FSConfigConverterTestCommons.OUTPUT_DIR,
        "capacity-scheduler.xml");
    assertTrue("Capacity file exists", capacityFile.exists());
    assertTrue("Capacity file length > 0", capacityFile.length() > 0);
    assertTrue("No. of configuration elements > 0", conf.size() > 0);

    File yarnSiteFile = new File(FSConfigConverterTestCommons.OUTPUT_DIR,
        "yarn-site.xml");
    assertTrue("Yarn site exists", yarnSiteFile.exists());
    assertTrue("Yarn site length > 0", yarnSiteFile.length() > 0);

    File mappingRulesFile = new File(FSConfigConverterTestCommons.OUTPUT_DIR,
        "mapping-rules.json");
    assertTrue("Mapping rules file exists", mappingRulesFile.exists());
    assertTrue("Mapping rules file length > 0", mappingRulesFile.length() > 0);
  }

  @Test
  public void testFairSchedulerXmlIsNotDefinedNeitherDirectlyNorInYarnSiteXml()
      throws Exception {
    FSConfigToCSConfigConverterParams params =
        createParamsBuilder(YARN_SITE_XML_NO_REF_TO_FS_XML)
        .withClusterResource(CLUSTER_RESOURCE_STRING)
        .build();

    expectedException.expect(PreconditionException.class);
    expectedException.expectMessage("fair-scheduler.xml is not defined");
    converter.convert(params);
  }

  @Test
  public void testInvalidFairSchedulerXml() throws Exception {
    FSConfigToCSConfigConverterParams params = createDefaultParamsBuilder()
        .withClusterResource(CLUSTER_RESOURCE_STRING)
        .withFairSchedulerXmlConfig(FAIR_SCHEDULER_XML_INVALID)
        .build();

    expectedException.expect(RuntimeException.class);
    converter.convert(params);
  }

  @Test
  public void testInvalidYarnSiteXml() throws Exception {
    FSConfigToCSConfigConverterParams params =
        createParamsBuilder(YARN_SITE_XML_INVALID)
        .withClusterResource(CLUSTER_RESOURCE_STRING)
        .build();

    expectedException.expect(RuntimeException.class);
    converter.convert(params);
  }

  @Test
  public void testConversionWithInvalidPlacementRules() throws Exception {
    config = new Configuration(false);
    config.set(FairSchedulerConfiguration.ALLOCATION_FILE,
        FS_INVALID_PLACEMENT_RULES_XML);
    config.setBoolean(FairSchedulerConfiguration.MIGRATION_MODE, true);
    expectedException.expect(ServiceStateException.class);

    converter.convert(config);
  }

  @Test
  public void testConversionWhenInvalidPlacementRulesIgnored()
      throws Exception {
    FSConfigToCSConfigConverterParams params = createDefaultParamsBuilder()
        .withClusterResource(CLUSTER_RESOURCE_STRING)
        .withFairSchedulerXmlConfig(FS_INVALID_PLACEMENT_RULES_XML)
        .build();

    ConversionOptions conversionOptions = createDefaultConversionOptions();
    conversionOptions.setNoTerminalRuleCheck(true);

    converter = new FSConfigToCSConfigConverter(ruleHandler,
        conversionOptions);

    converter.convert(params);

    // expected: no exception
  }

  @Test
  public void testConversionWhenOnlyFairPolicyIsUsed() throws Exception {
    FSConfigToCSConfigConverterParams params = createDefaultParamsBuilder()
        .withClusterResource(CLUSTER_RESOURCE_STRING)
        .withFairSchedulerXmlConfig(FS_ONLY_FAIR_POLICY_XML)
        .build();

    converter.convert(params);

    Configuration convertedConfig = converter.getYarnSiteConfig();

    assertEquals("Resource calculator class shouldn't be set", null,
        convertedConfig.getClass(
            CapacitySchedulerConfiguration.RESOURCE_CALCULATOR_CLASS, null));
  }

  @Test
  public void testConversionWhenMixedPolicyIsUsed() throws Exception {
    FSConfigToCSConfigConverterParams params = createDefaultParamsBuilder()
        .withClusterResource(CLUSTER_RESOURCE_STRING)
        .withFairSchedulerXmlConfig(FS_MIXED_POLICY_XML)
        .build();

    converter.convert(params);

    Configuration convertedConfig = converter.getYarnSiteConfig();

    assertEquals("Resource calculator type", DominantResourceCalculator.class,
        convertedConfig.getClass(
            CapacitySchedulerConfiguration.RESOURCE_CALCULATOR_CLASS, null));
  }

  @Test
  public void testUserAsDefaultQueueWithPlacementRules()
      throws Exception {
    testUserAsDefaultQueueAndPlacementRules(true);
  }

  @Test
  public void testUserAsDefaultQueueWithoutPlacementRules()
      throws Exception {
    testUserAsDefaultQueueAndPlacementRules(false);
  }

  private void testUserAsDefaultQueueAndPlacementRules(
      boolean hasPlacementRules) throws Exception {
    config = new Configuration(false);
    config.setBoolean(FairSchedulerConfiguration.MIGRATION_MODE, true);

    if (hasPlacementRules) {
      config.set(FairSchedulerConfiguration.ALLOCATION_FILE,
          FAIR_SCHEDULER_XML);
    } else {
      config.set(FairSchedulerConfiguration.ALLOCATION_FILE,
          FS_NO_PLACEMENT_RULES_XML);
    }

    config.setBoolean(FairSchedulerConfiguration.USER_AS_DEFAULT_QUEUE,
        true);

    converter.setConvertPlacementRules(true);
    converter.setConsoleMode(true);
    converter.convert(config);
    String json = converter.getCapacitySchedulerConfig()
        .get(CapacitySchedulerConfiguration.MAPPING_RULE_JSON);

    MappingRulesDescription description =
        new ObjectMapper()
          .reader()
          .forType(MappingRulesDescription.class)
          .readValue(json);

    if (hasPlacementRules) {
      // fs.xml defines 5 rules
      assertEquals("Number of rules", 5, description.getRules().size());
    } else {
      // by default, FS internally creates 2 rules
      assertEquals("Number of rules", 2, description.getRules().size());
    }
  }

  @Test
  public void testPlacementRulesConversionDisabled() throws Exception {
    FSConfigToCSConfigConverterParams params = createDefaultParamsBuilder()
        .withClusterResource(CLUSTER_RESOURCE_STRING)
        .withFairSchedulerXmlConfig(FAIR_SCHEDULER_XML)
        .withConvertPlacementRules(false)
        .build();

    converter.setPlacementConverter(placementConverter);
    converter.convert(params);

    verifyZeroInteractions(placementConverter);
  }

  @Test
  public void testPlacementRulesConversionEnabled() throws Exception {
    FSConfigToCSConfigConverterParams params = createDefaultParamsBuilder()
        .withClusterResource(CLUSTER_RESOURCE_STRING)
        .withFairSchedulerXmlConfig(FAIR_SCHEDULER_XML)
        .withConvertPlacementRules(true)
        .build();

    converter.setPlacementConverter(placementConverter);
    converter.convert(params);

    verify(placementConverter).convertPlacementPolicy(
        any(PlacementManager.class),
        any(FSConfigToCSConfigRuleHandler.class),
        any(CapacitySchedulerConfiguration.class),
        anyBoolean());
    assertTrue(converter.getCapacitySchedulerConfig().getBoolean(
        CapacitySchedulerConfiguration.ENABLE_QUEUE_MAPPING_OVERRIDE, false));
  }

  @Test
  public void testConversionWhenAsyncSchedulingIsEnabled()
          throws Exception {
    boolean schedulingEnabledValue =  testConversionWithAsyncSchedulingOption(true);
    assertTrue("Asynchronous scheduling should be true", schedulingEnabledValue);
  }

  @Test
  public void testConversionWhenAsyncSchedulingIsDisabled() throws Exception {
    boolean schedulingEnabledValue =  testConversionWithAsyncSchedulingOption(false);
    assertEquals("Asynchronous scheduling should be the default value",
            CapacitySchedulerConfiguration.DEFAULT_SCHEDULE_ASYNCHRONOUSLY_ENABLE,
            schedulingEnabledValue);
  }

  @Test
  public void testSiteDisabledPreemptionWithObserveOnlyConversion()
      throws Exception{
    FSConfigToCSConfigConverterParams params = createDefaultParamsBuilder()
        .withDisablePreemption(FSConfigToCSConfigConverterParams.
            PreemptionMode.OBSERVE_ONLY)
        .build();

    converter.convert(params);
    assertTrue("The observe only should be true",
        converter.getCapacitySchedulerConfig().
            getBoolean(CapacitySchedulerConfiguration.
                PREEMPTION_OBSERVE_ONLY, false));
  }

  private boolean testConversionWithAsyncSchedulingOption(boolean enabled) throws Exception {
    FSConfigToCSConfigConverterParams params = createDefaultParamsBuilder()
            .withClusterResource(CLUSTER_RESOURCE_STRING)
            .withFairSchedulerXmlConfig(FAIR_SCHEDULER_XML)
            .build();

    ConversionOptions conversionOptions = createDefaultConversionOptions();
    conversionOptions.setEnableAsyncScheduler(enabled);

    converter = new FSConfigToCSConfigConverter(ruleHandler,
            conversionOptions);

    converter.convert(params);

    Configuration convertedConfig = converter.getYarnSiteConfig();

    return convertedConfig.getBoolean(CapacitySchedulerConfiguration.SCHEDULE_ASYNCHRONOUSLY_ENABLE,
            CapacitySchedulerConfiguration.DEFAULT_SCHEDULE_ASYNCHRONOUSLY_ENABLE);
  }

  private Configuration getConvertedCSConfig(String dir) throws IOException {
    File capacityFile = new File(dir, "capacity-scheduler.xml");
    ByteArrayInputStream input =
        new ByteArrayInputStream(FileUtils.readFileToByteArray(capacityFile));
    Configuration conf = new Configuration(false);
    conf.addResource(input);

    return conf;
  }
}


text:
\section{Primární data}
\label{sec:primarydata}

Primární data ze simulací jsou příliš rozsáhlá, aby bylo možné je zařadit jako textovou přílohu. Jsou přiložena elektronicky k práci v SISu.

Zde je stručně popsán jejich formát a jak je v načíst pro případnou další analýzu.

Data jsou uložena v souborech \texttt{result\_\textit{XXX}\_0.\textit{YY}\_0.\textit{ZZ}}, kde
\textit{XXX} je počáteční velikost populace,
0.\textit{YY} je podíl alel, u kterých se projevuje negativní dominance,
a 0.\textit{ZZ} je podíl pleiotropních alel.

Každý soubor obsahuje statistiky pro všech 512 běhů \textit{fbeagle} s danými parametry. Ty jsou uloženy jako
haskellový literál typu \texttt{[[(String, [(Integer, Double)])]]}, ale vzhledem k jednoduché textové
reprezentaci je možné je připadně naparsovat i v jiném programovacím jazyce.

Semantika dat je následující -- jde o seznam výsledků pro všechny běhy s danou dvojicí parametrů. Každý výsledek
je seznam dvojic, prvním členem je jméno měřené veličiny (např. \textit{"avg\_fitness"} pro průměrnou hodnotu
fitness v populaci v daném kroku) a druhým členem seznam hodnot. Každá hodnota je dvojice, kde první člen je
číslo kroku simulace a druhý člen je hodnota dané veličiny. Tato hodnota je vždy číslo s plovoucí desetinnou čárkou,
i pokud by charakter veličiny umožňoval užít celé číslo. Pokud hodnota neexistuje (např. je to průměrná fitness vyhynulé
populace), je hodnotou \textit{NaN} (Not A Number).

Pro případné načtení dat z \textit{REPLu Haskellu} lze užít napřiklad tento kód:

\begin{code}[commandchars=\\\{\}]
handle <- openFile (fileName) ReadMode
contents <- hGetContents handle
\textbf{let}
        datas = read contents :: [[(String, [(Integer, Double)])]]
\end{code}

redpajama_set_name: RedPajamaGithub


text:
import { Component, OnInit, OnDestroy, AfterContentInit, NgZone } from '@angular/core';
import { AfterViewChecked, ElementRef, ViewChild } from '@angular/core';

import { ActivatedRoute }               from '@angular/router';
import { Subscription }                 from 'rxjs/Subscription';

import { LayoutService  }               from '../../services/layout.service';
import { SocketService }                from '../../services/socket.service';
import { DataframeAccount }             from '../../services/dataframe.account.service';
import { DataframeMessageHub }          from '../../services/dataframe.messageHub.service';

import * as jQuery                      from 'jquery';
import * as _                           from 'lodash';

@Component (
{
    selector    : 'messageHubProp'
,   templateUrl : './messageHub.component.prop.base.html'
,   styleUrls   : ['./messageHub.component.base.scss']
} )
export class MessageHubComponentPropBase implements OnInit
{
    @ViewChild('scrollMe') private myScrollContainer: ElementRef;

    current_height          : string;
    message_subscription    : Subscription;
    height_subscription     : Subscription;

    view_config         : any =
    {
        filter          : '',
        message         : ''
    };

    selected_offline    : boolean = true;
    selected_contact    : any     = { contact_name : '', contact_number : '' };
    listof_contact      : any []  =
    [
        { contact_name  : 'gabriel', contact_number : '+19547745358' },
        { contact_name  : 'kara',    contact_number : '+19545361329' },
        { contact_name  : 'logan',   contact_number : '+19548069113' },
        { contact_name  : 'luis',    contact_number : '+17867971927' },
        { contact_name  : 'maya',    contact_number : '+13054505516' },
    ];

    listof_message      : any [] = [];

    constructor ( protected _ngZone             : NgZone
                , private _route                : ActivatedRoute
                , private _layoutService        : LayoutService
                , private _socketService        : SocketService
                , private _dataframeMessageHub  : DataframeMessageHub )
    {
    }

    ngOnInit ( ) : void
    {
        this.height_subscription = this._layoutService.observe_content_height ( ).subscribe (

            value => { this.resizeFn ( ); }

        );

        this._socketService.engine_init ( );
    }

    ngAfterViewChecked()
    {
        this.scrollToBottom ( );
    }

    scrollToBottom ( ) : void
    {
        try
        {
            // this.myScrollContainer.nativeElement.scrollTop = this.myScrollContainer.nativeElement.scrollHeight;

            let ele = document.getElementsByClassName('hub-message-col');

            let eleArray = <Element[]>Array.prototype.slice.call(ele);

            eleArray.map ( val =>
            {
                val.scrollTop = val.scrollHeight;

            } );

        } catch ( err )
        {

        }
    }

    ngAfterContentInit ( )
    {
        this.message_subscription = this._socketService.observe_message ( ).subscribe (

            value => this._ngZone.run ( ( ) =>
            {
                console.log ( `message posted...` );

                this.refresh_history ( );

                console.log ( `message posted.` );
            } )

        );

    }

    ngOnDestroy ( )
    {
        this.height_subscription.unsubscribe();
    }

    private resizeFn ( )
    {
        this.current_height = this._layoutService.get_content_height ( );
    }

    on_toolbar_send ( )
    {
        let payload =
        {
            messageTo   : this.selected_contact.contact_number,
            messageBody : this.view_config.message
        };

        this._dataframeMessageHub.write ( payload ) .then (

            ( value ) =>
            {
                console.log ( '_dataframeMessageHub.write -', value );

                this.view_config.message = '';

                this.refresh_history ( );
            },
            ( error ) =>
            {
                console.log ( '!!! ERROR : _dataframeMessageHub.write -', error );
            }

        );

    }

    refresh_history ( ) : Promise<any>
    {
        return new Promise ( ( resolve, reject ) => this._ngZone.run ( ( ) =>
        {
            if ( ! this.selected_contact ||
                 ! this.selected_contact.contact_number ||
                 0 === this.selected_contact.contact_number.length )
            {
                resolve ( true );

            } else
            {
                this.selected_offline = false;

                let payload =
                {
                    messageTo   : this.selected_contact.contact_number,
                    messageBody : this.view_config.message
                };

                this._dataframeMessageHub.history ( payload ) .then (

                    ( value ) =>
                    {
                        console.log ( '_dataframeMessageHub.history -', value );

                        this.listof_message = value;

                        this.listof_message = _.sortBy ( this.listof_message, 'dateCreated' );

                        this.scrollToBottom ( );

                        resolve ( true );
                    },
                    ( error ) =>
                    {
                        this.listof_message   = [];

                        console.log ( '!!! ERROR : _dataframeMessageHub.history -', error );

                        resolve ( true );

                    }

                );

            }

        } ) );

    }

    on_change_selected_contact ( event ) : void
    {
        this.refresh_history ( );
    }

}


text:
var fs = require('./fs'),
  settings = require('./settings'),
  path = require('./path'),
  q = require('q'),
  sortBy = require('sort-by'),
  slug = require('slug'),
  truncate = require('html-truncate'),
  strip = require('striptags'),
  all = require('promise-all'),
  marked = require('marked'),
  highlight = require('./highlight');

exports.read = read;

/**
 * Read all posts from the posts directory
 *
 * @returns {Promise}
 */
function read() {
  return checkForPostsDir()
    .then(function (exists) {
      if (!exists)
        throw new Error(
          'Can not find posts directory: "' +
            settings.postsDir +
            '", have you run "jiffy init"?'
        );
      return fs.readDir(settings.postsDir);
    })
    .then(function (postDirs) {
      return q.all(postDirs.map(getPostInfo));
    })
    .then(removeInvalidPosts)
    .then(function (posts) {
      if (!posts.length)
        throw new Error('No posts found in: "' + settings.postsDir + '"');
      return posts.sort(sortBy('-date', 'name'));
    });
}

function checkForPostsDir() {
  return fs.exists(settings.postsDir);
}

function getPostInfo(dir) {
  var post = {};
  post.name = getPostName(dir);
  post.date = getPostDate(dir);
  post.url = nameToUrl('posts', post.name);
  post.fileName = nameToFileName('posts', post.name);

  if (['.', '_'].indexOf(dir[0]) > -1 || !post.name) return;

  var markdown = q.defer(),
    meta = q.defer();

  var hasPost = false,
    hasMeta = false;

  var postDir = path.join(settings.postsDir, dir);

  fs.stat(postDir).then(function (stats) {
    if (stats.isFile()) {
      if (!path.isMarkdown(postDir))
        markdown.reject(
          new Error('The file "' + postDir + '" is no markdown file!')
        );
      markdown.resolve(fs.readFile(postDir, 'utf-8'));
      meta.resolve({});
    } else {
      fs.readDir(postDir).then(function (files) {
        files.forEach(function (fileName) {
          var file = path.join(settings.postsDir, dir, fileName);
          if (path.isMarkdown(file)) {
            hasPost = true;
            markdown.resolve(fs.readFile(file, 'utf-8'));
          } else if (path.isJson(file)) {
            hasMeta = true;
            meta.resolve(fs.readJson(file));
          }
        });
        if (!hasPost)
          markdown.reject(
            new Error('Missing content (markdown file) for post: ' + post.name)
          );
        if (!hasMeta) meta.resolve({});
      });
    }
  });

  post.content = getHtml(markdown.promise);
  post.shortContent = getShortHtml(post.content);
  post.contentStripped = getStripped(post.content);
  post.shortStripped = getStripped(post.shortContent);
  post.category = getCategory(meta.promise);
  post.author = getAuthor(meta.promise);
  post.tags = getTags(meta.promise);
  post.datetime = getDatetime(post.date, meta.promise);
  post.pubDate = getPubDate(post.datetime);
  post.guid = getGuid(meta.promise);
  post.title = getTitle(post.name, meta.promise);

  return all(post);
}

function getPostName(dir) {
  var name = path.basename(dir).split(' - ').slice(1).join(' - ');
  if (path.isMarkdown(name)) return name.replace(/\.(md|markdown)$/, '');
  return name;
}

function getPostDate(dir) {
  return path.basename(dir).split(' - ')[0];
}

function nameToUrl(dir, name) {
  return dir + '/' + urlFriendlyName(name) + '.html';
}

function nameToFileName(dir, name) {
  return path.join(dir, urlFriendlyName(name) + '.html');
}

function urlFriendlyName(name) {
  return slug(name.toLowerCase());
}

function getHtml(markdown) {
  return markdown.then(function (markdown) {
    return marked(markdown, {highlight: highlight});
  });
}

function getTitle(name, meta) {
  return meta.then(function (meta) {
    return meta.title || name;
  });
}

function getShortHtml(html) {
  if (!settings.truncate) return html;

  return html.then(function (code) {
    return truncate(code, settings.truncate);
  });
}

function getStripped(promise) {
  return promise.then(function (content) {
    return strip(content);
  });
}

function getCategory(meta) {
  return meta.then(function (meta) {
    var name = meta.category || settings.defaultCategory;
    return {
      name: name,
      url: nameToUrl('category', name),
      fileName: nameToFileName('category', name),
    };
  });
}

function getAuthor(meta) {
  return meta.then(function (meta) {
    return settings.getAuthor(meta.author);
  });
}

function getTags(meta) {
  return meta.then(function (meta) {
    return (meta.tags || []).map(function (name) {
      return {
        name: name,
        url: nameToUrl('tags', name),
        fileName: nameToFileName('tags', name),
      };
    });
  });
}

function getDatetime(date, meta) {
  return meta.then(function (meta) {
    return new Date(
      Date.parse(meta.datetime || date + ' ' + (meta.time || '12:00:00 GMT'))
    );
  });
}

function getPubDate(datetimeStr) {
  return datetimeStr.then(function (datetime) {
    return datetime.toGMTString();
  });
}

function getGuid(meta) {
  return meta.then(function (meta) {
    return meta.guid;
  });
}

function removeInvalidPosts(posts) {
  return posts.filter(function (post) {
    return post;
  });
}


text:
import { TestBed } from '@angular/core/testing';
import { StorageService } from '@renet-consulting/storage';
import { IToken } from './token';
import { TokenService } from './token.service';

describe('TokenService', () => {

    let service: TokenService;

    let storage: jasmine.SpyObj<StorageService>;
    const key = 'token';

    beforeEach(() => {
        TestBed.configureTestingModule({
            providers: [
                { provide: StorageService, useValue: jasmine.createSpyObj<StorageService>('StorageService', ['get', 'set', 'remove']) }
            ]
        });

        service = TestBed.inject(TokenService);
        storage = TestBed.inject(StorageService) as jasmine.SpyObj<StorageService>;
    });

    it('should be created', () => {
        expect(service).toBeTruthy();
    });
    describe('valid', () => {
        it('true', () => {
            const token = { access_token: 'bob', refresh_token: 'mark' } as IToken;
            storage.get.and.returnValue(token);
            expect(service.valid).toEqual(true);
            expect(storage.get).toHaveBeenCalledWith(key);
        });
        it('storage returns empty object', () => {
            storage.get.and.returnValue({});
            expect(service.valid).toEqual(null);
            expect(storage.get).toHaveBeenCalledWith(key);
        });
        it('storage returns null', () => {
            storage.get.and.returnValue(null);
            expect(service.valid).toEqual(null);
            expect(storage.get).toHaveBeenCalledWith(key);
        });
    });
    describe('expired', () => {
        it('false, because token === null', () => {
            expect(service.expired).toEqual(false);
        });
        it('false, because expired_at more than now', () => {
            const expired_at = new Date(new Date().valueOf() + 1000).toString();
            const token = { access_token: 'bob', refresh_token: 'mark', expired_at } as IToken;
            storage.get.and.returnValue(token);
            expect(service.expired).toEqual(false);
        });
        it('true, because expired_at === undefined', () => {
            const token = { access_token: 'bob', refresh_token: 'mark' } as IToken;
            storage.get.and.returnValue(token);
            expect(service.expired).toEqual(true);
        });
        it('true, because expired_at less than now', () => {
            const expired_at = new Date(new Date().valueOf() - 1000).toString();
            const token = { access_token: 'bob', refresh_token: 'mark', expired_at } as IToken;
            storage.get.and.returnValue(token);
            expect(service.expired).toEqual(true);
        });
        it('true, because expired_at equals now', () => {
            const expired_at = new Date(new Date().valueOf()).toString();
            const token = { access_token: 'bob', refresh_token: 'mark', expired_at } as IToken;
            storage.get.and.returnValue(token);
            expect(service.expired).toEqual(true);
        });
        it('true, date in number format as string from localStorage', () => {
            const value = `{"access_token":"1","refresh_token":"2","expired_at":"1558723213274"}`;
            const token = JSON.parse(value);
            storage.get.and.returnValue(token);
            expect(service.expired).toEqual(true);
        });
        it('true, date in string format', () => {
            const token = {
                access_token: '1',
                refresh_token: '2',
                expired_at: 'Sat May 25 2019 00:27:50 GMT+0300 (Eastern European Summer Time)'
            };
            storage.get.and.returnValue(token);
            expect(service.expired).toEqual(true);
        });
        it('true, date in ISO format', () => {
            const value = `{"access_token":"1","refresh_token":"2","expired_at":"2019-05-24T21:28:11.511Z"}`;
            const token = JSON.parse(value);
            storage.get.and.returnValue(token);
            expect(service.expired).toEqual(true);
        });
    });
    describe('header', () => {
        it('null', () => {
            expect(service.header).toEqual(null);
        });
        it('token_type + access_token', () => {
            const token = { access_token: 'bob', refresh_token: 'mark', token_type: 'type' } as IToken;
            storage.get.and.returnValue(token);
            expect(service.header).toEqual({ authorization: `${token.token_type} ${token.access_token}` });
        });
    });
    it('setToken', () => {
        const token = { access_token: 'bob', refresh_token: 'mark', expires_in: 6 } as IToken;
        const date = new Date();
        const checkDate = new Date(date);
        service.setToken(token, date);
        expect(storage.set).toHaveBeenCalledWith(key, {
            ...token,
            expired_at: checkDate.setTime(checkDate.valueOf() + 1000 * token.expires_in).toString()
        } as IToken);
    });
    it('clean', () => {
        service.clean();
        expect(storage.remove).toHaveBeenCalledWith(key);
    });
});


text:
// Provides enumeration sap.ui.model.UpdateMethod
sap.ui.define(function() {
	"use strict";

	/**
	 * Different methods for update operations.
	 *
	 * @enum {string}
	 * @public
	 * @alias sap.ui.model.odata.UpdateMethod
	 */
	var UpdateMethod = {
		/**
		 * Update requests will be send with HTTP method MERGE.
		 *
		 * @public
		 */
		Merge: "MERGE",

		/**
		 * Update requests will be send with HTTP method PUT.
		 * @public
		 */
		Put: "PUT"
	};

	return UpdateMethod;

}, /* bExport= */ true);


text:
layout: post
title: Endlich...
date: 2013-06-07 21:40:00.000000000 +02:00
categories: article
tags:
- Allgemein
- android
- architektur
- java 8
status: publish
type: post
published: true
meta: {}
author: uwe
---

In den letzten Wochen habe ich mich etwas rar gemacht, was meiner aktuellen Nachfolgeprojektsuche geschuldet war.  Glücklicherweise haben sich die Dinge nun zum Guten gewendet und so kann ein wenig berichten. Für Christian Ullenbooms Vortrag in der kommenden Woche haben wir bereits über 120 Anmeldungen! Bei CKC werdet ihr wieder eine ganze Menge Zeitschriften vorfinden und es gibt Verlosungen von IntelliJ Lizenzen und Abos für das Java Magazin.  Ich freue mich auf den Donnerstag :-)

Lars Vogel kommt im September zu uns! Wer ihn noch nicht kennen sollte (kann ich mir eigentlich nicht vorstellen weil man letztendlich, auf der Suche nach einem guten Tutorial, fast immer bei vogella landet),  der sollte sich unbedingt anmelden.  Innerhalb von 24 Stunden gibt es hier bereits mehr als 30 Anmeldungen und es sind ja noch ein paar Tage bis dahin...

Der Rest des Jahres ist auch bereits verplant, die Einladungen kommen demnächst.

Hier noch ein paar Tipps:

Für die Source Talk Tage in Göttingen wird sich auch Adam Bien vor Ort einfinden. Göttingen ist sowieso eine Reise wert und somit gibt es noch einen guten Grund mehr. Den Link findet ihr hier...

Den aktuellen iJUG-Newsletter möchte ich euch auch nicht vorenthalten

Kommende Woche finden die Eclipse-DemoCamps statt und Infos dazu gibt es bei Bredex und Eclipse . Ich werde voraussichtlich in Hamburg teilnehmen

Ansonsten wünsche ich euch allen da draußen ein schönes Sommerwochenende! Nach diesem Mai haben wir es uns verdient!


text: module.exports = require('./dist/v-touch')


text:
extern "C" {
  #include <stdint.h>
}
#include <arduino.h>
#include <QueueList.h>
#include "Node.h"
#include "EventStore.h"
#include "Timer.h"
class DFRotation:public Node
{
  private:
      String name;
      uint16_t interval;
      uint8_t APin;
      QueueList<Node *> node;
      bool is_off;
      bool debug;
      uint8_t intervalID;
      int oldOutputValue;
  public:
      DFRotation();
      ~DFRotation();
      void
        setUp(String name,uint8_t APin,uint16_t interval,QueueList<Node *> &node, bool debug),
        onMsg();
      void callBack();
};
DFRotation::DFRotation(){
  is_off = true;
}
DFRotation::~DFRotation(){}
void DFRotation::setUp(String name,uint8_t APin,uint16_t interval,QueueList<Node *> &node,bool debug){
    this->name=name;
    this->interval = interval;
    this->APin = APin;
    this->node = node;
    this->debug = debug;
}
void DFRotation::onMsg(){

    if(debug){
      Serial.print(name);
      Serial.println(" start");
    }

    if (eventStore.getEvent().msg[0]==1){
        if (is_off){
            intervalID=timer.setInterval(this-> interval,this);
            is_off=false;
        }
    }
    if (eventStore.getEvent().msg[0]==0){
        if(!is_off){
            timer.clearInterval(intervalID);
            is_off=true;
        }
    }
}
void DFRotation::callBack(){
    int16_t msg[1]={0};
    int sensorValue = analogRead(APin);  // value read from the pot
    // map it to the range of the analog out:
    int outputValue = map(sensorValue, 0, 1023, 0, 255); // value output to the PWM (analog out)

    if (outputValue != oldOutputValue){
        msg[0] = outputValue;
        eventStore.addEvent(node,input,"payload",msg,1);
        oldOutputValue = outputValue;

        if (debug){
            Serial.print("Rotation Analog Value:");
            Serial.println(outputValue);
        }
    }
}
#endif


text:
function link(){
  return {
    restrict: 'A',
    require: 'ngModel',
    link: function(scope, element, attrs, ngModel) {
      ngModel.$validators.link = function(value){
        // Checks if valid url
        // Angular's normal url validator was not sufficient
        return /^(https?:\/\/(?:www\.|(?!www))[^\s\.]+\.[^\s]{2,}|www\.[^\s]+\.[^\s]{2,})$/g.test(value)
      }
    }
  }
}

angular.module('RssReaderApp')
  .directive('link', link);


text:
/**
 * Json Simple Schema
 * properties:
 *   _cache: holds fetched/parsed json schema objects
 * instance methods:
 *   emtpyCache
 *   toSimpleSchema - convert json schema to simple schema
 */

/**
 * Json Simple Schema constructor
 */
JsonSimpleSchema = function JsonSimpleSchema() {
  this._cache = {};
};

/**
 * Empty Cache
 */
JsonSimpleSchema.prototype.emptyCache = function emptyCache() {
  this._cache = {};
};

/**
 * Get Json Schema
 * Get Json schema with all internal and external refs dereferenced
 * @param {object} spec
 * @param {string|object} spec.json - json schema
 * @param {string} spec.url - url where json schema can be fetched
 * @param {function} callback - standard fn(error, result) style callback
 */
function getJsonSchema(spec, callback) {
  checkToSimpleSchemaSpec(spec);
  getJsonSchemaInternal.bind(this)(spec, callback);
}
JsonSimpleSchema.prototype.getJsonSchema = getJsonSchema;

/**
 * To Simple Schema
 */
JsonSimpleSchema.prototype.toSimpleSchema = function toSimpleSchema(spec, callback) {

  function getJsonHandler (error, jsonSchema) {
    if (error) { return callback(error); }
    var simpleSchema;
    try {
      simpleSchema = convertSchema(jsonSchema);
      simpleSchema = new SimpleSchema(simpleSchema);
    } catch(e) {
      return callback(e);
    }
    return callback(null, simpleSchema);
  }

  if (spec.skipDereference && spec.json) {
    if (typeof spec.json === 'string') {
      return parseJson(spec.json, getJsonHandler);
    }
    return getJsonHandler(null, spec.json);
  }
  return getJsonSchema.bind(this)(spec, getJsonHandler);
};

/**
 * Check To Simple Schema Spec
 */
function checkToSimpleSchemaSpec(spec) {
  check(spec, { url: Match.Optional(String), json: Match.Optional(Object) });
  if (!(spec.url || spec.json)) {
    throw new Meteor.Error('toSimpleSchema object must contain a json object or a url');
  }
  if (spec.url) {
    spec.url = isAbsoluteUrl(spec.url) ? spec.url : Meteor.absoluteUrl(spec.url);
  }
}

/**
 * Get Json Schema Internal
 * @param {object} spec - same spec object from 'toSimpleSchema'
 */
function getJsonSchemaInternal(spec, callback) {
  // return schema from cache, if available
  if (spec.url && this._cache[spec.url]) {
    return callback(null, this._cache[spec.url]);
  } else {
    //fetch schema will return spec.json if available, or do HTTP.get on spec.url
    fetchSchema.bind(this)(spec, function (error, jsonSchema) {
      if (error) { return callback(error); }
      spec.json = jsonSchema;
      //find external refs, fetch and convert, then resolve current schema
      resolveExternalRefs.bind(this)(spec, callback);
    }.bind(this));
  }
}

/**
 * Fetch Schema
 * @param {object} spec - same spec object from 'toSimpleSchema'
 */
function fetchSchema(spec, callback) {
  var self = this;
  if (typeof spec.json === 'object') {
    return callback(null, spec.json);
  } else if (typeof spec.json === 'string') {
    return parseJson(spec.json, callback);
  } else {
    HTTP.get(spec.url, function (error, result) {
      if (error) { return callback(error); }
      return parseJson(result.content, callback);
    });
  }
}

/**
 * Parse JSON
 */
function parseJson(json, callback) {
  try {
    json = JSON.parse(json);
  } catch (error) {
    return callback(error);
  }
  return callback(null, json);
}

/**
 * Resolve External Refs
 */
function resolveExternalRefs(spec, callback) {
  var cache = this._cache;
  var schema;
  // get url, internal schema path, and flattened key path for each external ref
  spec.externalRefs = getExternalRefInfo(spec);

  if (spec.externalRefs.length) {
    var resolvedCount = 0;
    spec.externalRefs.forEach(function (refItem) {
      getJsonSchema.bind(this)({url: refItem.url}, function (err, result) {
        insertExternalRef(spec.json, refItem, result);
        if (++resolvedCount === spec.externalRefs.length) {
          schema = resolveInternalRefs.bind(spec.json)();
          if (spec.url) { cache[spec.url] = schema; }
          return callback(null, schema);
        }
      });
    }, this);
  } else {
    schema = resolveInternalRefs.bind(spec.json)();
    if (spec.url) { cache[spec.url] = schema; }
    return callback(null, schema);
  }
}

/**
 * Get External Ref Info
 */
function getExternalRefInfo(spec) {
  // flatten function is imported from flatten.js
  var flatSchema = flatten(spec.json);
  return _.keys(flatSchema).filter(function (key) {
    return (key.indexOf('$ref') > -1) && (flatSchema[key].charAt(0) !== '#');
  })
  .map(function (key) {
    // split the ref on # to get [externalUrl, internalObjectPath]
    var ref = flatSchema[key].split('#');
    return {
      // absolute url of exernal reference
      url: isAbsoluteUrl(ref[0]) ? ref[0] : getRefAbsoluteUrl(spec.url, flatSchema, key),
      // relative path in schema to insert external schema
      relativePath: ref.length > 1 && ref[1],
      // flattened key path of external ref inside of schema
      key: key
    };
  });
}

/**
 * Insert External Ref
 * Replace ref with the actual schema
 */
function insertExternalRef(schema, refItem, refSchema) {
  var path = refItem.key.split('.');
  var pointer = schema;
  var key = path[0];
  for (var i = 1; i < path.length - 1; i++) {
    pointer = pointer[key];
    key = path[i];
  }
  var display = getDisplayValues(pointer[key]);
  pointer[key] = _.extend(refSchema, display);
}

/**
 * Resolve Internal Refs
 * Replace refs to definitions with actual schema
 */
function resolveInternalRefs(subSchema) {
  var schema = this;
  if (!subSchema) { subSchema = schema; }
  _.keys(subSchema).filter(function (key) {
    return subSchema[key] && (typeof subSchema[key] === 'object');
  })
  .forEach(function(key) {
    var prop = subSchema[key];
    var displayValues = getDisplayValues(prop);
    prop = resolveInternalReference(prop, schema);
    prop = resolveInternalRefs.bind(schema)(prop);
    subSchema[key] = _.extend(prop, displayValues);
  });
  return subSchema;
}

/**
 * Get Display Values
 * Return a new object with any display-related values from property (title, description)
 */
function getDisplayValues(property) {
  var result = {};
  if (property.title) { result.title = property.title; }
  if (property.description) { result.description = property.description; }
  return result;
}

/**
 * Get Ref Absolute Url
 * Look for id properties in the refs ancestor nodes
 * If the id is an absolute Url, use it to construct the ref's url
 * Otherwise, use the Url that the schema was fetched from
 */
function getRefAbsoluteUrl(schemaUrl, flatSchema, refKey) {
  var refPath = refKey.split('.');
  var relativeUrl = flatSchema[refKey].split('#')[0];
  var rootUrl = schemaUrl;
  while(refPath.length) {
    refPath.pop();
    var idKey = refPath.join('.')+'id';
    if (flatSchema[idKey] && isAbsoluteUrl(flatSchema[idKey])) {
      rootUrl = flatSchema[idKey];
      break;
    }
  }
  if (!rootUrl) {
    throw new Error('Unable to construct URL for external ref '+flatSchema[refKey]);
  }
  rootUrl = rootUrl.slice(0, rootUrl.lastIndexOf('/')+1);
  return rootUrl + relativeUrl;
}

/**
 * Is Absolute Url
 */
function isAbsoluteUrl(url) {
  return /^(?:[a-z]+:)?\/\//.test(url);
}

/**
 * Resolve Internal Reference
 */
function resolveInternalReference(prop, schema) {
  var $ref;
  if ($ref = prop.$ref) {
    if ($ref === '#') {
      // Prevent infinite recursion.
      return {type: schema.type || 'object'};
    } else if ($ref.substring(0, 2) === '#/') {
      var refParts = decodeURIComponent($ref).substring(2).split('/');
      var out = _.reduce(refParts, function(memo, refPart) {
        if (_.isArray(memo)) {
          return memo[parseInt(refPart)];
        } else {
          refPart = refPart.replace('~1', '/').replace('~0', '~');
          return memo[refPart];
        }
      }, schema);
      return resolveInternalReference(out);
    } else {
      throw new Error('Invalid internal reference '+$ref+'.');
    }
  } else {
    if (prop.items && prop.items.$ref) {
      return _.defaults({items: resolveInternalReference(prop.items, schema)}, prop);
    }
    return prop;
  }
}

/**
 * Convert Schema
 */
function convertSchema(jsonSchema) {
  var props = jsonSchema.properties || jsonSchema;
  return translateProperties(props, getRequiredFromProperty(jsonSchema));
}

function translateProperties(properties, required) {
  var schema = {};
  _.each(properties, function(prop, key) {
    var ssProp = {};
    addRules(ssProp, prop, required.indexOf(key) !== -1);
    if (Meteor.isClient) {
      addAutoformAttributes(ssProp, prop);
    }
    schema[key] = ssProp;
    var subProps = getSubPropertiesFromProperty(prop);
    if (subProps) {
      var subSchema = translateProperties(subProps, getRequiredFromProperty(prop));
      _.each(subSchema, function(subProp, subKey) {
        schema[key + '.' + (prop.type === 'array' ? '$.' : '') + subKey] = subProp;
      });
    }
  });
  return schema;
}

/**
 * Get Required From Property
 */
function getRequiredFromProperty(prop) {
  prop = (prop.type === 'array' && prop.items) ? prop.items : prop;
  return (prop.type === 'object' && prop.properties && prop.required) || [];
}

function getTypeFromProperty(prop) {
  var propType = prop.type === 'array' ? prop.items.type : prop.type;
  var format = prop.format;
  var ssType = String;

  switch (propType) {
    case 'integer':
    case 'number':
      ssType = Number;
      break;
    case 'boolean':
      ssType = Boolean;
      break;
    case 'object':
      ssType = Object;
      break;
    default:
      if (format === 'date' || format === 'date-time') {
        ssType = Date;
      } else {
        ssType = String;
      }
      break;
  }

  return (prop.type === 'array' ? [ssType] : ssType);
}

function getSubPropertiesFromProperty(prop) {
  if (prop.type === 'object' && prop.properties) {
    return prop.properties;
  } else if (prop.type === 'array' && prop.items && prop.items.type === 'object' && prop.items.properties) {
    return prop.items.properties;
  }

  return null;
}

var translationMap = {
  title: {key: 'label'},
  minimum: {key: 'min', type: Number},
  maximum: {key: 'max', type: Number},
  exclusiveMinimum: {key: 'exclusiveMin', type: Boolean},
  exclusiveMaximum: {key: 'exclusiveMax', type: Boolean},
  minLength: {key: 'min', type: Number},
  maxLength: {key: 'max', type: Number},
  minItems: {key: 'minCount', type: Number},
  maxItems: {key: 'maxCount', type: Number},
  'default': {key: 'defaultValue'}
};

function addRules(target, source, isRequired) {
  target.type = getTypeFromProperty(source);

  _.each(translationMap, function(spec, jKey) {
    if (typeof source[jKey] !== 'undefined') {
      target[spec.key] = spec.type ? spec.type(source[jKey]) : source[jKey];
    }
  });

  target.optional = !isRequired;

  if (source.pattern) {
    target.regEx = new RegExp(source.pattern);
  }

  if (source.enum && source.enum.every(function (item) { return item !== null; })) {
    target.allowedValues = source.enum;
  }

  if (!source.pattern && source.format === 'email') {
    target.regEx = SimpleSchema.RegEx.Email;
  } else if (!source.pattern && (source.format === 'host-name' || source.format === 'hostname')) {
    target.regEx = SimpleSchema.RegEx.Domain;
  } else if (!source.pattern && source.format === 'ipv4') {
    target.rexEx = SimpleSchema.RegEx.IPv4;
  } else if (!source.pattern && source.format === 'ipv6') {
    target.rexEx = SimpleSchema.RegEx.IPv6;
  } else if (source.type === 'number' || (source.type === 'array' && source.items && source.items.type === 'number')) {
    target.decimal = true;
  }
}

function attachAutoformObject(target) {
  if (!target.autoform) {
    target.autoform = {};
  }

  if (!target.autoform.afFieldInput) {
    target.autoform.afFieldInput = {};
  }
}

function addAutoformAttributes(target, source) {
  if (source.description) {
    attachAutoformObject(target);
    target.autoform.afFieldInput.title = source.description;
  }

  if (source.format === 'date-time') {
    attachAutoformObject(target);
    target.autoform.afFieldInput.type = 'datetime';
  }

  //for enums that contain null, create datalist to suggest options in an input
  if (source.enum && source.enum.some(function (item) { return item === null; })) {
    attachAutoformObject(target);
    //create datalist options
    var datalist = source.enum
      .filter(function (item) { return item !== null; })
      .map(function (item) { return {label: item, value: item}; });
    // note:  attaching datalist as an object threw an error
    // note:  attaching datalist (string or object) to autoform.afFieldInput throws an error
    // attaching it directly to autoform results in it being in afFieldInput on the client
    target.autoform.datalist = JSON.stringify(datalist);
  }
}


text:
/*
 * HTML5 Boilerplate
 *
 * What follows is the result of much research on cross-browser styling.
 * Credit left inline and big thanks to Nicolas Gallagher, Jonathan Neal,
 * Kroc Camen, and the H5BP dev community and team.
 */

/* ==========================================================================
   Base styles: opinionated defaults
   ========================================================================== */

html,
button,
input,
select,
textarea {
    color: #222;
}

body {
    font-size: 1em;
    line-height: 1.4;
}

/*
 * Remove text-shadow in selection highlight: h5bp.com/i
 * These selection rule sets have to be separate.
 * Customize the background color to match your design.
 */

::-moz-selection {
    background: #b3d4fc;
    text-shadow: none;
}

::selection {
    background: #b3d4fc;
    text-shadow: none;
}

/*
 * A better looking default horizontal rule
 */

hr {
    display: block;
    height: 1px;
    border: 0;
    border-top: 1px solid #ccc;
    margin: 1em 0;
    padding: 0;
}

/*
 * Remove the gap between images and the bottom of their containers: h5bp.com/i/440
 */

img {
    vertical-align: middle;
}

/*
 * Remove default fieldset styles.
 */

fieldset {
    border: 0;
    margin: 0;
    padding: 0;
}

/*
 * Allow only vertical resizing of textareas.
 */

textarea {
    resize: vertical;
}

/* ==========================================================================
   Chrome Frame prompt
   ========================================================================== */

.chromeframe {
    margin: 0.2em 0;
    background: #ccc;
    color: #000;
    padding: 0.2em 0;
}

/* ==========================================================================
   Author's custom styles
   ========================================================================== */

#header {
    background: #363e45;
    height: 56px;
    position: fixed;
    width: 100%;
    z-index: 1;
}

.header-inner ul li {
    display: inline;
    color: white;
}

#main-header-image {
    background-color: ##2a5669;

}

#header-image {
    height: 500px;
    width: 100%;
    background: url('img/header-image.jpg') no-repeat fixed;
}

#header-image #inner{
    height: 100%;
    width: 100%;
    background: black;
    opacity: 0.5;
}

/* ==========================================================================
   Helper classes
   ========================================================================== */

/*
 * Image replacement
 */

.ir {
    background-color: transparent;
    border: 0;
    overflow: hidden;
    /* IE 6/7 fallback */
    *text-indent: -9999px;
}

.ir:before {
    content: "";
    display: block;
    width: 0;
    height: 150%;
}

/*
 * Hide from both screenreaders and browsers: h5bp.com/u
 */

.hidden {
    display: none !important;
    visibility: hidden;
}

/*
 * Hide only visually, but have it available for screenreaders: h5bp.com/v
 */

.visuallyhidden {
    border: 0;
    clip: rect(0 0 0 0);
    height: 1px;
    margin: -1px;
    overflow: hidden;
    padding: 0;
    position: absolute;
    width: 1px;
}

/*
 * Extends the .visuallyhidden class to allow the element to be focusable
 * when navigated to via the keyboard: h5bp.com/p
 */

.visuallyhidden.focusable:active,
.visuallyhidden.focusable:focus {
    clip: auto;
    height: auto;
    margin: 0;
    overflow: visible;
    position: static;
    width: auto;
}

/*
 * Hide visually and from screenreaders, but maintain layout
 */

.invisible {
    visibility: hidden;
}

/*
 * Clearfix: contain floats
 *
 * For modern browsers
 * 1. The space content is one way to avoid an Opera bug when the
 *    `contenteditable` attribute is included anywhere else in the document.
 *    Otherwise it causes space to appear at the top and bottom of elements
 *    that receive the `clearfix` class.
 * 2. The use of `table` rather than `block` is only necessary if using
 *    `:before` to contain the top-margins of child elements.
 */

.clearfix:before,
.clearfix:after {
    content: " "; /* 1 */
    display: table; /* 2 */
}

.clearfix:after {
    clear: both;
}

/*
 * For IE 6/7 only
 * Include this rule to trigger hasLayout and contain floats.
 */

.clearfix {
    *zoom: 1;
}

/* ==========================================================================
   EXAMPLE Media Queries for Responsive Design.
   These examples override the primary ('mobile first') styles.
   Modify as content requires.
   ========================================================================== */

@media only screen and (min-width: 35em) {
    /* Style adjustments for viewports that meet the condition */
}

@media print,
       (-o-min-device-pixel-ratio: 5/4),
       (-webkit-min-device-pixel-ratio: 1.25),
       (min-resolution: 120dpi) {
    /* Style adjustments for high resolution devices */
}

/* ==========================================================================
   Print styles.
   Inlined to avoid required HTTP connection: h5bp.com/r
   ========================================================================== */

@media print {
    * {
        background: transparent !important;
        color: #000 !important; /* Black prints faster: h5bp.com/s */
        box-shadow: none !important;
        text-shadow: none !important;
    }

    a,
    a:visited {
        text-decoration: underline;
    }

    a[href]:after {
        content: " (" attr(href) ")";
    }

    abbr[title]:after {
        content: " (" attr(title) ")";
    }

    /*
     * Don't show links for images, or javascript/internal links
     */

    .ir a:after,
    a[href^="javascript:"]:after,
    a[href^="#"]:after {
        content: "";
    }

    pre,
    blockquote {
        border: 1px solid #999;
        page-break-inside: avoid;
    }

    thead {
        display: table-header-group; /* h5bp.com/t */
    }

    tr,
    img {
        page-break-inside: avoid;
    }

    img {
        max-width: 100% !important;
    }

    @page {
        margin: 0.5cm;
    }

    p,
    h2,
    h3 {
        orphans: 3;
        widows: 3;
    }

    h2,
    h3 {
        page-break-after: avoid;
    }
}


text:
class Person
  extend ActiveModel::Naming
  include ActiveModel::Validations

  attr_accessor :attributes
  attr_accessor :name, :email, :password, :address, :gender, :dateofbirth, :publish, :joindate, :created_at, :mobile_number, :country

  validates :name, presence: true
  validates :email, presence: true
  validates :password, presence: true
  validates :gender, presence: true
  validates :joindate, presence: true
  validates :mobile_number, presence: true
  validates :country, presence: true
  validates :address, presence: true
validates :dateofbirth, presence: true

  def initialize(attributes = {})
    @attributes = attributes
  end

  def read_attribute_for_validation(key)
    @attributes[key]
  end
end

class ValidatePerson
  extend ActiveModel::Naming
  include ActiveModel::Validations

  attr_accessor :name
  validates :name, Presence: true
end


text:
import * as zrUtil from 'zrender/src/core/util';
import DataZoomView from './DataZoomView';
import sliderMove from '../helper/sliderMove';
import * as roams from './roams';

var bind = zrUtil.bind;

var InsideZoomView = DataZoomView.extend({

    type: 'dataZoom.inside',

    /**
     * @override
     */
    init: function (ecModel, api) {
        /**
         * 'throttle' is used in this.dispatchAction, so we save range
         * to avoid missing some 'pan' info.
         * @private
         * @type {Array.<number>}
         */
        this._range;
    },

    /**
     * @override
     */
    render: function (dataZoomModel, ecModel, api, payload) {
        InsideZoomView.superApply(this, 'render', arguments);

        // Hence the `throttle` util ensures to preserve command order,
        // here simply updating range all the time will not cause missing
        // any of the the roam change.
        this._range = dataZoomModel.getPercentRange();

        // Reset controllers.
        zrUtil.each(this.getTargetCoordInfo(), function (coordInfoList, coordSysName) {

            var allCoordIds = zrUtil.map(coordInfoList, function (coordInfo) {
                return roams.generateCoordId(coordInfo.model);
            });

            zrUtil.each(coordInfoList, function (coordInfo) {
                var coordModel = coordInfo.model;

                var getRange = {};
                zrUtil.each(['pan', 'zoom', 'scrollMove'], function (eventName) {
                    getRange[eventName] = bind(roamHandlers[eventName], this, coordInfo, coordSysName);
                }, this);

                roams.register(
                    api,
                    {
                        coordId: roams.generateCoordId(coordModel),
                        allCoordIds: allCoordIds,
                        containsPoint: function (e, x, y) {
                            return coordModel.coordinateSystem.containPoint([x, y]);
                        },
                        dataZoomId: dataZoomModel.id,
                        dataZoomModel: dataZoomModel,
                        getRange: getRange
                    }
                );
            }, this);

        }, this);
    },

    /**
     * @override
     */
    dispose: function () {
        roams.unregister(this.api, this.dataZoomModel.id);
        InsideZoomView.superApply(this, 'dispose', arguments);
        this._range = null;
    }

});

var roamHandlers = {

    /**
     * @this {module:echarts/component/dataZoom/InsideZoomView}
     */
    zoom: function (coordInfo, coordSysName, controller, e) {
        var lastRange = this._range;
        var range = lastRange.slice();

        // Calculate transform by the first axis.
        var axisModel = coordInfo.axisModels[0];
        if (!axisModel) {
            return;
        }

        var directionInfo = getDirectionInfo[coordSysName](
            null, [e.originX, e.originY], axisModel, controller, coordInfo
        );
        var percentPoint = (
            directionInfo.signal > 0
                ? (directionInfo.pixelStart + directionInfo.pixelLength - directionInfo.pixel)
                : (directionInfo.pixel - directionInfo.pixelStart)
            ) / directionInfo.pixelLength * (range[1] - range[0]) + range[0];

        var scale = Math.max(1 / e.scale, 0);
        range[0] = (range[0] - percentPoint) * scale + percentPoint;
        range[1] = (range[1] - percentPoint) * scale + percentPoint;

        // Restrict range.
        var minMaxSpan = this.dataZoomModel.findRepresentativeAxisProxy().getMinMaxSpan();

        sliderMove(0, range, [0, 100], 0, minMaxSpan.minSpan, minMaxSpan.maxSpan);

        this._range = range;

        if (lastRange[0] !== range[0] || lastRange[1] !== range[1]) {
            return range;
        }
    },

    /**
     * @this {module:echarts/component/dataZoom/InsideZoomView}
     */
    pan: makeMover(function (range, axisModel, coordInfo, coordSysName, controller, e) {
        var directionInfo = getDirectionInfo[coordSysName](
            [e.oldX, e.oldY], [e.newX, e.newY], axisModel, controller, coordInfo
        );

        return directionInfo.signal
            * (range[1] - range[0])
            * directionInfo.pixel / directionInfo.pixelLength;
    }),

    /**
     * @this {module:echarts/component/dataZoom/InsideZoomView}
     */
    scrollMove: makeMover(function (range, axisModel, coordInfo, coordSysName, controller, e) {
        var directionInfo = getDirectionInfo[coordSysName](
            [0, 0], [e.scrollDelta, e.scrollDelta], axisModel, controller, coordInfo
        );
        return directionInfo.signal * (range[1] - range[0]) * e.scrollDelta;
    })
};

function makeMover(getPercentDelta) {
    return function (coordInfo, coordSysName, controller, e) {
        var lastRange = this._range;
        var range = lastRange.slice();

        // Calculate transform by the first axis.
        var axisModel = coordInfo.axisModels[0];
        if (!axisModel) {
            return;
        }

        var percentDelta = getPercentDelta(
            range, axisModel, coordInfo, coordSysName, controller, e
        );

        sliderMove(percentDelta, range, [0, 100], 'all');

        this._range = range;

        if (lastRange[0] !== range[0] || lastRange[1] !== range[1]) {
            return range;
        }
    };
}

var getDirectionInfo = {

    grid: function (oldPoint, newPoint, axisModel, controller, coordInfo) {
        var axis = axisModel.axis;
        var ret = {};
        var rect = coordInfo.model.coordinateSystem.getRect();
        oldPoint = oldPoint || [0, 0];

        if (axis.dim === 'x') {
            ret.pixel = newPoint[0] - oldPoint[0];
            ret.pixelLength = rect.width;
            ret.pixelStart = rect.x;
            ret.signal = axis.inverse ? 1 : -1;
        }
        else { // axis.dim === 'y'
            ret.pixel = newPoint[1] - oldPoint[1];
            ret.pixelLength = rect.height;
            ret.pixelStart = rect.y;
            ret.signal = axis.inverse ? -1 : 1;
        }

        return ret;
    },

    polar: function (oldPoint, newPoint, axisModel, controller, coordInfo) {
        var axis = axisModel.axis;
        var ret = {};
        var polar = coordInfo.model.coordinateSystem;
        var radiusExtent = polar.getRadiusAxis().getExtent();
        var angleExtent = polar.getAngleAxis().getExtent();

        oldPoint = oldPoint ? polar.pointToCoord(oldPoint) : [0, 0];
        newPoint = polar.pointToCoord(newPoint);

        if (axisModel.mainType === 'radiusAxis') {
            ret.pixel = newPoint[0] - oldPoint[0];
            // ret.pixelLength = Math.abs(radiusExtent[1] - radiusExtent[0]);
            // ret.pixelStart = Math.min(radiusExtent[0], radiusExtent[1]);
            ret.pixelLength = radiusExtent[1] - radiusExtent[0];
            ret.pixelStart = radiusExtent[0];
            ret.signal = axis.inverse ? 1 : -1;
        }
        else { // 'angleAxis'
            ret.pixel = newPoint[1] - oldPoint[1];
            // ret.pixelLength = Math.abs(angleExtent[1] - angleExtent[0]);
            // ret.pixelStart = Math.min(angleExtent[0], angleExtent[1]);
            ret.pixelLength = angleExtent[1] - angleExtent[0];
            ret.pixelStart = angleExtent[0];
            ret.signal = axis.inverse ? -1 : 1;
        }

        return ret;
    },

    singleAxis: function (oldPoint, newPoint, axisModel, controller, coordInfo) {
        var axis = axisModel.axis;
        var rect = coordInfo.model.coordinateSystem.getRect();
        var ret = {};

        oldPoint = oldPoint || [0, 0];

        if (axis.orient === 'horizontal') {
            ret.pixel = newPoint[0] - oldPoint[0];
            ret.pixelLength = rect.width;
            ret.pixelStart = rect.x;
            ret.signal = axis.inverse ? 1 : -1;
        }
        else { // 'vertical'
            ret.pixel = newPoint[1] - oldPoint[1];
            ret.pixelLength = rect.height;
            ret.pixelStart = rect.y;
            ret.signal = axis.inverse ? -1 : 1;
        }

        return ret;
    }
};

export default InsideZoomView;


text:
import Ember from 'ember';
import extendAssert from './extend-assert';
import {
  test as test_,
  only as only_,
  todo as todo_,
  skip
} from 'ember-qunit';

const {
  Logger: { error }
} = Ember;

const wrap = q => function(name, fn) {
  return q(name, async function(assert) {
    assert = extendAssert(assert);
    try {
      return await fn.call(this, assert);
    } catch(e) {
      error(e && e.stack || e);
      throw e;
    }
  });
};

export const test = wrap(test_);
export const only = wrap(only_);
export const todo = wrap(todo_);

test.skip = skip;
test.only = only;
test.todo = todo;


text:
<!DOCTYPE html>

        <title>Dawesome.</title>
        <meta charset="UTF-8">
        <link rel="stylesheet" href="styles.css">

        <link href='http://fonts.googleapis.com/css?family=Roboto Mono' rel='stylesheet' type='text/css'>
        <link href='http://fonts.googleapis.com/css?family=Lato' rel='stylesheet' type='text/css'>
        <link href='entypo.css' rel='stylesheet' type='text/css'>


text:
using System;
using System.ComponentModel;

namespace Azure.Search.Documents.Indexes.Models
{
    /// <summary> Specifies the environment in which the indexer should execute. </summary>
    public readonly partial struct IndexerExecutionEnvironment : IEquatable<IndexerExecutionEnvironment>
    {
        private readonly string _value;

        /// <summary> Determines if two <see cref="IndexerExecutionEnvironment"/> values are the same. </summary>
        /// <exception cref="ArgumentNullException"> <paramref name="value"/> is null. </exception>
        public IndexerExecutionEnvironment(string value)
        {
            _value = value ?? throw new ArgumentNullException(nameof(value));
        }

        private const string StandardValue = "standard";
        private const string PrivateValue = "private";

        /// <summary> Indicates that Azure Cognitive Search can determine where the indexer should execute. This is the default environment when nothing is specified and is the recommended value. </summary>
        public static IndexerExecutionEnvironment Standard { get; } = new IndexerExecutionEnvironment(StandardValue);
        /// <summary> Indicates that the indexer should run with the environment provisioned specifically for the search service. This should only be specified as the execution environment if the indexer needs to access resources securely over shared private link resources. </summary>
        public static IndexerExecutionEnvironment Private { get; } = new IndexerExecutionEnvironment(PrivateValue);
        /// <summary> Determines if two <see cref="IndexerExecutionEnvironment"/> values are the same. </summary>
        public static bool operator ==(IndexerExecutionEnvironment left, IndexerExecutionEnvironment right) => left.Equals(right);
        /// <summary> Determines if two <see cref="IndexerExecutionEnvironment"/> values are not the same. </summary>
        public static bool operator !=(IndexerExecutionEnvironment left, IndexerExecutionEnvironment right) => !left.Equals(right);
        /// <summary> Converts a string to a <see cref="IndexerExecutionEnvironment"/>. </summary>
        public static implicit operator IndexerExecutionEnvironment(string value) => new IndexerExecutionEnvironment(value);

        /// <inheritdoc />
        [EditorBrowsable(EditorBrowsableState.Never)]
        public override bool Equals(object obj) => obj is IndexerExecutionEnvironment other && Equals(other);
        /// <inheritdoc />
        public bool Equals(IndexerExecutionEnvironment other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase);

        /// <inheritdoc />
        [EditorBrowsable(EditorBrowsableState.Never)]
        public override int GetHashCode() => _value?.GetHashCode() ?? 0;
        /// <inheritdoc />
        public override string ToString() => _value;
    }
}


text:
using System.Linq;
using NUnit.Framework;
using Nest.Tests.MockData;
using Nest.Tests.MockData.Domain;

namespace Nest.Tests.Integration.Search.Filter
{
	/// <summary>
	/// Integrated tests of AndFilter, OrFilter and NotFilter with elasticsearch.
	/// </summary>
	[TestFixture]
	public class AndOrNotFilterTests : IntegrationTests
	{
		/// <summary>
		/// Document used in test.
		/// </summary>
		private ElasticsearchProject _LookFor = NestTestData.Data.First();

		/// <summary>
		/// Test the AndFilter.
		/// </summary>
		[Test]
		public void TestAndFilter()
		{
			var country = _LookFor.Country;
			var countryFail = _LookFor.Country + "_fail";

			this.DoFilterTest(
				ft => ft.And(
					f => f.Term(e => e.Country, country),
					f => f.Term(e => e.Country, country),
					f => f.Term(e => e.Country, country)
				      	),
				_LookFor,
				true
				);

			this.DoFilterTest(
				ft => ft.And(
					f => f.Term(e => e.Country, country),
					f => f.Term(e => e.Country, country),
					f => f.Term(e => e.Country, countryFail)
				      	),
				_LookFor,
				false
				);
		}

		/// <summary>
		/// Test the OrFilter.
		/// </summary>
		[Test]
		public void TestOrFilter()
		{
			var country = _LookFor.Country;
			var countryFail = _LookFor.Country + "_fail";

			this.DoFilterTest(
				ft => ft.Or(
					f => f.Term(e => e.Country, country),
					f => f.Term(e => e.Country, countryFail),
					f => f.Term(e => e.Country, countryFail)
						),
				_LookFor,
				true
				);

			this.DoFilterTest(
				ft => ft.Or(
					f => f.Term(e => e.Country, countryFail),
					f => f.Term(e => e.Country, countryFail),
					f => f.Term(e => e.Country, countryFail)
						),
				_LookFor,
				false
				);
		}

		/// <summary>
		/// Set of filters that should not filter de documento _LookFor.
		/// </summary>
		[Test]
		public void TestNotFilter()
		{
			this.DoFilterTest(
				f => f.Not(n => n.Term(o => o.Id, (_LookFor.Id + 1))),
				_LookFor,
				true);

			this.DoFilterTest(
				f => f.Not(n => n.Term(o => o.Id, _LookFor.Id)),
				_LookFor,
				false);
		}
	}
}


text:
package nz.co.lolnet.lolnetachievements.Listeners.Threads;

import static nz.co.lolnet.lolnetachievements.Achievements.Achievements.addCloudAchievementsToPlayer;
import static nz.co.lolnet.lolnetachievements.Achievements.Achievements.addPlayerAchievementsToCloud;
import nz.co.lolnet.lolnetachievements.LolnetAchievements;
import org.bukkit.event.player.PlayerJoinEvent;

/**
 *
 * @author CptWin
 */
public class OnPlayerJoinThread implements Runnable {

    private final PlayerJoinEvent event;

    public OnPlayerJoinThread(PlayerJoinEvent event)
    {
        this.event = event;
        start();
    }

    private void start()
    {
        LolnetAchievements.getThreadPool().execute(this);
    }

    @Override
    public void run() {
        addCloudAchievementsToPlayer(event.getPlayer());
        addPlayerAchievementsToCloud(event.getPlayer());
    }

}


text:
namespace prerender {

bool MaybeGetQueryStringBasedAliasURL(
    const GURL& url, GURL* alias_url) {
  DCHECK(alias_url);
  url_parse::Parsed parsed;
  url_parse::ParseStandardURL(url.spec().c_str(), url.spec().length(),
                              &parsed);
  url_parse::Component query = parsed.query;
  url_parse::Component key, value;
  while (url_parse::ExtractQueryKeyValue(url.spec().c_str(), &query, &key,
                                         &value)) {
    if (key.len != 3 || strncmp(url.spec().c_str() + key.begin, "url", key.len))
      continue;
    // We found a url= query string component.
    if (value.len < 1)
      continue;
    url_canon::RawCanonOutputW<1024> decoded_url;
    url_util::DecodeURLEscapeSequences(url.spec().c_str() + value.begin,
                                       value.len, &decoded_url);
    GURL new_url(string16(decoded_url.data(), decoded_url.length()));
    if (!new_url.is_empty() && new_url.is_valid()) {
      *alias_url = new_url;
      return true;
    }
    return false;
  }
  return false;
}

uint8 GetQueryStringBasedExperiment(const GURL& url) {
  url_parse::Parsed parsed;
  url_parse::ParseStandardURL(url.spec().c_str(), url.spec().length(),
                              &parsed);
  url_parse::Component query = parsed.query;
  url_parse::Component key, value;
  while (url_parse::ExtractQueryKeyValue(url.spec().c_str(), &query, &key,
                                         &value)) {
    if (key.len != 3 || strncmp(url.spec().c_str() + key.begin, "lpe", key.len))
      continue;

    // We found a lpe= query string component.
    if (value.len != 1)
      continue;
    uint8 exp = *(url.spec().c_str() + value.begin) - '0';
    if (exp < 1 || exp > 9)
      continue;
    return exp;
  }
  return kNoExperiment;
}

bool IsGoogleDomain(const GURL& url) {
  return StartsWithASCII(url.host(), std::string("www.google."), true);
}

bool IsGoogleSearchResultURL(const GURL& url) {
  if (!IsGoogleDomain(url))
    return false;
  return (url.path().empty() ||
          StartsWithASCII(url.path(), std::string("/search"), true) ||
          (url.path() == "/") ||
          StartsWithASCII(url.path(), std::string("/webhp"), true));
}

bool IsWebURL(const GURL& url) {
  return url.SchemeIs("http") || url.SchemeIs("https");
}

bool IsNoSwapInExperiment(uint8 experiment_id) {
  // Currently, experiments 5 and 6 fall in this category.
  return experiment_id == 5 || experiment_id == 6;
}

bool IsControlGroupExperiment(uint8 experiment_id) {
  // Currently, experiments 7 and 8 fall in this category.
  return experiment_id == 7 || experiment_id == 8;
}

void URLRequestResponseStarted(net::URLRequest* request) {
  static const char* kModPagespeedHeader = "X-Mod-Pagespeed";
  static const char* kModPagespeedHistogram = "Prerender.ModPagespeedHeader";
  const content::ResourceRequestInfo* info =
      content::ResourceRequestInfo::ForRequest(request);
  // Gather histogram information about the X-Mod-Pagespeed header.
  if (info->GetResourceType() == ResourceType::MAIN_FRAME &&
      IsWebURL(request->url())) {
    UMA_HISTOGRAM_SPARSE_SLOWLY(kModPagespeedHistogram, 0);
    if (request->response_headers() &&
        request->response_headers()->HasHeader(kModPagespeedHeader)) {
      UMA_HISTOGRAM_SPARSE_SLOWLY(kModPagespeedHistogram, 1);

      // Attempt to parse the version number, and encode it in buckets
      // 2 through 99. 0 and 1 are used to store all pageviews and
      // # pageviews with the MPS header (see above).
      void* iter = NULL;
      std::string mps_version;
      if (request->response_headers()->EnumerateHeader(
              &iter, kModPagespeedHeader, &mps_version) &&
          !mps_version.empty()) {
        // Mod Pagespeed versions are of the form a.b.c.d-e
        int a, b, c, d, e;
        int num_parsed = sscanf(mps_version.c_str(), "%d.%d.%d.%d-%d",
                                &a, &b, &c, &d, &e);
        if (num_parsed == 5) {
          int output = 2;
          if (c > 10)
            output += 2 * (c - 10);
          if (d > 1)
            output++;
          if (output < 2 || output >= 99)
            output = 99;
          UMA_HISTOGRAM_SPARSE_SLOWLY(kModPagespeedHistogram, output);
        }
      }
    }
  }
}

}  // namespace prerender


text:
/* scala-stm - (c) 2009-2010, Stanford University, PPL */

package scala.concurrent.stm

import java.util.concurrent.CyclicBarrier

import org.scalatest.{FunSuite, Tag}

class HistogramSuite extends FunSuite {

  for ((opsPerTest, name, slow) <- List((10000, "10K", false),
                                        (1000000, "1M", true))) {
    for (buckets <- List(1, 30, 10000)) {
      for (threads <- List(1, 2, 4, 8, 16, 32, 64, 128, 256, 512) if threads <= 2 * Runtime.getRuntime.availableProcessors) {
        for (useTArray <- List(false, true)) {
          val str = "" + buckets + " buckets, " + threads + " threads, " +
            (if (useTArray) "TArray[Int]" else "Array[Ref[Int]]")
          addTest("single-op-txn, " + str + ", " + name, Slow) {
            histogram(buckets, threads, opsPerTest / threads, useTArray, 100, 1)
          }

          for ((accesses, slow2) <- List((1, true), (3, false), (100, true))) {
            addTest("txn, " + str + ", " + accesses + " incr per txn, " + name, Slow) {
              histogram(buckets, threads, opsPerTest / threads, useTArray, 0, accesses)
            }
            val g = if (slow || slow2) List[Tag](Slow) else List.empty[Tag]
            addTest("mix, " + str + ", " + accesses + " incr per txn " + name, g:_*) {
              histogram(buckets, threads, opsPerTest / threads, useTArray, 50, accesses)
            }
          }
        }
      }
    }
  }

  private def addTest(name: String, tags: Tag*)(block: => Unit): Unit =
    test(name, tags:_*)(block)

  def histogram(bucketCount: Int,
                workerCount: Int,
                samplesPerWorker: Int,
                useTArray: Boolean,
                singlePct: Int,
                samplesPerTxn: Int): Unit = {

    val buckets: IndexedSeq[Ref[Int]] = if (useTArray) {
      TArray.ofDim[Int](bucketCount).refs
    } else {
      Array.tabulate(bucketCount)({ _ => Ref(0) })
    }
    val threads = new Array[Thread](workerCount)
    val barrier = new CyclicBarrier(workerCount, new Runnable {
      var start = 0L
      def run(): Unit = {
        val now = System.nanoTime
        if (start == 0) {
          start = now
        } else {
          val elapsed = now - start
          println("hist(" + bucketCount + "," + workerCount + "," + samplesPerWorker + "," +
            useTArray + "," + singlePct +
            "," + samplesPerTxn + ")  total_elapsed=" + elapsed + " nanos,  throughput=" +
            (samplesPerWorker * workerCount * 1000000000L) / elapsed + " ops/sec,  per_thread_latency=" +
            elapsed / samplesPerWorker + " nanos/op,  avg_arrival=" +
            elapsed / (samplesPerWorker * workerCount) + " nanos/op")
        }
      }
    })

    for (worker <- 0 until workerCount) {
      val work = new Runnable {
        def run(): Unit = {
          barrier.await
          var i = 0
          while (i < samplesPerWorker) {
            if (math.abs(hash(i, worker) % 100) < singlePct) {
              if ((i % 2) == 0) {
                buckets(math.abs(hash(worker, i) % bucketCount)).single.transform(_ + 1)
              } else {
                val nt = buckets(math.abs(hash(worker, i) % bucketCount)).single
                var x = nt()
                while (!nt.compareAndSet(x, x + 1)) x = nt()
              }
              i += 1
            } else {
              atomic { implicit t =>
                var j = 0
                while (j < samplesPerTxn && i + j < samplesPerWorker) {
                  val tv = buckets(math.abs(hash(worker, i + j) % bucketCount))
                  //tv.getAndTransform(_ + 1)
                  tv() = tv() + 1
                  //tv() = tv.bind.readForWrite + 1
                  j += 1
                }
              }
              i += samplesPerTxn
            }
          }
          barrier.await
        }
      }
      if (worker < workerCount - 1) {
        threads(worker) = new Thread(work, "worker " + worker)
        threads(worker).start()
      } else {
        work.run()
      }
    }

    for (worker <- 0 until workerCount - 1) threads(worker).join()

    val sum = buckets.map(_.single.get).sum
    assert(samplesPerWorker * workerCount === sum)
  }

  private def hash(i: Int, j: Int) = {
    var h = i * 37 + j * 101
    h ^= (h >>> 20) ^ (h >>> 12)
    h ^ (h >>> 7) ^ (h >>> 4)
  }
}


text:
class PageClickListener;

// This class is responsible for tracking clicks on elements in web pages and
// notifiying the associated listener when a node is clicked.
// Compared to a simple WebDOMEventListener, it offers the added capability of
// notifying the listeners of whether the clicked node was already focused
// before it was clicked.
//
// This is useful for password/form autofill where we want to trigger a
// suggestion popup when a text input is clicked.
// It only notifies of WebInputElement that are text inputs being clicked, but
// could easily be changed to report click on any type of WebNode.
//
// There is one PageClickTracker per RenderView.
class PageClickTracker : public RenderViewObserver,
                         public WebKit::WebDOMEventListener {
 public:
  explicit PageClickTracker(RenderView* render_view);
  virtual ~PageClickTracker();

  // Adds/removes a listener for getting notification when an element is
  // clicked.  Note that the order of insertion is important as a listener when
  // notified can decide to stop the propagation of the event (so that listeners
  // inserted after don't get the notification).
  void AddListener(PageClickListener* listener);
  void RemoveListener(PageClickListener* listener);

 private:
  // RenderView::Observer implementation.
  virtual bool OnMessageReceived(const IPC::Message& message);
  virtual void DidFinishDocumentLoad(WebKit::WebFrame* frame);
  virtual void FrameDetached(WebKit::WebFrame* frame);

  // WebKit::WebDOMEventListener implementation.
  virtual void handleEvent(const WebKit::WebDOMEvent& event);

  // Called after the mouse event |event| has been processed by WebKit.
  virtual void DidHandleMouseEvent(const WebKit::WebMouseEvent& event);

  // Returns the currently focused node in the associated render view.
  // That node may be null.
  WebKit::WebNode GetFocusedNode();

  // The last node that was clicked and had focus.
  WebKit::WebNode last_node_clicked_;

  // Whether the last clicked node had focused before it was clicked.
  bool was_focused_;

  // The frames we are listening to for mouse events.
  typedef std::vector<WebKit::WebFrame*> FrameList;
  FrameList tracked_frames_;

  // The listener getting the actual notifications.
  ObserverList<PageClickListener> listeners_;

  DISALLOW_COPY_AND_ASSIGN(PageClickTracker);
};

#endif  // CHROME_RENDERER_PAGE_CLICK_TRACKER_H_


text:
require_relative 'reader'

# Class that keeps track of the sources that contain CSAir's information.
#
# @author Cassio dos Santos Sousa
# @version 1.1
# @since 1.0
#
class Resources

  attr_reader :sources

  # @param [String] json_file_name
  #
  # @return [void]
  #
  def initialize(json_file_name)
    @sources = get_sources_from_json(json_file_name)
  end

  # @param [String] json_file_name
  #
  # @return [void]
  #
  def get_sources_from_json(json_file_name)
    read_me = Reader.new(json_file_name)
    read_me.get_data_sources
  end

end


text:
<?php

/* SonataAdminBundle:CRUD:acl.html.twig */
class __TwigTemplate_d6ad8411bebd9ae1fa3930c734379d1ffbde118d0922c7769e3ea9278a8f85dd extends Twig_Template
{
    public function __construct(Twig_Environment $env)
    {
        parent::__construct($env);

        // line 12
        $this->parent = $this->loadTemplate("SonataAdminBundle:CRUD:base_acl.html.twig", "SonataAdminBundle:CRUD:acl.html.twig", 12);
        $this->blocks = array(
        );
    }

    protected function doGetParent(array $context)
    {
        return "SonataAdminBundle:CRUD:base_acl.html.twig";
    }

    protected function doDisplay(array $context, array $blocks = array())
    {
        $this->parent->display($context, array_merge($this->blocks, $blocks));
    }

    public function getTemplateName()
    {
        return "SonataAdminBundle:CRUD:acl.html.twig";
    }

    public function isTraitable()
    {
        return false;
    }

    public function getDebugInfo()
    {
        return array (  11 => 12,);
    }
}


text:
package com.yummy.service;

import com.yummy.model.Student;

import java.util.List;

/**
 * Created by yummy on 2017/9/22.
 */
public interface StudentService {
    public Student findById(String Id);
    public List<Student> getStudentInfo(String id);

}