text:
var Aria = require("ariatemplates/Aria");

module.exports = Aria.classDefinition({
    $classpath : "test.aria.widgets.wai.autoComplete.AutoCompleteGlobalNonWaiRobotTestCase",
    $extends : require("./AutoCompleteRobotBase"),
    $prototype: {
        myAutoCompleteId: "city1",
        myAutoCompleteAccessible: false
    }
});

redpajama_set_name: RedPajamaGithub


text:
class API::V3::Catalog::SimpleSearchesController < API::V3::Catalog::BaseController
  def create
    paginate
    authorize(@catalog, :simple_search_create?) unless authenticated_catalog?

    build_simple_search
    if @simple_search.update(simple_search_params)
      @simple_search_results = ItemList::SimpleSearchResult.new(
        :catalog => @catalog,
        :query => @simple_search.query,
        :page => params[:page],
        :item_type_slug => params[:item_type_slug],
        :search_uuid => @simple_search.uuid
      )
      render("api/v3/catalog/simple_searches/show")
    else
      render_unprocessable_record(@simple_search)
    end
  end

  def show
    paginate
    authorize(@catalog, :simple_search_show?) unless authenticated_catalog?

    find_simple_search
    return routing_error if @simple_search.nil?

    @simple_search_results = ItemList::SimpleSearchResult.new(
      :catalog => @catalog,
      :query => @simple_search.query,
      :page => params[:page],
      :item_type_slug => params[:item_type_slug],
      :search_uuid => @simple_search.uuid
    )
  end

  private

  def paginate
    @page = params[:page]
    @per = params[:per]
  end

  def build_simple_search
    @simple_search = scope.new do |simple_search|
      simple_search.creator = @current_user if !authenticated_catalog? && @current_user.authenticated?
    end
  end

  def find_simple_search
    @simple_search = SimpleSearch.find_by(:uuid => params[:uuid])
  end

  def simple_search_params
    params.permit(:q)
  end

  def scope
    @catalog.simple_searches
  end
end


text:
<!DOCTYPE html>

  <title>
    Template
  </title>

	<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">

	<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css" integrity="sha384-fLW2N01lMqjakBkx3l/M9EahuwpSfeNvV63J5ezn3uZzapT0u7EYsXMjQV+0En5r" crossorigin="anonymous">

	<link rel="stylesheet" type="text/css" href="index.css">

Yoda

Hodor hodor HODOR! Hodor hodor... Hodor hodor hodor hodor? Hodor hodor - hodor; hodor hodor... Hodor hodor hodor hodor. Hodor. Hodor, hodor. Hodor. Hodor, hodor - HODOR hodor, hodor hodor. Hodor. Hodor hodor, hodor. Hodor HODOR hodor, hodor hodor, hodor. Hodor hodor?! Hodor hodor HODOR! Hodor hodor - hodor hodor? Hodor. Hodor hodor... Hodor hodor hodor? Hodor hodor HODOR! Hodor hodor hodor hodor... Hodor hodor hodor?! Hodor hodor HODOR! Hodor hodor; hodor hodor?!

Hodor hodor HODOR! Hodor HODOR hodor, hodor hodor hodor hodor. Hodor. Hodor hodor... Hodor hodor hodor hodor hodor hodor hodor hodor hodor! Hodor hodor hodor hodor hodor hodor hodor hodor. Hodor. Hodor hodor hodor hodor... Hodor hodor hodor, hodor, hodor hodor. Hodor! Hodor hodor, HODOR hodor, hodor hodor - hodor... Hodor hodor hodor, hodor, hodor hodor. Hodor hodor, hodor. Hodor hodor, hodor, hodor hodor.

Hodor hodor hodor? Hodor, hodor... Hodor hodor hodor... Hodor hodor hodor? Hodor, hodor. Hodor. Hodor, HODOR hodor, hodor HODOR hodor, hodor HODOR hodor, hodor hodor. Hodor, hodor hodor hodor hodor. Hodor hodor - hodor; hodor hodor... Hodor hodor hodor hodor. Hodor. Hodor, hodor. Hodor. Hodor, hodor; hodor hodor?

  			 -Wikipedia
  				-Star Wars website
  				-Yoda's Theme Song
  				-Yoda speak translator
  				-Yoda Quotes


text:
BY MATT MCGREGOR AND ELIZABETH HERITAGE

For the month of March (and a little bit of April), Creative Commons Aotearoa New Zealand has been travelling around Aotearoa spreading the word about Open Educational Resources for New Zealand schools. In case you didn't make it to any of these events, we've embedded the slides below.

Matt McGregor and Elizabeth Heritage, Creative Commons Aotearoa New Zealand

Andrew Matangi, Creative Commons Aotearoa New Zealand Legal Team

Tim Kong, Network for Learning

Richard White, University of Otago

Clare Forrest, Raroa School


text:
struct choice  {
 char hostarg[65];
 char logarg[17];
 short option_algorithm;
 int portarg;
 int redirectarg;
 int wafmode;
};

struct choice param;

void isnull_argv();

#endif


text:
package com.vendelligence.webapp.crm.feedback.model;

/*
 * Simple Model class to map to the HTML form fields in the Feedback form view.
 * This is the most simple CRM Feedback form with name, email (both fields optional) and
 * a placeholder for the feedback message.
 *
 */

public class Feedback
{
	private String name;
	private String email;
    private String message;

    public Feedback()
    {
    	this.name = "";
    	this.email = "";
    	this.message = "";
    }

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

    public String getEmail()
    {
    	return this.email;
    }

    public String getMessage()
    {
        return this.message;
    }

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

    public void setEmail(String mail)
    {
    	this.email = mail;
    }

    public void setMessage(String msg)
    {
        this.message = msg;
    }

}


text:
package com.google.common.collect;

import static com.google.common.truth.Truth.assertThat;

import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableBiMap.Builder;
import com.google.common.collect.testing.MapInterfaceTest;
import com.google.common.collect.testing.features.CollectionFeature;
import com.google.common.collect.testing.features.CollectionSize;
import com.google.common.collect.testing.features.MapFeature;
import com.google.common.collect.testing.google.BiMapGenerators.ImmutableBiMapCopyOfEntriesGenerator;
import com.google.common.collect.testing.google.BiMapGenerators.ImmutableBiMapCopyOfGenerator;
import com.google.common.collect.testing.google.BiMapGenerators.ImmutableBiMapGenerator;
import com.google.common.collect.testing.google.BiMapInverseTester;
import com.google.common.collect.testing.google.BiMapTestSuiteBuilder;
import com.google.common.testing.SerializableTester;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;

/**
 * Tests for {@link ImmutableBiMap}.
 *
 * @author Jared Levy
 */
@GwtCompatible(emulated = true)
public class ImmutableBiMapTest extends TestCase {

  // TODO: Reduce duplication of ImmutableMapTest code

  @GwtIncompatible // suite
  public static Test suite() {
    TestSuite suite = new TestSuite();

    suite.addTestSuite(MapTests.class);
    suite.addTestSuite(InverseMapTests.class);
    suite.addTestSuite(CreationTests.class);
    suite.addTestSuite(BiMapSpecificTests.class);

    suite.addTest(
        BiMapTestSuiteBuilder.using(new ImmutableBiMapGenerator())
            .named("ImmutableBiMap")
            .withFeatures(
                CollectionSize.ANY,
                CollectionFeature.SERIALIZABLE,
                CollectionFeature.KNOWN_ORDER,
                MapFeature.REJECTS_DUPLICATES_AT_CREATION,
                MapFeature.ALLOWS_ANY_NULL_QUERIES)
            .suppressing(BiMapInverseTester.getInverseSameAfterSerializingMethods())
            .createTestSuite());
    suite.addTest(
        BiMapTestSuiteBuilder.using(new ImmutableBiMapCopyOfGenerator())
            .named("ImmutableBiMap.copyOf[Map]")
            .withFeatures(
                CollectionSize.ANY,
                CollectionFeature.SERIALIZABLE,
                CollectionFeature.KNOWN_ORDER,
                MapFeature.ALLOWS_ANY_NULL_QUERIES)
            .suppressing(BiMapInverseTester.getInverseSameAfterSerializingMethods())
            .createTestSuite());
    suite.addTest(
        BiMapTestSuiteBuilder.using(new ImmutableBiMapCopyOfEntriesGenerator())
            .named("ImmutableBiMap.copyOf[Iterable<Entry>]")
            .withFeatures(
                CollectionSize.ANY,
                CollectionFeature.SERIALIZABLE,
                CollectionFeature.KNOWN_ORDER,
                MapFeature.REJECTS_DUPLICATES_AT_CREATION,
                MapFeature.ALLOWS_ANY_NULL_QUERIES)
            .suppressing(BiMapInverseTester.getInverseSameAfterSerializingMethods())
            .createTestSuite());

    return suite;
  }

  public abstract static class AbstractMapTests<K, V> extends MapInterfaceTest<K, V> {
    public AbstractMapTests() {
      super(false, false, false, false, false);
    }

    @Override
    protected Map<K, V> makeEmptyMap() {
      throw new UnsupportedOperationException();
    }

    private static final Joiner joiner = Joiner.on(", ");

    @Override
    protected void assertMoreInvariants(Map<K, V> map) {

      BiMap<K, V> bimap = (BiMap<K, V>) map;

      for (Entry<K, V> entry : map.entrySet()) {
        assertEquals(entry.getKey() + "=" + entry.getValue(), entry.toString());
        assertEquals(entry.getKey(), bimap.inverse().get(entry.getValue()));
      }

      assertEquals("{" + joiner.join(map.entrySet()) + "}", map.toString());
      assertEquals("[" + joiner.join(map.entrySet()) + "]", map.entrySet().toString());
      assertEquals("[" + joiner.join(map.keySet()) + "]", map.keySet().toString());
      assertEquals("[" + joiner.join(map.values()) + "]", map.values().toString());

      assertEquals(Sets.newHashSet(map.entrySet()), map.entrySet());
      assertEquals(Sets.newHashSet(map.keySet()), map.keySet());
    }
  }

  public static class MapTests extends AbstractMapTests<String, Integer> {
    @Override
    protected Map<String, Integer> makeEmptyMap() {
      return ImmutableBiMap.of();
    }

    @Override
    protected Map<String, Integer> makePopulatedMap() {
      return ImmutableBiMap.of("one", 1, "two", 2, "three", 3);
    }

    @Override
    protected String getKeyNotInPopulatedMap() {
      return "minus one";
    }

    @Override
    protected Integer getValueNotInPopulatedMap() {
      return -1;
    }
  }

  public static class InverseMapTests extends AbstractMapTests<String, Integer> {
    @Override
    protected Map<String, Integer> makeEmptyMap() {
      return ImmutableBiMap.of();
    }

    @Override
    protected Map<String, Integer> makePopulatedMap() {
      return ImmutableBiMap.of(1, "one", 2, "two", 3, "three").inverse();
    }

    @Override
    protected String getKeyNotInPopulatedMap() {
      return "minus one";
    }

    @Override
    protected Integer getValueNotInPopulatedMap() {
      return -1;
    }
  }

  public static class CreationTests extends TestCase {
    public void testEmptyBuilder() {
      ImmutableBiMap<String, Integer> map = new Builder<String, Integer>().build();
      assertEquals(Collections.<String, Integer>emptyMap(), map);
      assertEquals(Collections.<Integer, String>emptyMap(), map.inverse());
      assertSame(ImmutableBiMap.of(), map);
    }

    public void testSingletonBuilder() {
      ImmutableBiMap<String, Integer> map = new Builder<String, Integer>().put("one", 1).build();
      assertMapEquals(map, "one", 1);
      assertMapEquals(map.inverse(), 1, "one");
    }

    public void testBuilder_withImmutableEntry() {
      ImmutableBiMap<String, Integer> map =
          new Builder<String, Integer>().put(Maps.immutableEntry("one", 1)).build();
      assertMapEquals(map, "one", 1);
    }

    public void testBuilder() {
      ImmutableBiMap<String, Integer> map =
          ImmutableBiMap.<String, Integer>builder()
              .put("one", 1)
              .put("two", 2)
              .put("three", 3)
              .put("four", 4)
              .put("five", 5)
              .build();
      assertMapEquals(map, "one", 1, "two", 2, "three", 3, "four", 4, "five", 5);
      assertMapEquals(map.inverse(), 1, "one", 2, "two", 3, "three", 4, "four", 5, "five");
    }

    @GwtIncompatible
    public void testBuilderExactlySizedReusesArray() {
      ImmutableBiMap.Builder<Integer, Integer> builder = ImmutableBiMap.builderWithExpectedSize(10);
      Object[] builderArray = builder.alternatingKeysAndValues;
      for (int i = 0; i < 10; i++) {
        builder.put(i, i);
      }
      Object[] builderArrayAfterPuts = builder.alternatingKeysAndValues;
      RegularImmutableBiMap<Integer, Integer> map =
          (RegularImmutableBiMap<Integer, Integer>) builder.build();
      Object[] mapInternalArray = map.alternatingKeysAndValues;
      assertSame(builderArray, builderArrayAfterPuts);
      assertSame(builderArray, mapInternalArray);
    }

    public void testBuilder_orderEntriesByValue() {
      ImmutableBiMap<String, Integer> map =
          ImmutableBiMap.<String, Integer>builder()
              .orderEntriesByValue(Ordering.natural())
              .put("three", 3)
              .put("one", 1)
              .put("five", 5)
              .put("four", 4)
              .put("two", 2)
              .build();
      assertMapEquals(map, "one", 1, "two", 2, "three", 3, "four", 4, "five", 5);
      assertMapEquals(map.inverse(), 1, "one", 2, "two", 3, "three", 4, "four", 5, "five");
    }

    public void testBuilder_orderEntriesByValueAfterExactSizeBuild() {
      ImmutableBiMap.Builder<String, Integer> builder =
          new ImmutableBiMap.Builder<String, Integer>(2).put("four", 4).put("one", 1);
      ImmutableMap<String, Integer> keyOrdered = builder.build();
      ImmutableMap<String, Integer> valueOrdered =
          builder.orderEntriesByValue(Ordering.natural()).build();
      assertMapEquals(keyOrdered, "four", 4, "one", 1);
      assertMapEquals(valueOrdered, "one", 1, "four", 4);
    }

    public void testBuilder_orderEntriesByValue_usedTwiceFails() {
      ImmutableBiMap.Builder<String, Integer> builder =
          new Builder<String, Integer>().orderEntriesByValue(Ordering.natural());
      try {
        builder.orderEntriesByValue(Ordering.natural());
        fail("Expected IllegalStateException");
      } catch (IllegalStateException expected) {
      }
    }

    public void testBuilderPutAllWithEmptyMap() {
      ImmutableBiMap<String, Integer> map =
          new Builder<String, Integer>().putAll(Collections.<String, Integer>emptyMap()).build();
      assertEquals(Collections.<String, Integer>emptyMap(), map);
    }

    public void testBuilderPutAll() {
      Map<String, Integer> toPut = new LinkedHashMap<>();
      toPut.put("one", 1);
      toPut.put("two", 2);
      toPut.put("three", 3);
      Map<String, Integer> moreToPut = new LinkedHashMap<>();
      moreToPut.put("four", 4);
      moreToPut.put("five", 5);

      ImmutableBiMap<String, Integer> map =
          new Builder<String, Integer>().putAll(toPut).putAll(moreToPut).build();
      assertMapEquals(map, "one", 1, "two", 2, "three", 3, "four", 4, "five", 5);
      assertMapEquals(map.inverse(), 1, "one", 2, "two", 3, "three", 4, "four", 5, "five");
    }

    public void testBuilderReuse() {
      Builder<String, Integer> builder = new Builder<>();
      ImmutableBiMap<String, Integer> mapOne = builder.put("one", 1).put("two", 2).build();
      ImmutableBiMap<String, Integer> mapTwo = builder.put("three", 3).put("four", 4).build();

      assertMapEquals(mapOne, "one", 1, "two", 2);
      assertMapEquals(mapOne.inverse(), 1, "one", 2, "two");
      assertMapEquals(mapTwo, "one", 1, "two", 2, "three", 3, "four", 4);
      assertMapEquals(mapTwo.inverse(), 1, "one", 2, "two", 3, "three", 4, "four");
    }

    public void testBuilderPutNullKey() {
      Builder<String, Integer> builder = new Builder<>();
      try {
        builder.put(null, 1);
        fail();
      } catch (NullPointerException expected) {
      }
    }

    public void testBuilderPutNullValue() {
      Builder<String, Integer> builder = new Builder<>();
      try {
        builder.put("one", null);
        fail();
      } catch (NullPointerException expected) {
      }
    }

    public void testBuilderPutNullKeyViaPutAll() {
      Builder<String, Integer> builder = new Builder<>();
      try {
        builder.putAll(Collections.<String, Integer>singletonMap(null, 1));
        fail();
      } catch (NullPointerException expected) {
      }
    }

    public void testBuilderPutNullValueViaPutAll() {
      Builder<String, Integer> builder = new Builder<>();
      try {
        builder.putAll(Collections.<String, Integer>singletonMap("one", null));
        fail();
      } catch (NullPointerException expected) {
      }
    }

    public void testPuttingTheSameKeyTwiceThrowsOnBuild() {
      Builder<String, Integer> builder =
          new Builder<String, Integer>()
              .put("one", 1)
              .put("one", 1); // throwing on this line would be even better

      try {
        builder.build();
        fail();
      } catch (IllegalArgumentException expected) {
        assertThat(expected.getMessage()).contains("one");
      }
    }

    public void testOf() {
      assertMapEquals(ImmutableBiMap.of("one", 1), "one", 1);
      assertMapEquals(ImmutableBiMap.of("one", 1).inverse(), 1, "one");
      assertMapEquals(ImmutableBiMap.of("one", 1, "two", 2), "one", 1, "two", 2);
      assertMapEquals(ImmutableBiMap.of("one", 1, "two", 2).inverse(), 1, "one", 2, "two");
      assertMapEquals(
          ImmutableBiMap.of("one", 1, "two", 2, "three", 3), "one", 1, "two", 2, "three", 3);
      assertMapEquals(
          ImmutableBiMap.of("one", 1, "two", 2, "three", 3).inverse(),
          1,
          "one",
          2,
          "two",
          3,
          "three");
      assertMapEquals(
          ImmutableBiMap.of("one", 1, "two", 2, "three", 3, "four", 4),
          "one",
          1,
          "two",
          2,
          "three",
          3,
          "four",
          4);
      assertMapEquals(
          ImmutableBiMap.of("one", 1, "two", 2, "three", 3, "four", 4).inverse(),
          1,
          "one",
          2,
          "two",
          3,
          "three",
          4,
          "four");
      assertMapEquals(
          ImmutableBiMap.of("one", 1, "two", 2, "three", 3, "four", 4, "five", 5),
          "one",
          1,
          "two",
          2,
          "three",
          3,
          "four",
          4,
          "five",
          5);
      assertMapEquals(
          ImmutableBiMap.of("one", 1, "two", 2, "three", 3, "four", 4, "five", 5).inverse(),
          1,
          "one",
          2,
          "two",
          3,
          "three",
          4,
          "four",
          5,
          "five");
    }

    public void testOfNullKey() {
      try {
        ImmutableBiMap.of(null, 1);
        fail();
      } catch (NullPointerException expected) {
      }

      try {
        ImmutableBiMap.of("one", 1, null, 2);
        fail();
      } catch (NullPointerException expected) {
      }
    }

    public void testOfNullValue() {
      try {
        ImmutableBiMap.of("one", null);
        fail();
      } catch (NullPointerException expected) {
      }

      try {
        ImmutableBiMap.of("one", 1, "two", null);
        fail();
      } catch (NullPointerException expected) {
      }
    }

    public void testOfWithDuplicateKey() {
      try {
        ImmutableBiMap.of("one", 1, "one", 1);
        fail();
      } catch (IllegalArgumentException expected) {
        assertThat(expected.getMessage()).contains("one");
      }
    }

    public void testCopyOfEmptyMap() {
      ImmutableBiMap<String, Integer> copy =
          ImmutableBiMap.copyOf(Collections.<String, Integer>emptyMap());
      assertEquals(Collections.<String, Integer>emptyMap(), copy);
      assertSame(copy, ImmutableBiMap.copyOf(copy));
      assertSame(ImmutableBiMap.of(), copy);
    }

    public void testCopyOfSingletonMap() {
      ImmutableBiMap<String, Integer> copy =
          ImmutableBiMap.copyOf(Collections.singletonMap("one", 1));
      assertMapEquals(copy, "one", 1);
      assertSame(copy, ImmutableBiMap.copyOf(copy));
    }

    public void testCopyOf() {
      Map<String, Integer> original = new LinkedHashMap<>();
      original.put("one", 1);
      original.put("two", 2);
      original.put("three", 3);

      ImmutableBiMap<String, Integer> copy = ImmutableBiMap.copyOf(original);
      assertMapEquals(copy, "one", 1, "two", 2, "three", 3);
      assertSame(copy, ImmutableBiMap.copyOf(copy));
    }

    public void testEmpty() {
      ImmutableBiMap<String, Integer> bimap = ImmutableBiMap.of();
      assertEquals(Collections.<String, Integer>emptyMap(), bimap);
      assertEquals(Collections.<String, Integer>emptyMap(), bimap.inverse());
    }

    public void testFromHashMap() {
      Map<String, Integer> hashMap = Maps.newLinkedHashMap();
      hashMap.put("one", 1);
      hashMap.put("two", 2);
      ImmutableBiMap<String, Integer> bimap =
          ImmutableBiMap.copyOf(ImmutableMap.of("one", 1, "two", 2));
      assertMapEquals(bimap, "one", 1, "two", 2);
      assertMapEquals(bimap.inverse(), 1, "one", 2, "two");
    }

    public void testFromImmutableMap() {
      ImmutableBiMap<String, Integer> bimap =
          ImmutableBiMap.copyOf(
              new ImmutableMap.Builder<String, Integer>()
                  .put("one", 1)
                  .put("two", 2)
                  .put("three", 3)
                  .put("four", 4)
                  .put("five", 5)
                  .build());
      assertMapEquals(bimap, "one", 1, "two", 2, "three", 3, "four", 4, "five", 5);
      assertMapEquals(bimap.inverse(), 1, "one", 2, "two", 3, "three", 4, "four", 5, "five");
    }

    public void testDuplicateValues() {
      ImmutableMap<String, Integer> map =
          new ImmutableMap.Builder<String, Integer>()
              .put("one", 1)
              .put("two", 2)
              .put("uno", 1)
              .put("dos", 2)
              .build();

      try {
        ImmutableBiMap.copyOf(map);
        fail();
      } catch (IllegalArgumentException expected) {
        assertThat(expected.getMessage()).contains("1");
      }
    }

    // TODO(b/172823566): Use mainline testToImmutableBiMap once CollectorTester is usable to java7.
    public void testToImmutableBiMap_java7_combine() {
      ImmutableBiMap.Builder<String, Integer> zis =
          ImmutableBiMap.<String, Integer>builder().put("one", 1);
      ImmutableBiMap.Builder<String, Integer> zat =
          ImmutableBiMap.<String, Integer>builder().put("two", 2).put("three", 3);
      ImmutableBiMap<String, Integer> biMap = zis.combine(zat).build();
      assertMapEquals(biMap, "one", 1, "two", 2, "three", 3);
    }

    // TODO(b/172823566): Use mainline testToImmutableBiMap once CollectorTester is usable to java7.
    public void testToImmutableBiMap_exceptionOnDuplicateKey_java7_combine() {
      ImmutableBiMap.Builder<String, Integer> zis =
          ImmutableBiMap.<String, Integer>builder().put("one", 1).put("two", 2);
      ImmutableBiMap.Builder<String, Integer> zat =
          ImmutableBiMap.<String, Integer>builder().put("two", 22).put("three", 3);
      try {
        zis.combine(zat).build();
        fail("Expected IllegalArgumentException");
      } catch (IllegalArgumentException expected) {
        // expected
      }
    }
  }

  public static class BiMapSpecificTests extends TestCase {

    public void testForcePut() {
      BiMap<String, Integer> bimap = ImmutableBiMap.copyOf(ImmutableMap.of("one", 1, "two", 2));
      try {
        bimap.forcePut("three", 3);
        fail();
      } catch (UnsupportedOperationException expected) {
      }
    }

    public void testKeySet() {
      ImmutableBiMap<String, Integer> bimap =
          ImmutableBiMap.copyOf(ImmutableMap.of("one", 1, "two", 2, "three", 3, "four", 4));
      Set<String> keys = bimap.keySet();
      assertEquals(Sets.newHashSet("one", "two", "three", "four"), keys);
      assertThat(keys).containsExactly("one", "two", "three", "four").inOrder();
    }

    public void testValues() {
      ImmutableBiMap<String, Integer> bimap =
          ImmutableBiMap.copyOf(ImmutableMap.of("one", 1, "two", 2, "three", 3, "four", 4));
      Set<Integer> values = bimap.values();
      assertEquals(Sets.newHashSet(1, 2, 3, 4), values);
      assertThat(values).containsExactly(1, 2, 3, 4).inOrder();
    }

    public void testDoubleInverse() {
      ImmutableBiMap<String, Integer> bimap =
          ImmutableBiMap.copyOf(ImmutableMap.of("one", 1, "two", 2));
      assertSame(bimap, bimap.inverse().inverse());
    }

    @GwtIncompatible // SerializableTester
    public void testEmptySerialization() {
      ImmutableBiMap<String, Integer> bimap = ImmutableBiMap.of();
      assertSame(bimap, SerializableTester.reserializeAndAssert(bimap));
    }

    @GwtIncompatible // SerializableTester
    public void testSerialization() {
      ImmutableBiMap<String, Integer> bimap =
          ImmutableBiMap.copyOf(ImmutableMap.of("one", 1, "two", 2));
      ImmutableBiMap<String, Integer> copy = SerializableTester.reserializeAndAssert(bimap);
      assertEquals(Integer.valueOf(1), copy.get("one"));
      assertEquals("one", copy.inverse().get(1));
      assertSame(copy, copy.inverse().inverse());
    }

    @GwtIncompatible // SerializableTester
    public void testInverseSerialization() {
      ImmutableBiMap<String, Integer> bimap =
          ImmutableBiMap.copyOf(ImmutableMap.of(1, "one", 2, "two")).inverse();
      ImmutableBiMap<String, Integer> copy = SerializableTester.reserializeAndAssert(bimap);
      assertEquals(Integer.valueOf(1), copy.get("one"));
      assertEquals("one", copy.inverse().get(1));
      assertSame(copy, copy.inverse().inverse());
    }
  }

  private static <K, V> void assertMapEquals(Map<K, V> map, Object... alternatingKeysAndValues) {
    int i = 0;
    for (Entry<K, V> entry : map.entrySet()) {
      assertEquals(alternatingKeysAndValues[i++], entry.getKey());
      assertEquals(alternatingKeysAndValues[i++], entry.getValue());
    }
  }

  /** No-op test so that the class has at least one method, making Maven's test runner happy. */
  public void testNoop() {}
}


text:
/*
 * java.lang.reflect.Constructor
 */
#include "Dalvik.h"
#include "native/InternalNativePriv.h"

/*
 * public int getConstructorModifiers(Class declaringClass, int slot)
 */
static void Dalvik_java_lang_reflect_Constructor_getConstructorModifiers(
    const u4* args, JValue* pResult)
{
    // ignore thisPtr in args[0]
    ClassObject* declaringClass = (ClassObject*) args[1];
    int slot = args[2];
    Method* meth;

    meth = dvmSlotToMethod(declaringClass, slot);
    RETURN_INT(dvmFixMethodFlags(meth->accessFlags));
}

/*
 * public int constructNative(Object[] args, Class declaringClass,
 *     Class[] parameterTypes, int slot, boolean noAccessCheck)
 *
 * We get here through Constructor.newInstance().  The Constructor object
 * would not be available if the constructor weren't public (per the
 * definition of Class.getConstructor), so we can skip the method access
 * check.  We can also safely assume the constructor isn't associated
 * with an interface, array, or primitive class.
 */
static void Dalvik_java_lang_reflect_Constructor_constructNative(
    const u4* args, JValue* pResult)
{
    // ignore thisPtr in args[0]
    ArrayObject* argList = (ArrayObject*) args[1];
    ClassObject* declaringClass = (ClassObject*) args[2];
    ArrayObject* params = (ArrayObject*) args[3];
    int slot = args[4];
    bool noAccessCheck = (args[5] != 0);
    Object* newObj;
    Method* meth;

    if (dvmIsAbstractClass(declaringClass)) {
        dvmThrowExceptionWithClassMessage("Ljava/lang/InstantiationException;",
            declaringClass->descriptor);
        RETURN_VOID();
    }

    /* initialize the class if it hasn't been already */
    if (!dvmIsClassInitialized(declaringClass)) {
        if (!dvmInitClass(declaringClass)) {
            LOGW("Class init failed in Constructor.constructNative (%s)\n",
                declaringClass->descriptor);
            assert(dvmCheckException(dvmThreadSelf()));
            RETURN_VOID();
        }
    }

    newObj = dvmAllocObject(declaringClass, ALLOC_DEFAULT);
    if (newObj == NULL)
        RETURN_PTR(NULL);

    meth = dvmSlotToMethod(declaringClass, slot);
    assert(meth != NULL);

    (void) dvmInvokeMethod(newObj, meth, argList, params, NULL, noAccessCheck);
    dvmReleaseTrackedAlloc(newObj, NULL);
    RETURN_PTR(newObj);
}

/*
 * public Annotation[] getDeclaredAnnotations(Class declaringClass, int slot)
 *
 * Return the annotations declared for this constructor.
 */
static void Dalvik_java_lang_reflect_Constructor_getDeclaredAnnotations(
    const u4* args, JValue* pResult)
{
    // ignore thisPtr in args[0]
    ClassObject* declaringClass = (ClassObject*) args[1];
    int slot = args[2];
    Method* meth;

    meth = dvmSlotToMethod(declaringClass, slot);
    assert(meth != NULL);

    ArrayObject* annos = dvmGetMethodAnnotations(meth);
    dvmReleaseTrackedAlloc((Object*)annos, NULL);
    RETURN_PTR(annos);
}

/*
 * public Annotation[][] getParameterAnnotations(Class declaringClass, int slot)
 *
 * Return the annotations declared for this constructor's parameters.
 */
static void Dalvik_java_lang_reflect_Constructor_getParameterAnnotations(
    const u4* args, JValue* pResult)
{
    // ignore thisPtr in args[0]
    ClassObject* declaringClass = (ClassObject*) args[1];
    int slot = args[2];
    Method* meth;

    meth = dvmSlotToMethod(declaringClass, slot);
    assert(meth != NULL);

    ArrayObject* annos = dvmGetParameterAnnotations(meth);
    dvmReleaseTrackedAlloc((Object*)annos, NULL);
    RETURN_PTR(annos);
}

/*
 * private Object[] getSignatureAnnotation()
 *
 * Returns the signature annotation.
 */
static void Dalvik_java_lang_reflect_Constructor_getSignatureAnnotation(
    const u4* args, JValue* pResult)
{
    // ignore thisPtr in args[0]
    ClassObject* declaringClass = (ClassObject*) args[1];
    int slot = args[2];
    Method* meth;

    meth = dvmSlotToMethod(declaringClass, slot);
    assert(meth != NULL);

    ArrayObject* arr = dvmGetMethodSignatureAnnotation(meth);
    dvmReleaseTrackedAlloc((Object*) arr, NULL);
    RETURN_PTR(arr);
}

const DalvikNativeMethod dvm_java_lang_reflect_Constructor[] = {
    { "constructNative",    "([Ljava/lang/Object;Ljava/lang/Class;[Ljava/lang/Class;IZ)Ljava/lang/Object;",
        Dalvik_java_lang_reflect_Constructor_constructNative },
    { "getConstructorModifiers", "(Ljava/lang/Class;I)I",
        Dalvik_java_lang_reflect_Constructor_getConstructorModifiers },
    { "getDeclaredAnnotations", "(Ljava/lang/Class;I)[Ljava/lang/annotation/Annotation;",
        Dalvik_java_lang_reflect_Constructor_getDeclaredAnnotations },
    { "getParameterAnnotations", "(Ljava/lang/Class;I)[[Ljava/lang/annotation/Annotation;",
        Dalvik_java_lang_reflect_Constructor_getParameterAnnotations },
    { "getSignatureAnnotation",  "(Ljava/lang/Class;I)[Ljava/lang/Object;",
        Dalvik_java_lang_reflect_Constructor_getSignatureAnnotation },
    { NULL, NULL, NULL },
};


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DD4T.ViewModels.Contracts;
using System.Reflection;
using System.Web;
using DD4T.ViewModels.Reflection;
using DD4T.ViewModels.Exceptions;
using System.Collections;
using DD4T.ViewModels;
using DD4T.ContentModel;

namespace DD4T.ViewModels.Attributes
{
    /// <summary>
    /// A Base class for an Attribute identifying a Property that represents some part of a View Model
    /// </summary>
    public abstract class ModelPropertyAttributeBase : Attribute, IPropertyAttribute
    {
        public abstract IEnumerable GetPropertyValues(IModel modelData, IModelProperty property, IViewModelFactory factory);
        /// <summary>
        /// When overriden in a derived class, this property returns the expected return type of the View Model property.
        /// </summary>
        /// <remarks>Primarily used for debugging purposes. This property is used to throw an accurate exception at run time if
        /// the property return type does not match with the expected type.</remarks>
        public abstract Type ExpectedReturnType { get; }

        public Binding.IModelMapping ComplexTypeMapping
        {
            get;
            set;
        }
    }

    /// <summary>
    /// A Base class for an Attribute identifying a Property that represents a Field
    /// </summary>
    /// <remarks>
    /// The field can be content, metadata, or the metadata of a template
    /// </remarks>
    public abstract class FieldAttributeBase : ModelPropertyAttributeBase, IFieldAttribute
    {
        protected bool allowMultipleValues = false;
        protected bool inlineEditable = false;
        protected bool mandatory = false; //probably don't need this one
        protected bool isMetadata = false;
        /// <summary>
        /// Creates a new Field Attribute
        /// </summary>
        public FieldAttributeBase()
        { }

        public override IEnumerable GetPropertyValues(IModel modelData, IModelProperty property, IViewModelFactory factory)
        {
            IEnumerable result = null;
            if (modelData != null)
            {
                //need null checks on Template
                IFieldSet fields = null;
                ITemplate template = null;
                if (IsTemplateMetadata)
                {
                    if (modelData is IComponentPresentation)
                    {
                        var templateData = modelData as IComponentPresentation;
                        template = templateData.ComponentTemplate;
                    }
                    else if (modelData is IPage)
                    {
                        var templateData = modelData as IPage;
                        template = templateData.PageTemplate;
                    }
                    fields = template != null ? template.MetadataFields : null;
                }
                else if (IsMetadata)
                {
                    if (modelData is IComponentPresentation)
                    {
                        fields = (modelData as IComponentPresentation).Component.MetadataFields;
                    }
                    else if (modelData is IComponent)
                    {
                        fields = (modelData as IComponent).MetadataFields;
                    }
                    else if (modelData is IPage)
                    {
                        fields = (modelData as IPage).MetadataFields;
                    }
                    else if (modelData is ITemplate)
                    {
                        fields = (modelData as ITemplate).MetadataFields;
                    }
                    else if (modelData is IKeyword)
                    {
                        fields = (modelData as IKeyword).MetadataFields;
                    }
                    //Any other things with MetadataFields?

                }
                else if (modelData is IComponentPresentation)
                {
                    fields = (modelData as IComponentPresentation).Component.Fields;
                }

                if (String.IsNullOrEmpty(FieldName)) FieldName = GetFieldName(property.Name); //Convention over configuration by default -- Field name = Property name

                if (fields != null && fields.ContainsKey(FieldName))
                {
                    result = this.GetFieldValues(fields[FieldName], property, template, factory);
                }
            }
            return result;
        }
        private string GetFieldName(string propertyName)
        {
            return propertyName.Substring(0, 1).ToLowerInvariant() + propertyName.Substring(1); //lowercase the first letter
        }
        /// <summary>
        /// When overriden in a derived class, this method should return the value of the View Model property from a Field object
        /// </summary>
        /// <param name="field">The Field</param>
        /// <param name="propertyType">The concrete type of the view model property for this attribute</param>
        /// <param name="template">The Component Template to use</param>
        /// <param name="factory">The View Model Builder</param>
        /// <returns></returns>
        public abstract IEnumerable GetFieldValues(IField field, IModelProperty property, ITemplate template,IViewModelFactory factory = null);

        /// <summary>
        /// The Tridion schema field name for this property. If not used, the property name with camel casing is used
        /// e.g. public string SubTitle { get; set; } will use schema field name "subTitle" if FieldName is not specified.
        /// </summary>
        public string FieldName
        {
            get;
            set;
        }
        /// <summary>
        /// Is a metadata field. False (default) indicates this is a content field.
        /// </summary>
        public bool IsMetadata
        {
            get { return isMetadata; }
            set { isMetadata = value; }
        }
        /// <summary>
        /// Is a template metadata field (if a template exists in the context of the property).
        /// </summary>
        public bool IsTemplateMetadata { get; set; }

    }
    /// <summary>
    /// A Base class for an Attribute identifying a Property that represents some part of a Component
    /// </summary>
    public abstract class ComponentAttributeBase : ModelPropertyAttributeBase, IComponentAttribute
    {
        public override IEnumerable GetPropertyValues(IModel modelData, IModelProperty property, IViewModelFactory factory)
        {
            IEnumerable result = null;
            if (modelData != null)
            {
                if (modelData is IComponentPresentation)
                {
                    var cpData = modelData as IComponentPresentation;
                    if (cpData != null)
                    {
                        result = GetPropertyValues(cpData.Component, property,
                            cpData.ComponentTemplate, factory);
                    }
                }
                else if (modelData is IComponent) //Not all components come with Templates (Multimedia?)
                {
                    result = GetPropertyValues(modelData as IComponent, property, null, factory);
                }
            }
            return result;
        }
        /// <summary>
        /// When overriden in a derived class, this gets the value of the Property for a given Component
        /// </summary>
        /// <param name="component">Component for the View Model</param>
        /// <param name="propertyType">Actual return type for the Property</param>
        /// <param name="template">Component Template</param>
        /// <param name="factory">View Model factory</param>
        /// <returns>The Property value</returns>
        public abstract IEnumerable GetPropertyValues(IComponent component, IModelProperty property, ITemplate template, IViewModelFactory factory);
    }

    /// <summary>
    ///  A Base class for an Attribute identifying a Property that represents some part of a Template
    /// </summary>
    public abstract class TemplateAttributeBase : ModelPropertyAttributeBase, ITemplateAttribute
    {
        /// <summary>
        /// When overriden in a derived class, this gets the value of the Property for a given Template
        /// </summary>
        /// <param name="template">Template for the View Model</param>
        /// <param name="propertyType">Actual return type for the Property</param>
        /// <param name="factory">View Model factory</param>
        /// <returns>The Property value</returns>
        public abstract IEnumerable GetPropertyValues(ITemplate template, Type propertyType, IViewModelFactory factory);

        public override IEnumerable GetPropertyValues(IModel modelData, IModelProperty property, IViewModelFactory factory)
        {
            IEnumerable result = null;
            if (modelData != null && modelData is IComponentPresentation
                && (modelData as IComponentPresentation).ComponentTemplate != null)
            {
                ITemplate templateData = (modelData as IComponentPresentation).ComponentTemplate;
                result = this.GetPropertyValues(templateData, property.ModelType, factory);
            }
            return result;
        }
    }

    /// <summary>
    /// A Base class for an Attribute identifying a Property that represents some part of a Page
    /// </summary>
    public abstract class PageAttributeBase : ModelPropertyAttributeBase, IPageAttribute
    {
        /// <summary>
        /// When overriden in a derived class, this gets the value of the Property for a given Page
        /// </summary>
        /// <param name="page">Page for the View Model</param>
        /// <param name="propertyType">Actual return type for the Property</param>
        /// <param name="factory">View Model factory</param>
        /// <returns>The Property value</returns>
        public abstract IEnumerable GetPropertyValues(IPage page, Type propertyType, IViewModelFactory factory);

        public override IEnumerable GetPropertyValues(IModel modelData, IModelProperty property, IViewModelFactory factory)
        {
            IEnumerable result = null;
            if (modelData is IPage)
            {
                var pageModel = modelData as IPage;
                result = this.GetPropertyValues(pageModel, property.ModelType, factory);
            }
            return result;
        }
    }

    /// <summary>
    /// A Base class for an Attribute identifying a Property that represents a set of Component Presentations
    /// </summary>
    /// <remarks>The View Model must be a Page</remarks>
    public abstract class ComponentPresentationsAttributeBase : ModelPropertyAttributeBase //For use in a PageModel
    {
        //Really leaving the bulk of the work to implementer -- they must both find out if the CP matches this attribute and then construct an object with it
        /// <summary>
        /// When overriden in a derived class, this gets a set of values representing Component Presentations of a Page
        /// </summary>
        /// <param name="cps">Component Presentations for the Page Model</param>
        /// <param name="propertyType">Actual return type of the Property</param>
        /// <param name="factory">A View Model factory</param>
        /// <returns>The Property value</returns>
        public abstract IEnumerable GetPresentationValues(IList<IComponentPresentation> cps, IModelProperty property, IViewModelFactory factory);

        public override IEnumerable GetPropertyValues(IModel modelData, IModelProperty property, IViewModelFactory factory)
        {
            IEnumerable result = null;
            if (modelData is IPage)
            {
                var cpModels = (modelData as IPage).ComponentPresentations;
                result = GetPresentationValues(cpModels, property, factory);
            }
            return result;
        }
    }

    /// <summary>
    /// An Attribute for identifying a Content View Model. Can be based on either Embedded Schema or Component Schema
    /// </summary>
    public class ContentModelAttribute : Attribute, IContentModelAttribute
    {
        //TODO: De-couple this from the Schema name specifically? What would make sense?
        //TOOD: Possibly change this to use purely ViewModelKey and make that an object, leave it to the key provider to assign objects with logical equals overrides

        private string schemaName;
        private bool inlineEditable = false;
        private bool isDefault = false;
        private string[] viewModelKeys;
        /// <summary>
        /// View Model
        /// </summary>
        /// <param name="schemaName">Tridion schema name for component type for this View Model</param>
        /// <param name="isDefault">Is this the default View Model for this schema. If true, Components
        /// with this schema will use this class if no other View Models' Keys match.</param>
        public ContentModelAttribute(string schemaName, bool isDefault)
        {
            this.schemaName = schemaName;
            this.isDefault = isDefault;
        }

        //Using Schema Name ties each View Model to a single Tridion Schema -- this is probably ok in 99% of cases
        //Using schema name doesn't allow us to de-couple the Model itself from Tridion however (neither does requiring
        //inheritance of IViewModel!)
        //Possible failure: if the same model was meant to represent similar parts of multiple schemas (should however
        //be covered by decent Schema design i.e. use of Embedded Schemas and Linked Components. Same fields shouldn't
        //occur repeatedly)

        public string SchemaName
        {
            get
            {
                return schemaName;
            }
        }

        /// <summary>
        /// Identifiers for further specifying which View Model to use for different presentations.
        /// </summary>
        public string[] ViewModelKeys
        {
            get { return viewModelKeys; }
            set { viewModelKeys = value; }
        }
        /// <summary>
        /// Is inline editable. Only for semantic use.
        /// </summary>
        public bool InlineEditable
        {
            get
            {
                return inlineEditable;
            }
            set
            {
                inlineEditable = value;
            }
        }

        /// <summary>
        /// Is the default View Model for the schema. If set to true, this will be the View Model to use for a given schema if no View Model ID is specified.
        /// </summary>
        public bool IsDefault { get { return isDefault; } }

        public override int GetHashCode()
        {
            return (ViewModelKeys != null ? ViewModelKeys.GetHashCode() : 0) * 37 + SchemaName.GetHashCode();
        }
        public override bool Equals(object obj)
        {
            if (obj != null && obj is ContentModelAttribute)
            {
                ContentModelAttribute key = (ContentModelAttribute)obj;
                if (this.ViewModelKeys != null && key.ViewModelKeys != null)
                {
                    //if both have a ViewModelKey set, use both ViewModelKey and schema
                    //Check for a match anywhere in both lists
                    var match = from i in this.ViewModelKeys
                                join j in key.ViewModelKeys
                                on i equals j
                                select i;
                    //Schema names match and there is a matching view model ID
                    if (this.SchemaName == key.SchemaName && match.Count() > 0)
                        return true;
                }
                //Note: if the parent of a linked component is using a View Model Key, the View Model
                //for that linked component must either be Default with no View Model Keys, or it must
                //have the View Model Key of the parent View Model
                if (((this.ViewModelKeys == null || this.ViewModelKeys.Length == 0) && key.IsDefault) //this set of IDs is empty and the input is default
                    || ((key.ViewModelKeys == null || key.ViewModelKeys.Length == 0) && this.IsDefault)) //input set of IDs is empty and this is default
                //if (key.IsDefault || this.IsDefault) //Fall back to default if the view model key isn't found -- useful for linked components
                {
                    //Just compare the schema names
                    return this.SchemaName == key.SchemaName;
                }
            }
            return false;
        }

        public bool IsMatch(IModel data, string key)
        {
            bool result = false;
            string schemaName = null;
            if (data != null)
            {
                //Ideally we'd have a common interface for these 2 that have a Schema property
                if (data is IComponent)
                {
                    var definedData = data as IComponent;
                    schemaName = definedData.Schema.Title;
                }
                else if (data is IEmbeddedFields)
                {
                    var definedData = data as IEmbeddedFields;
                    schemaName = definedData.EmbeddedSchema.Title;
                }
                if (!String.IsNullOrEmpty(schemaName))
                {
                    var compare = new ContentModelAttribute(schemaName, false)
                    {
                        ViewModelKeys = key == null ? null : new string[] { key }
                    };
                    result = this.Equals(compare);
                }
            }
            return result;
        }
    }

    /// <summary>
    /// An Attribute for identifying a Page View Model
    /// </summary>
    public class PageViewModelAttribute : Attribute, IPageModelAttribute
    {
        public PageViewModelAttribute(string[] viewModelKeys)
        {
            ViewModelKeys = viewModelKeys;
        }
        public string[] ViewModelKeys
        {
            get;
            set;
        }

        public bool IsMatch(IModel data, string key)
        {
            bool result = false;
            if (data is IPage)
            {
                var contentData = data as IPage;
                result = ViewModelKeys.Any(x => x.Equals(key));
            }
            return result;
        }
    }

    /// <summary>
    /// An Attribute for identifying a Keyword View Model
    /// </summary>
    public class KeywordViewModelAttribute : Attribute, IKeywordModelAttribute
    {
        public KeywordViewModelAttribute(string[] viewModelKeys)
        {
            ViewModelKeys = viewModelKeys;
        }
        /// <summary>
        /// View Model Keys for this Keyword
        /// </summary>
        /// <remarks>Common View Model Keys for Keywords are Metadata Schema Title or Category Title.</remarks>
        public string[] ViewModelKeys
        {
            get;
            set;
        }

        public bool IsMatch(IModel data, string key)
        {
            bool result = false;
            if (data is IKeyword)
            {
                result = ViewModelKeys.Any(x => x.Equals(key));
            }
            return result;
        }
    }

    public abstract class NestedModelFieldAttributeBase : FieldAttributeBase
    {
        public override IEnumerable GetFieldValues(IField field, IModelProperty property, ITemplate template,IViewModelFactory factory = null)
        {
            IEnumerable fieldValue = null;
            var values = GetRawValues(field);
            if (values != null)
            {
                if (ComplexTypeMapping == null && ReturnRawData)
                    fieldValue = values;
                else
                    fieldValue = values.Cast<object>()
                        .Select(value => BuildModel(factory, BuildModelData(value, field, template)))
                    .Where(value => value != null);
            }
            return fieldValue;
        }

        protected virtual object BuildModel(IViewModelFactory factory, IModel data)
        {
            object result = null;
            if (ComplexTypeMapping != null)
            {
                result = factory.BuildMappedModel(data, ComplexTypeMapping);
            }
            else
            {
                var modelType = GetModelType(data, factory);
                result = modelType != null ? factory.BuildViewModel(modelType, data) : null;
            }
            return result;
        }

        public abstract IEnumerable GetRawValues(IField field);

        protected abstract IModel BuildModelData(object value, IField field, ITemplate template);
        protected abstract Type GetModelType(IModel data, IViewModelFactory factory);
        protected abstract bool ReturnRawData { get; }

        public override Type ExpectedReturnType
        {
            get
            {
                if (ComplexTypeMapping != null)
                    return typeof(object);
                else return typeof(IViewModel);
            }
        }
    }
}


text:
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <artifactId>kylo-nifi-core-service-nar</artifactId>
  <parent>
    <groupId>com.thinkbiganalytics.kylo.integrations</groupId>
    <artifactId>kylo-nifi-core-service-bundle</artifactId>
    <version>0.9.0-SNAPSHOT</version>
  </parent>
  <packaging>nar</packaging>
  <properties>
    <maven.javadoc.skip>true</maven.javadoc.skip>
    <source.skip>true</source.skip>
    <plugin.license.parentRelative>../../../../../../</plugin.license.parentRelative>
  </properties>

  <dependencies>

    <dependency>
      <groupId>com.thinkbiganalytics.kylo.integrations</groupId>
      <artifactId>kylo-nifi-core-service</artifactId>
      <version>${project.version}</version>
    </dependency>

    <dependency>
      <groupId>com.thinkbiganalytics.kylo.integrations</groupId>
      <artifactId>kylo-nifi-standard-services-nar</artifactId>
      <version>${project.version}</version>
      <type>nar</type>
    </dependency>

  </dependencies>

</project>


text:
"""
Tutorial - Hello World

The most basic (working) CherryPy application possible.
"""

# Import CherryPy global namespace
import cherrypy

class HelloWorld:

    """ Sample request handler class. """

    def index(self):
        # CherryPy will call this method for the root URI ("/") and send
        # its return value to the client. Because this is tutorial
        # lesson number 01, we'll just send something really simple.
        # How about...
        return "Hello world!"

    # Expose the index method through the web. CherryPy will never
    # publish methods that don't have the exposed attribute set to True.
    index.exposed = True

import os.path
tutconf = os.path.join(os.path.dirname(__file__), 'tutorial.conf')

if __name__ == '__main__':
    # CherryPy always starts with app.root when trying to map request URIs
    # to objects, so we need to mount a request handler root. A request
    # to '/' will be mapped to HelloWorld().index().
    cherrypy.quickstart(HelloWorld(), config=tutconf)
else:
    # This branch is for the test suite; you can ignore it.
    cherrypy.tree.mount(HelloWorld(), config=tutconf)


text:
package org.kobjects.nativehtml.dom;

public interface HtmlCollection {

    HtmlCollection EMPTY = new HtmlCollection() {
        @Override
        public int getLength() {
            return 0;
        }

        @Override
        public Element item(int index) {
            return null;
        }
    };

    int getLength();
    Element item(int index);
}


text:
WYMeditor.WymClassSafari = function(wym) {

    this._wym = wym;
    this._class = "class";
    this._newLine = "\n";
};

WYMeditor.WymClassSafari.prototype.initIframe = function(iframe) {

    this._iframe = iframe;
    this._doc = iframe.contentDocument;

    //add css rules from options

    var styles = this._doc.styleSheets[0];
    var aCss = eval(this._options.editorStyles);

    this.addCssRules(this._doc, aCss);

    this._doc.title = this._wym._index;

    //set the text direction
    jQuery('html', this._doc).attr('dir', this._options.direction);

    //init designMode
    this._doc.designMode = "on";

    //init html value
    this.html(this._wym._html);

    //pre-bind functions
    if(jQuery.isFunction(this._options.preBind)) this._options.preBind(this);

    //bind external events
    this._wym.bindEvents();

    //bind editor keydown events
    jQuery(this._doc).bind("keydown", this.keydown);

    //bind editor keyup events
    jQuery(this._doc).bind("keyup", this.keyup);

    //post-init functions
    if(jQuery.isFunction(this._options.postInit)) this._options.postInit(this);

    //add event listeners to doc elements, e.g. images
    this.listen();
};

WYMeditor.WymClassSafari.prototype._exec = function(cmd,param) {

    if(!this.selected()) return(false);

    var focusNode = this.selected();

    switch(cmd) {

    case WYMeditor.INDENT: case WYMeditor.OUTDENT:

        var sel = this._iframe.contentWindow.getSelection();
        var anchorNode = sel.anchorNode;
        if(anchorNode.nodeName == "#text") anchorNode = anchorNode.parentNode;

        focusNode = this.findUp(focusNode, WYMeditor.BLOCKS);
        anchorNode = this.findUp(anchorNode, WYMeditor.BLOCKS);

        if(focusNode && focusNode == anchorNode &&
          focusNode.tagName.toLowerCase() == WYMeditor.LI) {

            var ancestor = focusNode.parentNode.parentNode;

            if(focusNode.parentNode.childNodes.length>1 ||
              ancestor.tagName.toLowerCase() == WYMeditor.OL ||
              ancestor.tagName.toLowerCase() == WYMeditor.UL)
                this._doc.execCommand(cmd,'',null);
        }

    break;

    case WYMeditor.INSERT_ORDEREDLIST: case WYMeditor.INSERT_UNORDEREDLIST:

        this._doc.execCommand(cmd,'',null);

        //Safari creates lists in e.g. paragraphs.
        //Find the container, and remove it.
        var container = this.findUp(focusNode, WYMeditor.MAIN_CONTAINERS);
        if(container) jQuery(container).replaceWith(jQuery(container).html());

    break;

    default:

        if(param) this._doc.execCommand(cmd,'',param);
        else this._doc.execCommand(cmd,'',null);

    break;
    }

    //set to P if parent = BODY
    container = this.selected();
    if(container && container.tagName.toLowerCase() == WYMeditor.BODY)
        this._exec(WYMeditor.FORMAT_BLOCK, WYMeditor.P);

    return true;

};

/* @name selected
 * @description Returns the selected container
 */
WYMeditor.WymClassSafari.prototype.selected = function() {

    var sel = this._iframe.contentWindow.getSelection();
    var node = sel.focusNode;
    if(node) {
        if(node.nodeName == "#text") return(node.parentNode);
        else return(node);
    } else return(null);
};

WYMeditor.WymClassSafari.prototype.addCssRule = function(styles, oCss) {

    styles.insertRule(oCss.name + " {" + oCss.css + "}",
        styles.cssRules.length);
};

//keydown handler, mainly used for keyboard shortcuts
WYMeditor.WymClassSafari.prototype.keydown = function(e) {

  //'this' is the doc
  var wym = WYMeditor.INSTANCES[this.title];

  if(e.ctrlKey){
    if(e.keyCode == 66){
      //CTRL+b => STRONG
      wym._exec(WYMeditor.BOLD);
      e.preventDefault();
    }
    if(e.keyCode == 73){
      //CTRL+i => EMPHASIS
      wym._exec(WYMeditor.ITALIC);
      e.preventDefault();
    }
  } else if(e.shiftKey && e.keyCode == 13) {
    wym._exec('InsertLineBreak');
    e.preventDefault();
  }
};

//keyup handler, mainly used for cleanups
WYMeditor.WymClassSafari.prototype.keyup = function(evt) {

  //'this' is the doc
  var wym = WYMeditor.INSTANCES[this.title];

  wym._selected_image = null;
  var container = null;

  if(evt.keyCode == 13 && !evt.shiftKey) {

    //RETURN key
    //cleanup

 between paragraphs
    jQuery(wym._doc.body).children(WYMeditor.BR).remove();

    //fix PRE bug #73
    container = wym.selected();
    if(container && container.tagName.toLowerCase() == WYMeditor.PRE)
        wym._exec(WYMeditor.FORMAT_BLOCK, WYMeditor.P); //create P after PRE
  }

  if(evt.keyCode != 8 &&
       evt.keyCode != 17 &&
       evt.keyCode != 46 &&
       evt.keyCode != 224 &&
       !evt.metaKey &&
       !evt.ctrlKey) {

    //NOT BACKSPACE, NOT DELETE, NOT CTRL, NOT COMMAND
    //text nodes replaced by P

    container = wym.selected();
    var name = container.tagName.toLowerCase();

    //fix forbidden main containers
    if(
      name == "strong" ||
      name == "b" ||
      name == "em" ||
      name == "i" ||
      name == "sub" ||
      name == "sup" ||
      name == "a" ||
      name == "span" /* fix #110 */ ) {
        name = container.parentNode.tagName.toLowerCase();
    }

    if(name == WYMeditor.BODY || name == WYMeditor.DIV) wym._exec(WYMeditor.FORMAT_BLOCK, WYMeditor.P); //fix #110 for DIV
  }
};

WYMeditor.WymClassSafari.prototype.openBlockTag = function(tag, attributes)
{
    attributes = this.validator.getValidTagAttributes(tag, attributes);

    // Handle Safari styled spans
    if (tag == 'span' && attributes.style) {
        var new_tag = this.getTagForStyle(attributes.style);
        if (new_tag) {
            tag = new_tag;
            this._tag_stack.pop();
            this._tag_stack.push(tag);
            attributes.style = '';

            // Should fix #125 - also removed the xhtml() override
            if(typeof attributes['class'] == 'string') {
                attributes['class'] = attributes['class'].replace(/apple-style-span/gi, '');
            }
        }
    }

    this.output += this.helper.tag(tag, attributes, true);
};

WYMeditor.WymClassSafari.prototype.getTagForStyle = function(style) {

  if(/bold/.test(style)) return 'strong';
  if(/italic/.test(style)) return 'em';
  if(/sub/.test(style)) return 'sub';
  if(/super/.test(style)) return 'sup';
  return false;
};


text:
VertiCal = {};

Meteor.startup(function(){
  Session.set('vertiCalStartDate', moment().format('MM/DD/YYYY') );
  Session.set('vertiCalSelectedDate', moment().format('MM/DD/YYYY') );
});

Template.vertiCal.rendered = function(){
  $('#vertiCalScrollable').bind('mousewheel',function(event){
    if (event.originalEvent.wheelDelta >= 0) {
      Session.set('vertiCalStartDate',
        moment(Session.get("vertiCalStartDate")).add(-1, 'days').format('MM/DD/YYYY')
      );
    }
    else {
      Session.set('vertiCalStartDate',
        moment(Session.get("vertiCalStartDate")).add(1, 'days').format('MM/DD/YYYY')
      );
    }
    event.preventDefault();
  });
}

Template.vertiCal.dates = function(){
  var num = this.numDays ? this.numDays : 7;
  var indexs = [];
  for( i = 0; i < num; i++ ){
    indexs.push(i);
  }
  return indexs;
}

Template.vertiCalDefaultHeader.text = function(){
  return moment(Session.get("vertiCalStartDate")).format('MMMM YYYY');
}

Template.vertiCalDefaultDateContent.active = function(){
  var current = moment(Session.get("vertiCalStartDate")).add(parseInt(this), 'days');
  var selected = Session.get("vertiCalSelectedDate");
  return current.isSame(selected,"day") ? "active" : "";
}

Template.vertiCalDefaultDateContent.customBtnContents = function(){
  return VertiCal.dateBtnContentsTemplate;
}

Template.vertiCalDefaultDateContent.text = function(){
  var current = moment(Session.get("vertiCalStartDate")).add(parseInt(this), 'days');
  var start = moment(Session.get("vertiCalStartDate"));
  return current.isSame(start,"month") ? current.format("Do") : current.format("MMM Do");
}

Template.vertiCalDefaultDateContent.events({
  'click': function(event){
    Session.set("vertiCalSelectedDate",
        moment(Session.get("vertiCalStartDate")).add(parseInt(this),'days').format("MM/DD/YYYY")
    );
  }
});

Template.vertiCalDefaultUpArrow.events({
  'click': function(event){
    var newDate = moment(Session.get('vertiCalStartDate')).add(-1,'days');
    Session.set('vertiCalStartDate', newDate.format('MM/DD/YYYY'));
  }
});

Template.vertiCalDefaultDownArrow.events({
  'click': function(event){
    var newDate = moment(Session.get('vertiCalStartDate')).add(1,'days');
    Session.set('vertiCalStartDate', newDate.format('MM/DD/YYYY') );
  }
});

Template.vertiCalJumpToToday.events({
  'click #vertiCalJumpToToday': function(event){
    Session.set('vertiCalStartDate', moment().format('MM/DD/YYYY') );
    Session.set("vertiCalSelectedDate", moment().format('MM/DD/YYYY') );
  }
});

Template.vertiCalJumpToDate.value = function(){
  return Session.get('vertiCalStartDate');
}

Template.vertiCalJumpToDate.events({
  'click #jumpToDateSubmit': function(event ){
    if( moment($('#jumpToDateInput').val()).isValid() ){
      Session.set('vertiCalStartDate', moment($('#jumpToDateInput').val()).format('MM/DD/YYYY') );
      Session.set("vertiCalSelectedDate", moment($('#jumpToDateInput').val()).format('MM/DD/YYYY') );
    }else{
      Session.set('vertiCalStartDate', moment().format('MM/DD/YYYY') );
      Session.set("vertiCalSelectedDate", moment().format('MM/DD/YYYY') );
    }
  }
});


text:
package net.mgsx.game.examples.rts.systems;

import com.badlogic.ashley.core.Entity;
import com.badlogic.ashley.core.Family;
import com.badlogic.ashley.systems.IteratingSystem;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.glutils.ShaderProgram;

import net.mgsx.game.core.GamePipeline;
import net.mgsx.game.core.GameScreen;
import net.mgsx.game.core.annotations.Editable;
import net.mgsx.game.core.annotations.EditableSystem;
import net.mgsx.game.core.helpers.ShaderProgramHelper;
import net.mgsx.game.examples.rts.components.PlanetComponent;
import net.mgsx.game.examples.rts.logic.RtsFactory;
import net.mgsx.game.plugins.core.components.Transform2DComponent;

@EditableSystem
public class PlanetRenderSystem extends IteratingSystem
{
	private GameScreen game;
	private ShaderProgram shader;
	private SpriteBatch batch;
	private Sprite sprite;

	@Editable
	public void updateShader(){
		shader = ShaderProgramHelper.reload(shader,
				Gdx.files.internal("rts/planet-vertex.glsl"),
				Gdx.files.internal("rts/planet-fragment.glsl"));
	}

	public PlanetRenderSystem(GameScreen game) {
		super(Family.all(PlanetComponent.class, Transform2DComponent.class).get(), GamePipeline.RENDER);
		this.game = game;
		updateShader();
		batch = new SpriteBatch();
		sprite = new Sprite(new Texture(Gdx.files.internal("perlin.png")));
	}

	@Override
	public void update(float deltaTime) {
		batch.setProjectionMatrix(game.camera.combined);
		batch.setShader(shader);
		batch.enableBlending();
		batch.begin();
		super.update(deltaTime);
		batch.end();
	}

	@Override
	protected void processEntity(Entity entity, float deltaTime) {
		PlanetComponent planet = entity.getComponent(PlanetComponent.class);
		Transform2DComponent transform = Transform2DComponent.components.get(entity);
		shader.setUniformf("u_color", RtsFactory.colors[planet.owner + 1]);
		batch.setColor(planet.color.set(planet.health, planet.solarDistance / 5f, planet.size, planet.population / planet.maxPopulation));
		sprite.setColor(batch.getColor());
		sprite.setBounds(transform.position.x - planet.size, transform.position.y - planet.size, planet.size * 2, planet.size * 2);
		sprite.draw(batch);
		batch.flush();
	}
}


text:
order: 4
zh-CN:
	title: 左右箭头禁用
en-US:
	title: Arrows Disabled
---

```js
import { Carousel } from 'zent';

const pages = [1, 2, 3, 4, 5];

class Simple extends React.Component {
	state = {
		current: 0,
	};

	handleChange = cur => {
		this.setState({ current: cur });
	};

	render() {
		const { current } = this.state;
		return (
			<div className="carousel-demo-container">
				<Carousel
					className="carousel-demo-simple"
					onChange={this.handleChange}
					arrows
					arrowsDisabled={{
						left: current === 0,
						right: current === pages.length - 1,
					}}
				>
					{pages.map((item, index) => {
						return (
							<div className="carousel-demo-simple-h" key={index}>
								{item}
							</div>
						);
					})}
				</Carousel>
			</div>
		);
	}
}

ReactDOM.render(<Simple />, mountNode);
```


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

Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Recommendations.OptionStatements
    Public Class StrictOptionsRecommenderTests
        Inherits RecommenderTests

        <Fact>
        <Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
        Public Sub OptionsAfterOptionStrictTest()
            VerifyRecommendationsAreExactly(<File>Option Strict |</File>, "On", "Off")
        End Sub
    End Class
End Namespace


text:
WebdriverIO Shared Store Service
=========================

> Exchange data between main process and workers (specs).

## Installation

The easiest way is to keep `@wdio/shared-store-service` as a devDependency in your `package.json`, via:

```sh
npm install @wdio/shared-store-service --save-dev
```

Instructions on how to install `WebdriverIO` can be found [here.](https://webdriver.io/docs/gettingstarted)

## Usage

Get/set a value (a plain object) to/from the store by key (string). The key can be any arbitrary string except `*` which is reserved as it allows you to fetch the whole store.

### Set Values

To set values to the store call:

```js
await browser.sharedStore.set('key', 'foobar123')
```

### Get Values

To get values from the store call:

```js
const value = await browser.sharedStore.get('key')
console.log(value) // returns "foobar123"
```

You can also fetch all key values by using the `*` key:

```js
const store = await browser.sharedStore.get('*')
console.log(value) // returns `{ key: "foobar" }`
```

### Access Store in WDIO Hooks

You could also directly access to `setValue` and `getValue` async handlers.
Make sure you properly call them with the `await` keyword.

```js
import { setValue } from '@wdio/shared-store-service'

// ...
onPrepare: [async function (config, capabilities) {
    await setValue('foo', 'bar')
}],
```

IMPORTANT! Every spec file should be atomic and isolated from others' specs.
The idea of the service is to deal with very specific environment setup issues.
Please avoid sharing test execution data!

## Configuration

Add `shared-store` to the services list and the `sharedStore` object will be accessible to you in your test.

```js
// wdio.conf.js
export const config = {
    // ...
    services: ['shared-store'],
    // ...
};
```


text:
<?php

// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.

defined('MOODLE_INTERNAL') || die();

$string['page-admin-current'] = 'La página de administración del sitio actual';
$string['page-admin-x'] = 'Cualquier página de administración del sitio';
$string['page-course-index'] = 'Página vista por categorías';
$string['page-course-index-category'] = 'Página vista de la categoría actual';
$string['page-course-index-x'] = 'Página vista de todas las categorías';
$string['page-course-report-x'] = 'Cualquier informe del curso';
$string['page-course-search'] = 'Página de búsqueda de cursos';
$string['page-course-view-x'] = 'Cualquier tipo de página principal de curso';
$string['page-course-x'] = 'Cualquier página de curso';
$string['page-mod-x'] = 'Cualquier página de actividad del módulo';
$string['page-mod-x-view'] = 'Cualquier página principal de actividad del módulo';
$string['page-my-index'] = 'Página Área personal';
$string['page-report-x'] = 'Cualquier página de reporte';
$string['page-site-index'] = 'Sólo página principal';
$string['page-site-x'] = 'Cualquier página del nivel superior del sitio';
$string['page-user-profile'] = 'Solamente páginas de perfil de usuario';
$string['page-user-view'] = 'Sólo páginas de perfil de usuario';
$string['page-user-x'] = 'Todas las páginas de usuario';
$string['page-x'] = 'Cualquier página';


text:
from netforce.model import Model, fields, get_model
from netforce.database import get_connection
from datetime import *
import time
from netforce.access import get_active_company

def js_time(d):
    return time.mktime(d.timetuple()) * 1000

class ReportPayable(Model):
    _name = "report.payable"
    _store = False

    def money_out(self, context={}):
        company_id = get_active_company()
        company_ids = get_model("company").search([["id", "child_of", company_id]])
        db = get_connection()
        res = db.query(
            "SELECT COALESCE(l.due_date,l.move_date) AS due_date,SUM(l.credit-l.debit) as amount FROM account_move_line l JOIN account_account a ON a.id=l.account_id LEFT JOIN account_reconcile r ON r.id=l.reconcile_id WHERE l.move_state='posted' AND a.type='payable' AND l.reconcile_id IS NULL AND a.company_id IN %s GROUP BY COALESCE(l.due_date,l.move_date)", tuple(company_ids))
        amounts = {}
        for r in res:
            amounts[r.due_date] = r.amount
        values = []
        d0 = date.today()
        d1 = d0 + timedelta(days=60)
        d = d0
        while d < d1:
            ds = d.strftime("%Y-%m-%d")
            values.append((js_time(d), amounts.get(ds, 0)))
            d += timedelta(days=1)
        data = {
            "value": [{
                "key": "Payable",
                "values": values,
            }]
        }
        res = db.get(
            "SELECT count(*) AS count,SUM(amount_total_cur) AS amount FROM account_invoice WHERE type='in' AND inv_type='invoice' AND state='draft' AND company_id IN %s", tuple(company_ids))
        if res:
            data["draft_count"] = res.count
            data["draft_amount"] = res.amount
        res = db.get(
            "SELECT count(*) AS count,SUM(amount_total_cur) AS amount FROM account_invoice WHERE type='in' AND inv_type='invoice' AND state='waiting_payment' AND due_date<now() AND company_id IN %s", tuple(company_ids))
        if res:
            data["overdue_count"] = res.count
            data["overdue_amount"] = res.amount
        return data

    def payable_status(self, context={}):
        company_id = get_active_company()
        company_ids = get_model("company").search([["id", "child_of", company_id]])
        data = {}
        for st in ("draft", "waiting_approval", "waiting_payment"):
            data[st] = {
                "count": 0,
                "amount": 0,
            }
        db = get_connection()
        res = db.query(
            "SELECT state,COUNT(*) as count,SUM(amount_due_cur) as amount FROM account_invoice WHERE type='in' AND inv_type='invoice' AND company_id IN %s GROUP BY state", tuple(company_ids))
        for r in res:
            data[r["state"]] = {
                "count": r["count"],
                "amount": r["amount"],
            }
        return data

ReportPayable.register()


text:
require 'test_helper'
require 'local_service_importer'

class LocalServiceImporterTest < ActiveSupport::TestCase
  def fixture_file(file)
    File.expand_path("fixtures/" + file, File.dirname(__FILE__))
  end

  context "update" do
    setup do
      LocalServiceImporter.stubs(:new).returns(stub(:run))
    end

    should "create a new instance with a filehandle on the services csv, and run it" do
      stub_fh = stub(:close)
      File.expects(:open).with('data/local_services.csv', 'r:Windows-1252:UTF-8').returns(stub_fh)
      LocalServiceImporter.expects(:new).with(stub_fh).returns(stub(:run))
      LocalServiceImporter.update
    end

    should "run it" do
      instance = stub()
      instance.expects(:run)
      LocalServiceImporter.stubs(:new).returns(instance)
      LocalServiceImporter.update
    end

    should "close the filehandle when done" do
      stub_fh = stub()
      File.stubs(:open).with('data/local_services.csv', anything() ).returns(stub_fh)
      stub_fh.expects(:close)
      LocalServiceImporter.update
    end
  end

  context "CSV of service definitions" do
    setup do
      @sample_csv = File.open(fixture_file('local_services_sample.csv'))
    end

    should "import the definitions" do
      assert_difference "LocalService.count" do
        LocalServiceImporter.new(@sample_csv).run
      end
      s = LocalService.first
      assert_equal 'Find out about hazardous waste collection', s.description
      assert_equal 850, s.lgsl_code
      assert_equal %w{county unitary}, s.providing_tier
    end

    should "not duplicate definitions if running the import again" do
      LocalServiceImporter.new(@sample_csv).run
      assert_difference "LocalService.count", 0 do
        LocalServiceImporter.new(@sample_csv).run
      end
    end
  end

  context "updates to service definitions" do
    setup do
      @sample_csv = File.open(fixture_file('local_services_sample.csv'))
      @update_csv = File.open(fixture_file('local_services_update_sample.csv'))
      LocalServiceImporter.new(@sample_csv).run
    end

    should "update description and providing tier" do
      LocalServiceImporter.new(@update_csv).run
      s = LocalService.first
      assert_equal 850, s.lgsl_code
      assert_equal 'Updated hazardous waste collection description', s.description
      assert_equal %w{district unitary}, s.providing_tier
    end
  end
end


text:
*OCaml must be installed on your local machine to compile and run the projects. To install, see below*

### Mac OS
```
brew install ocaml
```

### Linux
```
apt-get install ocaml
```


text:
<?xml version="1.0" encoding="UTF-8"?>

<!--

-->

<types xmlns="commonj.sdo"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:sdoXML="commonj.sdo/xml"
  xsi:schemaLocation="commonj.sdo sdoModel.xsd commonj.sdo/java sdoJava.xsd commonj.sdo/xml sdoXML.xsd">

<!--
   Global properties used in open content for
   the XML binding of SDO Types and Properties.
-->

  <type uri="commonj.sdo/xml">
    <property name="xmlElement" type="commonj.sdo#Boolean"/>
  </type>

  <!-- XMLInfo deprecated in 2.1.0 -->
  <type name="XMLInfo" uri="commonj.sdo/xml">
    <property name="xmlElement" type="commonj.sdo#Boolean"/>
  </type>

</types>


text:
package org.jboss.as.quickstarts.deltaspike.projectstage.util;

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

import javax.enterprise.inject.Any;
import javax.enterprise.inject.Instance;
import javax.enterprise.inject.Produces;
import javax.inject.Inject;
import javax.inject.Named;

import org.apache.deltaspike.core.api.projectstage.ProjectStage;
import org.apache.deltaspike.core.util.ProjectStageProducer;
import org.jboss.as.quickstarts.deltaspike.projectstage.bean.MessageProvider;

/**
 *
 * This class uses CDI to produce the Current {@link ProjectStage} and get the available list of {@link MessageProvider}
 * implementations
 *
 * @author Rafael Benevides
 *
 */
public class Resources {

    @Inject
    @Any
    // Allows the application to dynamically obtain instances of MessageProvider instances
    private Instance<MessageProvider> mesageProviders;

    /**
     * Return the current {@link ProjectStage}
     *
     * @return
     */
    @Produces
    @Named
    public ProjectStage currentProjectStage() {
        return ProjectStageProducer.getInstance().getProjectStage();
    }

    /**
     * This will create a {@link MessageProvider} {@link List} to be exposed as #{availableMessageProvidersImplementations} expression
     *
     * @return Return all available instances of {@link MessageProvider} implementations.
     */
    @Produces
    @Named
    public List<MessageProvider> availableMessageProvidersImplementations() {
        // * Since {@link Instance} only provides an {@link Iterator}, we need to convert it to a {@link List} so we can display
        // it on the JSF page
        return convertToList(mesageProviders.iterator());
    }

    /**
     * This utility method will convert any {@link Iterator} to a {@link List}
     *
     * @param the {@link Iterator}
     * @return the {@link List}
     */
    private <T> List<T> convertToList(Iterator<T> i) {
        List<T> list = new ArrayList<T>();
        while (i.hasNext()) {
            list.add(i.next());
        }
        return list;
    }
}


text:
#pragma once

#include "esp_err.h"

#define ESP_VFS_FLAG_CONTEXT_PTR    1
#define ESP_VFS_PATH_MAX            15


text:
package MySQLProtocol

type Packet_COM_DELAYED_INSERT struct {
	Packet
}

func (packet Packet_COM_DELAYED_INSERT) GetPacketSize(context Context) (size uint64) {
	size += 1
	return size
}

func (packet Packet_COM_DELAYED_INSERT) ToPacket(context Context) (data []byte) {
	size := packet.GetPacketSize(context)

	data = make([]byte, 0, size+4)
	data = append(data, BuildFixedLengthInteger3(uint32(size))...)
	data = append(data, BuildFixedLengthInteger1(packet.sequence_id)...)
	data = append(data, COM_DELAYED_INSERT)

	return data
}

func (packet *Packet_COM_DELAYED_INSERT) FromPacket(context Context, data Proto) {
	data.GetFixedLengthInteger3()
	packet.sequence_id = data.GetFixedLengthInteger1()
	data.GetFixedLengthInteger1()
}


text:
package io.github.thankpoint.core.impl.strategy;

import org.assertj.core.api.Assertions;
import org.junit.Test;

import io.github.thankpoint.core.api.strategy.ThankGlobalStrategy;
import io.github.thankpoint.core.api.strategy.ThankStrategyFactory;
import io.github.thankpoint.core.api.strategy.ThankVersionStrategy;
import io.github.thankpoint.core.impl.io.ThankTokenReaderDelegate;
import io.github.thankpoint.core.impl.io.ThankTokenReaderImpl;
import io.github.thankpoint.core.impl.io.ThankTokenWriterDelegate;
import io.github.thankpoint.core.impl.io.ThankTokenWriterImpl;
import io.github.thankpoint.core.impl.signing.ThankTokenSignerDelegate;
import io.github.thankpoint.core.impl.signing.ThankTokenSignerImpl;
import io.github.thankpoint.core.impl.signing.ThankTokenTxSecretGeneratorImpl;
import io.github.thankpoint.core.impl.validation.ThankTokenValidatorDelegate;
import io.github.thankpoint.core.impl.validation.ThankTokenValidatorImpl;

/**
 * Test of {@link ThankGlobalStrategy} and {@link ThankStrategyFactory#getGlobalStrategy()}.
 *
 * @author thks
 */
public class ThankVersionStrategyTest extends Assertions {

  /**
   * Test that {@link ThankStrategyFactory#getGlobalStrategy()} finds the corret implementation via service loader.
   */
  @Test
  public void testGlobalStrategy() {

    ThankGlobalStrategy globalStrategy = ThankStrategyFactory.get().getGlobalStrategy();
    assertThat(globalStrategy).isNotNull().isInstanceOf(ThankGlobalStrategyImpl.class);
    assertThat(globalStrategy.getReader()).isNotNull().isSameAs(ThankTokenReaderDelegate.get());
    assertThat(globalStrategy.getWriter()).isNotNull().isSameAs(ThankTokenWriterDelegate.get());
    assertThat(globalStrategy.getSigner()).isNotNull().isSameAs(ThankTokenSignerDelegate.get());
    assertThat(globalStrategy.getValidator()).isNotNull().isSameAs(ThankTokenValidatorDelegate.get());
    assertThat(globalStrategy.createBuffer().capacity()).isEqualTo(2287);
  }

  /**
   * Test that {@link ThankStrategyFactory#getGlobalStrategy()} finds the corret implementation via service loader.
   */
  @Test
  public void testVersionStrategy() {

    ThankStrategyFactory factory = ThankStrategyFactory.get();
    assertThat(factory.getVersions()).containsExactly(ThankVersionStrategyV001.VERSION);
    assertThat(factory.getLatestVersion()).isEqualTo(ThankVersionStrategyV001.VERSION);
    ThankVersionStrategy strategy = factory.getLatestStrategy();
    assertThat(strategy).isNotNull().isInstanceOf(ThankVersionStrategyV001.class);
    assertThat(strategy.getVersion()).isEqualTo(ThankVersionStrategyV001.VERSION);
    assertThat(strategy.getReader()).isInstanceOf(ThankTokenReaderImpl.class);
    assertThat(strategy.getWriter()).isInstanceOf(ThankTokenWriterImpl.class);
    assertThat(strategy.getSigner()).isInstanceOf(ThankTokenSignerImpl.class);
    assertThat(strategy.getValidator()).isInstanceOf(ThankTokenValidatorImpl.class);
    assertThat(strategy.getTxSecretGenerator()).isInstanceOf(ThankTokenTxSecretGeneratorImpl.class);
  }

}


text:
//
//  NSDate+TTExt2Format.m
//  TTLightKit
//
//  Created by 天智慧启 on 2017/5/15.
//  Copyright © 2017年 天智慧启. All rights reserved.
//

#import "NSDate+TTExt2Format.h"
#import "NSDate+TTExt.h"

@implementation NSDate (TTExt2Format)

/**
 * 根据日期返回字符串 format源字符串格式
 */
+ (NSString *)tt_stringWithDate:(NSDate *)date format:(NSString *)format {
    return [date tt_stringWithFormat:format];
}

- (NSString *)tt_stringWithFormat:(NSString *)format {
    NSDateFormatter *outputFormatter = [[NSDateFormatter alloc] init];
    [outputFormatter setDateFormat:format];

    NSString *retStr = [outputFormatter stringFromDate:self];

    return retStr;
}

+ (NSDate *)tt_dateWithString:(NSString *)string format:(NSString *)format {
    NSDateFormatter *inputFormatter = [[NSDateFormatter alloc] init];
    [inputFormatter setDateFormat:format];

    NSDate *date = [inputFormatter dateFromString:string];

    return date;
}

/**
 * 分别获取yyyy-MM-dd/HH:mm:ss/yyyy-MM-dd HH:mm:ss格式的字符串
 */
- (NSString *)tt_ymdFormat {
    return [NSDate tt_ymdFormat];
}
+ (NSString *)tt_ymdFormat {
    return @"yyyy-MM-dd";
}
- (NSString *)tt_hmsFormat {
    return [NSDate tt_hmsFormat];
}
+ (NSString *)tt_hmsFormat {
     return @"HH:mm:ss";
}
- (NSString *)tt_ymdHmsFormat {
    return [NSDate tt_ymdHmsFormat];
}
+ (NSString *)tt_ymdHmsFormat {
    return [NSString stringWithFormat:@"%@ %@", [self tt_ymdFormat], [self tt_hmsFormat]];
}

/**
 * 返回x分钟前/x小时前/昨天/x天前/x个月前/x年前
 */
- (NSString *)tt_stringWithTimeInfo {
    return [NSDate tt_stringWithTimeInfoByDate:self];
}
+ (NSString *)tt_stringWithTimeInfoByDate:(NSDate *)date {
    return [self tt_stringWithTimeInfoByDateString:[self tt_stringWithDate:date format:[self tt_ymdHmsFormat]]];
}
+ (NSString *)tt_stringWithTimeInfoByDateString:(NSString *)dateString {
    NSDate *date = [self tt_dateWithString:dateString format:[self tt_ymdHmsFormat]];

    NSDate *curDate = [NSDate date];
    NSTimeInterval time = -[date timeIntervalSinceDate:curDate];

    int month = (int)([curDate month] - [date month]);
    int year = (int)([curDate year] - [date year]);
    int day = (int)([curDate day] - [date day]);

    NSTimeInterval retTime = 1.0;
    if (time < 3600) { // 小于一小时
        retTime = time / 60;
        retTime = retTime <= 0.0 ? 1.0 : retTime;
        return [NSString stringWithFormat:@"%.0f分钟前", retTime];
    } else if (time < 3600 * 24) { // 小于一天,也就是今天
        retTime = time / 3600;
        retTime = retTime <= 0.0 ? 1.0 : retTime;
        return [NSString stringWithFormat:@"%.0f小时前", retTime];
    } else if (time < 3600 * 24 * 2) {
        return @"昨天";
    }
    // 第一个条件是同年,且相隔时间在一个月内
    // 第二个条件是隔年,对于隔年,只能是去年12月与今年1月这种情况
    else if ((abs(year) == 0 && abs(month) <= 1)
             || (abs(year) == 1 && [curDate month] == 1 && [date month] == 12)) {
        int retDay = 0;
        if (year == 0) { // 同年
            if (month == 0) { // 同月
                retDay = day;
            }
        }

        if (retDay <= 0) {
            // 获取发布日期中,该月有多少天
            int totalDays = (int)[self daysInMonth:date month:[date month]];

            // 当前天数 + (发布日期月中的总天数-发布日期月中发布日,即等于距离今天的天数)
            retDay = (int)[curDate day] + (totalDays - (int)[date day]);
        }

        return [NSString stringWithFormat:@"%d天前", (abs)(retDay)];
    } else  {
        if (abs(year) <= 1) {
            if (year == 0) { // 同年
                return [NSString stringWithFormat:@"%d个月前", abs(month)];
            }

            // 隔年
            int month = (int)[curDate month];
            int preMonth = (int)[date month];
            if (month == 12 && preMonth == 12) {// 隔年,但同月,就作为满一年来计算
                return @"1年前";
            }
            return [NSString stringWithFormat:@"%d个月前", (abs)(12 - preMonth + month)];
        }

        return [NSString stringWithFormat:@"%d年前", abs(year)];
    }

    return @"1小时前";
}

/**
 days 之前显示 x分钟前/x小时前/昨天/x天前, 之后显示成日期

 @param days 几天的时间
 @return days 之前显示 x分钟前/x小时前/昨天/x天前, 之后显示成日期
 */
- (NSString *)tt_stringWithTimeInfoByAfterDaysOfInteger:(NSInteger)days {
    NSInteger daysAgo = [self daysAgo];
    if (daysAgo > days) {
        return [self tt_ymdHmsFormat];
    }
    return [self tt_stringWithTimeInfo];
}

#pragma mark - private
+ (NSUInteger)daysInMonth:(NSDate *)date month:(NSUInteger)month {
    switch (month) {
        case 1: case 3: case 5: case 7: case 8: case 10: case 12:
            return 31;
        case 2:
            return [date isLeapYear] ? 29 : 28;
    }
    return 30;
}

- (NSUInteger)daysAgo {
    return [NSDate daysAgo:self];
}

+ (NSUInteger)daysAgo:(NSDate *)date {
    NSCalendar *calendar = [NSCalendar currentCalendar];

#if __IPHONE_OS_VERSION_MIN_REQUIRED >= __IPHONE_8_0
    NSDateComponents *components = [calendar components:(NSCalendarUnitDay)
                                               fromDate:date
                                                 toDate:[NSDate date]
                                                options:0];
#else
    NSDateComponents *components = [calendar components:(NSDayCalendarUnit)
                                               fromDate:date
                                                 toDate:[NSDate date]
                                                options:0];
#endif

    return [components day];
}
@end


text:
package com.facebook.reactnative.demo;

import android.app.Activity;
import android.os.Bundle;
import android.view.KeyEvent;

import com.facebook.react.LifecycleState;
import com.facebook.react.ReactInstanceManager;
import com.facebook.react.ReactRootView;
import com.facebook.react.modules.core.DefaultHardwareBackBtnHandler;
import com.facebook.react.shell.MainReactPackage;

public class HelloWorld extends Activity implements DefaultHardwareBackBtnHandler {

    private ReactInstanceManager mReactInstanceManager;
    private ReactRootView mReactRootView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mReactRootView = new ReactRootView(this);

        mReactInstanceManager = ReactInstanceManager.builder()
                .setApplication(getApplication())
//                .setBundleAssetName("helloword.bundle")
                .setJSMainModuleName("demo-for-eclipse/react_native_demo/js/HelloWorld/index.android")
                .addPackage(new MainReactPackage())
                .setUseDeveloperSupport(BuildConfig.DEBUG)
                .setInitialLifecycleState(LifecycleState.RESUMED)
                .build();

        mReactRootView.startReactApplication(mReactInstanceManager, "AwesomeProject", null);

        setContentView(mReactRootView);
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_MENU && mReactInstanceManager != null) {
            mReactInstanceManager.showDevOptionsDialog();
            return true;
        }
        return super.onKeyUp(keyCode, event);
    }

    @Override
    public void onBackPressed() {
      if (mReactInstanceManager != null) {
        mReactInstanceManager.onBackPressed();
      } else {
        super.onBackPressed();
      }
    }

    @Override
    public void invokeDefaultOnBackPressed() {
      super.onBackPressed();
    }

    @Override
    protected void onPause() {
        super.onPause();

        if (mReactInstanceManager != null) {
            mReactInstanceManager.onPause();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();

        if (mReactInstanceManager != null) {
            mReactInstanceManager.onResume(this, this);
        }
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<Configuration>
    <Appenders>
        <Null name="null"/>
    </Appenders>
    <Loggers>
        <AsyncLogger name="com.foo" />
        <AsyncRoot level="trace">
            <AppenderRef ref="null" />
        </AsyncRoot>
    </Loggers>
</Configuration>


text:
---
uid: SolidEdgePart.CloseCorners.Add(System.Object,System.Object,System.Object,System.Double,System.Double,System.Double,System.Double,System.Double,System.Double)
summary:
remarks:
example: [*content]
---
[!code-vb[Main](..\snippets\SolidEdgePart.CloseCorners.Add.vb]
[!code-csharp[Main](..\snippets\SolidEdgePart.CloseCorners.Add.cs]


text:
/* AGLightSettingsEditor.cs
 *
 * This extends AGLightSettings.cs for interactive UI in the editor.
 *
 * Joe Yip
 * 2015-Aug-14
 * yip@ict.usc.edu
 */
using UnityEditor;
using UnityEngine;
using System.Collections;
using System.Collections.Generic;

[CustomEditor(typeof(AGLightSettings))]
public class AGLightSettingsEditor : Editor
{
    public override void OnInspectorGUI()
    {
        #region Variables
        AGLightSettings m_lightsManagerCmp = (AGLightSettings)target;
        List<string> editorLightSetNameList = m_lightsManagerCmp.GetAllSetNames();

        //Initialize dropdown menu value
        int m_enabledGOs = 0;
        for (int i = 0; i < m_lightsManagerCmp.GetAllSetNames().Count; i++)
        {
            bool m_goActive = m_lightsManagerCmp.m_goSets[i].m_active;

            if (m_goActive)
            {
                m_lightsManagerCmp.m_currentToggledGoSet = i;
                m_enabledGOs += 1;
            }
        }
        if (m_enabledGOs > 1) { m_lightsManagerCmp.m_currentToggledGoSet = -1; }
        #endregion

        #region GUI
        int editorConfigVarIndex = EditorGUILayout.Popup("Light Set Toggle", m_lightsManagerCmp.m_currentToggledGoSet, editorLightSetNameList.ToArray());
        if (editorConfigVarIndex != m_lightsManagerCmp.m_currentToggledGoSet)
        {
            m_lightsManagerCmp.Toggle(m_lightsManagerCmp.m_goSets[editorConfigVarIndex].m_goName);
            m_lightsManagerCmp.m_currentToggledGoSet = editorConfigVarIndex;
        }
        #endregion

    }
}


text:
Login

    <form name="login-form" ng-submit="login()" class="form-signin">
      <input type="text" ng-model="user.email" id="user_email" class="form-control" placeholder="Email" autofocus="" required>
      <input type="password" ng-model="user.password" id="user_password" class="form-control" placeholder="Password" required>
      <input ng-model="user.remember_me" id="user_remember" type="checkbox"> keep me logged in
      <input type="submit" value="Login" class="btn btn-primary btn-block" id="login_user">
    </form>

    Forgot password? | Resend activation email


text:
package org.apache.ibatis.submitted.nested_query_cache;

import domain.blog.Author;

public interface AuthorMapper {

  Author selectAuthor(int id);

}


text:
package com.badlogic.gdx.graphics.g3d.loaders.ogre.skeleton;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

/**
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "")
@XmlRootElement(name = "axis")
public class Axis {

	@XmlAttribute(required = true) public float x;
	@XmlAttribute(required = true) public float y;
	@XmlAttribute(required = true) public float z;
}


text:
import {
  moduleForComponent,
  test
} from 'ember-qunit';

moduleForComponent('btn-compose', {
  // Specify the other units that are required for this test
  // needs: ['component:foo', 'helper:bar']
});

test('it renders', function(assert) {
  assert.expect(2);

  // Creates the component instance
  var component = this.subject();
  assert.equal(component._state, 'preRender');

  // Renders the component to the page
  this.render();
  assert.equal(component._state, 'inDOM');
});


text:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Mappings between typescript defs and implementations</title>
   <script src="typings/jquery/jquery.d.ts"></script>=<script src="jquery-1.11.1.js"></script>
    <script src="../tsp_script/emmet.d.ts"></script>=<script src="emmet.js"></script>
    <script src="typings/slickgrid/SlickGrid.d.ts"></script>=<script src="jquery-2.0.3.js"></script>+<script src="jquery.event.drag.js"></script>+<script src="slickGrid/slick.core.js"></script>+<script src="slickGrid/slick.dataView.js"></script>+<script src="slickGrid/slick.editors.js"></script>+<script src="slickGrid/slick.formatters.js"></script>+<script src="slickGrid/slick.groupitemmetadataprovider.js"></script>+<script src="slickGrid/slick.grid.js"></script>+<script src="jquery.event.drag.js"></script>
</head>
<body>

</body>
</html>


text:
import type { Links } from './Links';
import type { Recipe } from './Recipe';
import type { ShoppingItem } from './ShoppingItem';
import type { User } from './User';
import type { QuantitativeUnit } from './QuantitativeUnit';

// Provide all app types in one export.
export type {
  Links,
  Recipe,
  ShoppingItem,
  User,
  QuantitativeUnit,
};


text:
package com.gs.extractor.impl;

import java.util.HashSet;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.gs.extractor.Extractor;
import com.gs.utils.URL;

public final class SinaExtractor extends Extractor {

	public SinaExtractor(String html, int level, int topN, int depth) {
		super(html, level, topN, depth);
	}

	@Override
	public Extractor process() {
		String titleregex = "<title>(.+?)_新浪新闻</title>";// 去掉最后的尾坠
		Pattern titlept = Pattern.compile(titleregex);
		Matcher titlemt = titlept.matcher(this.html);
		if (titlemt.find()) {
			this.title = titlemt.group(1);
		}
		// /////////////////////////////////////////
		String contentregex = "
(.*?)
";
		Pattern contentpt = Pattern.compile(contentregex, Pattern.DOTALL);
		Matcher contentmt = contentpt.matcher(this.html);
		if (contentmt.find()) {
			this.content = contentmt.group(1);
		}
		Pattern pt1 = Pattern.compile("
(.*?)
", Pattern.DOTALL);
		Matcher mt1 = pt1.matcher(this.content);
		this.content = "";
		while (mt1.find()) {
			this.content += mt1.group(1);
		}
		this.content = this.content.replaceAll("<.*?>", "");// 抹掉所有尖括号的内容
		this.content = this.content.replaceAll("\\s", "");// 抹掉所有空白
		// ///////////////////////////////////////
		this.set = new HashSet<URL>();
		if (this.level >= this.depth && this.depth != 0) {
			;// 若已经超过抓取深度则不再提取
		} else {
			String linkregex = "]*>(.*?)";
			Pattern linkpt = Pattern.compile(linkregex);
			Matcher linkmt = linkpt.matcher(this.html);
			int counter = 0;// 已抽取的连接计数器
			while (linkmt.find()) {
				String u = linkmt.group(1);
				if (u.startsWith("http://news.sina.com.cn/")
						&& (u.endsWith("htm") || u.endsWith("html") || u
								.endsWith("shtml"))) {
					URL re = new URL(u, this.level + 1);
					this.set.add(re);// 向结果List中添加
					counter++;
				}
				if (counter > this.topN && this.topN != 0)
					break;// 是否达到topN
			}
		}
		return this;
	}

}