text:
import other.PublicClass;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/*
 * Test field access through reflection.
 */
public class Main {
  public static void main(String[] args) {
    SubClass.main(null);

    try {
      GetNonexistent.main(null);
      System.err.println("Not expected to succeed");
    } catch (VerifyError fe) {
      // dalvik
      System.out.println("Got expected failure");
    } catch (NoSuchFieldError nsfe) {
      // reference
      System.out.println("Got expected failure");
    }

    try {
      Class c = Class.forName("SubClassUsingInaccessibleField");
      Object o = c.newInstance();
      c.getMethod("test").invoke(o, null);
    } catch (InvocationTargetException ite) {
      if (ite.getCause() instanceof IllegalAccessError) {
        System.out.println("Got expected failure");
      } else {
        System.out.println("Got unexpected failure " + ite.getCause());
      }
    } catch (Exception e) {
      System.out.println("Got unexpected failure " + e);
    }
  }

  /*
   * Get the field specified by "field" from "obj".
   *
   * "type" determines which "get" call is made, e.g. 'B' turns into
   * field.getByte().
   *
   * The "expectedException" must match the class of the exception thrown,
   * or be null if no exception was expected.
   *
   * On success, the boxed value retrieved is returned.
   */
  public Object getValue(Field field, Object obj, char type,
      Class expectedException) {
    Object result = null;
    try {
      switch (type) {
        case 'Z':
          result = field.getBoolean(obj);
          break;
        case 'B':
          result = field.getByte(obj);
          break;
        case 'S':
          result = field.getShort(obj);
          break;
        case 'C':
          result = field.getChar(obj);
          break;
        case 'I':
          result = field.getInt(obj);
          break;
        case 'J':
          result = field.getLong(obj);
          break;
        case 'F':
          result = field.getFloat(obj);
          break;
        case 'D':
          result = field.getDouble(obj);
          break;
        case 'L':
          result = field.get(obj);
          break;
        default:
          throw new RuntimeException("bad type '" + type + "'");
      }

      /* success; expected? */
      if (expectedException != null) {
        System.err.println("ERROR: call succeeded for field " + field +
            " with a read of type '" + type +
            "', was expecting " + expectedException);
        Thread.dumpStack();
      }
    } catch (Exception ex) {
      if (expectedException == null) {
        System.err.println("ERROR: call failed unexpectedly: "
            + ex.getClass());
        ex.printStackTrace();
      } else {
        if (!expectedException.equals(ex.getClass())) {
          System.err.println("ERROR: incorrect exception: wanted "
              + expectedException.getName() + ", got "
              + ex.getClass());
          ex.printStackTrace();
        }
      }
    }

    return result;
  }
}

/*
 * Local class with some fields.
 */
class SamePackage {
  public boolean samePackagePublicBooleanInstanceField = true;
  public byte samePackagePublicByteInstanceField = 2;
  public char samePackagePublicCharInstanceField = 3;
  public short samePackagePublicShortInstanceField = 4;
  public int samePackagePublicIntInstanceField = 5;
  public long samePackagePublicLongInstanceField = 6;
  public float samePackagePublicFloatInstanceField = 7.0f;
  public double samePackagePublicDoubleInstanceField = 8.0;
  public Object samePackagePublicObjectInstanceField = "9";

  protected boolean samePackageProtectedBooleanInstanceField = true;
  protected byte samePackageProtectedByteInstanceField = 10;
  protected char samePackageProtectedCharInstanceField = 11;
  protected short samePackageProtectedShortInstanceField = 12;
  protected int samePackageProtectedIntInstanceField = 13;
  protected long samePackageProtectedLongInstanceField = 14;
  protected float samePackageProtectedFloatInstanceField = 15.0f;
  protected double samePackageProtectedDoubleInstanceField = 16.0;
  protected Object samePackageProtectedObjectInstanceField = "17";

  private boolean samePackagePrivateBooleanInstanceField = true;
  private byte samePackagePrivateByteInstanceField = 18;
  private char samePackagePrivateCharInstanceField = 19;
  private short samePackagePrivateShortInstanceField = 20;
  private int samePackagePrivateIntInstanceField = 21;
  private long samePackagePrivateLongInstanceField = 22;
  private float samePackagePrivateFloatInstanceField = 23.0f;
  private double samePackagePrivateDoubleInstanceField = 24.0;
  private Object samePackagePrivateObjectInstanceField = "25";

  /* package */ boolean samePackagePackageBooleanInstanceField = true;
  /* package */ byte samePackagePackageByteInstanceField = 26;
  /* package */ char samePackagePackageCharInstanceField = 27;
  /* package */ short samePackagePackageShortInstanceField = 28;
  /* package */ int samePackagePackageIntInstanceField = 29;
  /* package */ long samePackagePackageLongInstanceField = 30;
  /* package */ float samePackagePackageFloatInstanceField = 31.0f;
  /* package */ double samePackagePackageDoubleInstanceField = 32.0;
  /* package */ Object samePackagePackageObjectInstanceField = "33";

  public static boolean samePackagePublicBooleanStaticField = true;
  public static byte samePackagePublicByteStaticField = 34;
  public static char samePackagePublicCharStaticField = 35;
  public static short samePackagePublicShortStaticField = 36;
  public static int samePackagePublicIntStaticField = 37;
  public static long samePackagePublicLongStaticField = 38;
  public static float samePackagePublicFloatStaticField = 39.0f;
  public static double samePackagePublicDoubleStaticField = 40.0;
  public static Object samePackagePublicObjectStaticField = "41";

  protected static boolean samePackageProtectedBooleanStaticField = true;
  protected static byte samePackageProtectedByteStaticField = 42;
  protected static char samePackageProtectedCharStaticField = 43;
  protected static short samePackageProtectedShortStaticField = 44;
  protected static int samePackageProtectedIntStaticField = 45;
  protected static long samePackageProtectedLongStaticField = 46;
  protected static float samePackageProtectedFloatStaticField = 47.0f;
  protected static double samePackageProtectedDoubleStaticField = 48.0;
  protected static Object samePackageProtectedObjectStaticField = "49";

  private static boolean samePackagePrivateBooleanStaticField = true;
  private static byte samePackagePrivateByteStaticField = 50;
  private static char samePackagePrivateCharStaticField = 51;
  private static short samePackagePrivateShortStaticField = 52;
  private static int samePackagePrivateIntStaticField = 53;
  private static long samePackagePrivateLongStaticField = 54;
  private static float samePackagePrivateFloatStaticField = 55.0f;
  private static double samePackagePrivateDoubleStaticField = 56.0;
  private static Object samePackagePrivateObjectStaticField = "57";

  /* package */ static boolean samePackagePackageBooleanStaticField = true;
  /* package */ static byte samePackagePackageByteStaticField = 58;
  /* package */ static char samePackagePackageCharStaticField = 59;
  /* package */ static short samePackagePackageShortStaticField = 60;
  /* package */ static int samePackagePackageIntStaticField = 61;
  /* package */ static long samePackagePackageLongStaticField = 62;
  /* package */ static float samePackagePackageFloatStaticField = 63.0f;
  /* package */ static double samePackagePackageDoubleStaticField = 64.0;
  /* package */ static Object samePackagePackageObjectStaticField = "65";

  public void samePublicMethod() { }
  protected void sameProtectedMethod() { }
  private void samePrivateMethod() { }
  /* package */ void samePackageMethod() { }
}

/*
 * This is a sub-class of other.PublicClass, which should be allowed to access
 * the various protected fields declared by other.PublicClass and its parent
 * other.ProtectedClass.
 */
class SubClass extends PublicClass {
  /*
   * Perform the various tests.
   *
   * localInst.getValue() is performed using an instance of Main as the
   * source of the reflection call.  otherInst.getValue() uses a subclass
   * of OtherPackage as the source.
   */
  public static void main(String[] args) {
    SubClass subOther = new SubClass();
    subOther.doDirectTests();
    subOther.doReflectionTests();
  }

  private static void check(boolean b) {
    if (!b) {
      throw new Error("Test failed");
    }
  }

  public void doDirectTests() {
    check(otherProtectedClassPublicBooleanInstanceField == true);
    check(otherProtectedClassPublicByteInstanceField == 2);
    check(otherProtectedClassPublicCharInstanceField == 3);
    check(otherProtectedClassPublicShortInstanceField == 4);
    check(otherProtectedClassPublicIntInstanceField == 5);
    check(otherProtectedClassPublicLongInstanceField == 6);
    check(otherProtectedClassPublicFloatInstanceField == 7.0f);
    check(otherProtectedClassPublicDoubleInstanceField == 8.0);
    check(otherProtectedClassPublicObjectInstanceField == "9");

    check(otherProtectedClassProtectedBooleanInstanceField == true);
    check(otherProtectedClassProtectedByteInstanceField == 10);
    check(otherProtectedClassProtectedCharInstanceField == 11);
    check(otherProtectedClassProtectedShortInstanceField == 12);
    check(otherProtectedClassProtectedIntInstanceField == 13);
    check(otherProtectedClassProtectedLongInstanceField == 14);
    check(otherProtectedClassProtectedFloatInstanceField == 15.0f);
    check(otherProtectedClassProtectedDoubleInstanceField == 16.0);
    check(otherProtectedClassProtectedObjectInstanceField == "17");

    // check(otherProtectedClassPrivateBooleanInstanceField == true);
    // check(otherProtectedClassPrivateByteInstanceField == 18);
    // check(otherProtectedClassPrivateCharInstanceField == 19);
    // check(otherProtectedClassPrivateShortInstanceField == 20);
    // check(otherProtectedClassPrivateIntInstanceField == 21);
    // check(otherProtectedClassPrivateLongInstanceField == 22);
    // check(otherProtectedClassPrivateFloatInstanceField == 23.0f);
    // check(otherProtectedClassPrivateDoubleInstanceField == 24.0);
    // check(otherProtectedClassPrivateObjectInstanceField == "25");

    // check(otherProtectedClassPackageBooleanInstanceField == true);
    // check(otherProtectedClassPackageByteInstanceField == 26);
    // check(otherProtectedClassPackageCharInstanceField == 27);
    // check(otherProtectedClassPackageShortInstanceField == 28);
    // check(otherProtectedClassPackageIntInstanceField == 29);
    // check(otherProtectedClassPackageLongInstanceField == 30);
    // check(otherProtectedClassPackageFloatInstanceField == 31.0f);
    // check(otherProtectedClassPackageDoubleInstanceField == 32.0);
    // check(otherProtectedClassPackageObjectInstanceField == "33");

    check(otherProtectedClassPublicBooleanStaticField == true);
    check(otherProtectedClassPublicByteStaticField == 34);
    check(otherProtectedClassPublicCharStaticField == 35);
    check(otherProtectedClassPublicShortStaticField == 36);
    check(otherProtectedClassPublicIntStaticField == 37);
    check(otherProtectedClassPublicLongStaticField == 38);
    check(otherProtectedClassPublicFloatStaticField == 39.0f);
    check(otherProtectedClassPublicDoubleStaticField == 40.0);
    check(otherProtectedClassPublicObjectStaticField == "41");

    check(otherProtectedClassProtectedBooleanStaticField == true);
    check(otherProtectedClassProtectedByteStaticField == 42);
    check(otherProtectedClassProtectedCharStaticField == 43);
    check(otherProtectedClassProtectedShortStaticField == 44);
    check(otherProtectedClassProtectedIntStaticField == 45);
    check(otherProtectedClassProtectedLongStaticField == 46);
    check(otherProtectedClassProtectedFloatStaticField == 47.0f);
    check(otherProtectedClassProtectedDoubleStaticField == 48.0);
    check(otherProtectedClassProtectedObjectStaticField == "49");

    // check(otherProtectedClassPrivateBooleanStaticField == true);
    // check(otherProtectedClassPrivateByteStaticField == 50);
    // check(otherProtectedClassPrivateCharStaticField == 51);
    // check(otherProtectedClassPrivateShortStaticField == 52);
    // check(otherProtectedClassPrivateIntStaticField == 53);
    // check(otherProtectedClassPrivateLongStaticField == 54);
    // check(otherProtectedClassPrivateFloatStaticField == 55.0f);
    // check(otherProtectedClassPrivateDoubleStaticField == 56.0);
    // check(otherProtectedClassPrivateObjectStaticField == "57");

    // check(otherProtectedClassPackageBooleanStaticField == true);
    // check(otherProtectedClassPackageByteStaticField == 58);
    // check(otherProtectedClassPackageCharStaticField == 59);
    // check(otherProtectedClassPackageShortStaticField == 60);
    // check(otherProtectedClassPackageIntStaticField == 61);
    // check(otherProtectedClassPackageLongStaticField == 62);
    // check(otherProtectedClassPackageFloatStaticField == 63.0f);
    // check(otherProtectedClassPackageDoubleStaticField == 64.0);
    // check(otherProtectedClassPackageObjectStaticField == "65");

    check(otherPublicClassPublicBooleanInstanceField == true);
    check(otherPublicClassPublicByteInstanceField == -2);
    check(otherPublicClassPublicCharInstanceField == (char)-3);
    check(otherPublicClassPublicShortInstanceField == -4);
    check(otherPublicClassPublicIntInstanceField == -5);
    check(otherPublicClassPublicLongInstanceField == -6);
    check(otherPublicClassPublicFloatInstanceField == -7.0f);
    check(otherPublicClassPublicDoubleInstanceField == -8.0);
    check(otherPublicClassPublicObjectInstanceField == "-9");

    check(otherPublicClassProtectedBooleanInstanceField == true);
    check(otherPublicClassProtectedByteInstanceField == -10);
    check(otherPublicClassProtectedCharInstanceField == (char)-11);
    check(otherPublicClassProtectedShortInstanceField == -12);
    check(otherPublicClassProtectedIntInstanceField == -13);
    check(otherPublicClassProtectedLongInstanceField == -14);
    check(otherPublicClassProtectedFloatInstanceField == -15.0f);
    check(otherPublicClassProtectedDoubleInstanceField == -16.0);
    check(otherPublicClassProtectedObjectInstanceField == "-17");

    // check(otherPublicClassPrivateBooleanInstanceField == true);
    // check(otherPublicClassPrivateByteInstanceField == -18);
    // check(otherPublicClassPrivateCharInstanceField == (char)-19);
    // check(otherPublicClassPrivateShortInstanceField == -20);
    // check(otherPublicClassPrivateIntInstanceField == -21);
    // check(otherPublicClassPrivateLongInstanceField == -22);
    // check(otherPublicClassPrivateFloatInstanceField == -23.0f);
    // check(otherPublicClassPrivateDoubleInstanceField == -24.0);
    // check(otherPublicClassPrivateObjectInstanceField == "-25");

    // check(otherPublicClassPackageBooleanInstanceField == true);
    // check(otherPublicClassPackageByteInstanceField == -26);
    // check(otherPublicClassPackageCharInstanceField == (char)-27);
    // check(otherPublicClassPackageShortInstanceField == -28);
    // check(otherPublicClassPackageIntInstanceField == -29);
    // check(otherPublicClassPackageLongInstanceField == -30);
    // check(otherPublicClassPackageFloatInstanceField == -31.0f);
    // check(otherPublicClassPackageDoubleInstanceField == -32.0);
    // check(otherPublicClassPackageObjectInstanceField == "-33");

    check(otherPublicClassPublicBooleanStaticField == true);
    check(otherPublicClassPublicByteStaticField == -34);
    check(otherPublicClassPublicCharStaticField == (char)-35);
    check(otherPublicClassPublicShortStaticField == -36);
    check(otherPublicClassPublicIntStaticField == -37);
    check(otherPublicClassPublicLongStaticField == -38);
    check(otherPublicClassPublicFloatStaticField == -39.0f);
    check(otherPublicClassPublicDoubleStaticField == -40.0);
    check(otherPublicClassPublicObjectStaticField == "-41");

    check(otherPublicClassProtectedBooleanStaticField == true);
    check(otherPublicClassProtectedByteStaticField == -42);
    check(otherPublicClassProtectedCharStaticField == (char)-43);
    check(otherPublicClassProtectedShortStaticField == -44);
    check(otherPublicClassProtectedIntStaticField == -45);
    check(otherPublicClassProtectedLongStaticField == -46);
    check(otherPublicClassProtectedFloatStaticField == -47.0f);
    check(otherPublicClassProtectedDoubleStaticField == -48.0);
    check(otherPublicClassProtectedObjectStaticField == "-49");

    // check(otherPublicClassPrivateBooleanStaticField == true);
    // check(otherPublicClassPrivateByteStaticField == -50);
    // check(otherPublicClassPrivateCharStaticField == (char)-51);
    // check(otherPublicClassPrivateShortStaticField == -52);
    // check(otherPublicClassPrivateIntStaticField == -53);
    // check(otherPublicClassPrivateLongStaticField == -54);
    // check(otherPublicClassPrivateFloatStaticField == -55.0f);
    // check(otherPublicClassPrivateDoubleStaticField == -56.0);
    // check(otherPublicClassPrivateObjectStaticField == "-57");

    // check(otherPublicClassPackageBooleanStaticField == true);
    // check(otherPublicClassPackageByteStaticField == -58);
    // check(otherPublicClassPackageCharStaticField == (char)-59);
    // check(otherPublicClassPackageShortStaticField == -60);
    // check(otherPublicClassPackageIntStaticField == -61);
    // check(otherPublicClassPackageLongStaticField == -62);
    // check(otherPublicClassPackageFloatStaticField == -63.0f);
    // check(otherPublicClassPackageDoubleStaticField == -64.0);
    // check(otherPublicClassPackageObjectStaticField == "-65");

    SamePackage s = new SamePackage();
    check(s.samePackagePublicBooleanInstanceField == true);
    check(s.samePackagePublicByteInstanceField == 2);
    check(s.samePackagePublicCharInstanceField == 3);
    check(s.samePackagePublicShortInstanceField == 4);
    check(s.samePackagePublicIntInstanceField == 5);
    check(s.samePackagePublicLongInstanceField == 6);
    check(s.samePackagePublicFloatInstanceField == 7.0f);
    check(s.samePackagePublicDoubleInstanceField == 8.0);
    check(s.samePackagePublicObjectInstanceField == "9");

    check(s.samePackageProtectedBooleanInstanceField == true);
    check(s.samePackageProtectedByteInstanceField == 10);
    check(s.samePackageProtectedCharInstanceField == 11);
    check(s.samePackageProtectedShortInstanceField == 12);
    check(s.samePackageProtectedIntInstanceField == 13);
    check(s.samePackageProtectedLongInstanceField == 14);
    check(s.samePackageProtectedFloatInstanceField == 15.0f);
    check(s.samePackageProtectedDoubleInstanceField == 16.0);
    check(s.samePackageProtectedObjectInstanceField == "17");

    // check(s.samePackagePrivateBooleanInstanceField == true);
    // check(s.samePackagePrivateByteInstanceField == 18);
    // check(s.samePackagePrivateCharInstanceField == 19);
    // check(s.samePackagePrivateShortInstanceField == 20);
    // check(s.samePackagePrivateIntInstanceField == 21);
    // check(s.samePackagePrivateLongInstanceField == 22);
    // check(s.samePackagePrivateFloatInstanceField == 23.0f);
    // check(s.samePackagePrivateDoubleInstanceField == 24.0);
    // check(s.samePackagePrivateObjectInstanceField == "25");

    check(s.samePackagePackageBooleanInstanceField == true);
    check(s.samePackagePackageByteInstanceField == 26);
    check(s.samePackagePackageCharInstanceField == 27);
    check(s.samePackagePackageShortInstanceField == 28);
    check(s.samePackagePackageIntInstanceField == 29);
    check(s.samePackagePackageLongInstanceField == 30);
    check(s.samePackagePackageFloatInstanceField == 31.0f);
    check(s.samePackagePackageDoubleInstanceField == 32.0);
    check(s.samePackagePackageObjectInstanceField == "33");

    check(SamePackage.samePackagePublicBooleanStaticField == true);
    check(SamePackage.samePackagePublicByteStaticField == 34);
    check(SamePackage.samePackagePublicCharStaticField == 35);
    check(SamePackage.samePackagePublicShortStaticField == 36);
    check(SamePackage.samePackagePublicIntStaticField == 37);
    check(SamePackage.samePackagePublicLongStaticField == 38);
    check(SamePackage.samePackagePublicFloatStaticField == 39.0f);
    check(SamePackage.samePackagePublicDoubleStaticField == 40.0);
    check(SamePackage.samePackagePublicObjectStaticField == "41");

    check(SamePackage.samePackageProtectedBooleanStaticField == true);
    check(SamePackage.samePackageProtectedByteStaticField == 42);
    check(SamePackage.samePackageProtectedCharStaticField == 43);
    check(SamePackage.samePackageProtectedShortStaticField == 44);
    check(SamePackage.samePackageProtectedIntStaticField == 45);
    check(SamePackage.samePackageProtectedLongStaticField == 46);
    check(SamePackage.samePackageProtectedFloatStaticField == 47.0f);
    check(SamePackage.samePackageProtectedDoubleStaticField == 48.0);
    check(SamePackage.samePackageProtectedObjectStaticField == "49");

    // check(SamePackage.samePackagePrivateBooleanStaticField == true);
    // check(SamePackage.samePackagePrivateByteStaticField == 50);
    // check(SamePackage.samePackagePrivateCharStaticField == 51);
    // check(SamePackage.samePackagePrivateShortStaticField == 52);
    // check(SamePackage.samePackagePrivateIntStaticField == 53);
    // check(SamePackage.samePackagePrivateLongStaticField == 54);
    // check(SamePackage.samePackagePrivateFloatStaticField == 55.0f);
    // check(SamePackage.samePackagePrivateDoubleStaticField == 56.0);
    // check(SamePackage.samePackagePrivateObjectStaticField == "57");

    check(SamePackage.samePackagePackageBooleanStaticField == true);
    check(SamePackage.samePackagePackageByteStaticField == 58);
    check(SamePackage.samePackagePackageCharStaticField == 59);
    check(SamePackage.samePackagePackageShortStaticField == 60);
    check(SamePackage.samePackagePackageIntStaticField == 61);
    check(SamePackage.samePackagePackageLongStaticField == 62);
    check(SamePackage.samePackagePackageFloatStaticField == 63.0f);
    check(SamePackage.samePackagePackageDoubleStaticField == 64.0);
    check(SamePackage.samePackagePackageObjectStaticField == "65");
  }

  private static boolean compatibleTypes(char srcType, char dstType) {
    switch (dstType) {
      case 'Z':
      case 'C':
      case 'B':
        return srcType == dstType;
      case 'S':
        return srcType == 'B' || srcType == 'S';
      case 'I':
        return srcType == 'B' || srcType == 'C' || srcType == 'S' || srcType == 'I';
      case 'J':
        return srcType == 'B' || srcType == 'C' || srcType == 'S' || srcType == 'I' ||
        srcType == 'J';
      case 'F':
        return srcType == 'B' || srcType == 'C' || srcType == 'S' || srcType == 'I' ||
        srcType == 'J' || srcType == 'F';
      case 'D':
        return srcType == 'B' || srcType == 'C' || srcType == 'S' || srcType == 'I' ||
        srcType == 'J' || srcType == 'F' || srcType == 'D';
      case 'L':
        return true;
      default:
        throw new Error("Unexpected type char " + dstType);
    }
  }

  public void doReflectionTests() {
    String typeChars = "ZBCSIJFDL";
    String fieldNameForTypeChar[] = {
        "Boolean",
        "Byte",
        "Char",
        "Short",
        "Int",
        "Long",
        "Float",
        "Double",
        "Object"
    };

    Main localInst = new Main();
    SamePackage samePkgInst = new SamePackage();
    PublicClass otherPkgInst = new PublicClass();
    Object plainObj = new Object();

    for (int round = 0; round < 3; round++) {
      Object validInst;
      Field[] fields;
      Method[] methods;
      boolean same_package = false;
      boolean protected_class = false;
      switch (round) {
        case 0:
          validInst = new SamePackage();
          fields = SamePackage.class.getDeclaredFields();
          check(fields.length == 72);
          methods = SamePackage.class.getDeclaredMethods();
          check(methods.length == 4);
          same_package = true;
          break;
        case 1:
          validInst = new PublicClass();
          fields = PublicClass.class.getDeclaredFields();
          check(fields.length == 72);
          methods = PublicClass.class.getDeclaredMethods();
          check(methods.length == 4);
          break;
        default:
          validInst = new PublicClass();
          fields = PublicClass.class.getSuperclass().getDeclaredFields();
          check(fields.length == 72);
          methods = PublicClass.class.getSuperclass().getDeclaredMethods();
          check(methods.length == 4);
          protected_class = true;
          break;
      }
      for (Field f : fields) {
        char typeChar = '?';
        for (int i = 0; i < fieldNameForTypeChar.length; i++) {
          if (f.getName().contains(fieldNameForTypeChar[i])) {
            typeChar = typeChars.charAt(i);
            break;
          }
        }
        // Check access or lack of to field.
        Class<?> subClassAccessExceptionClass = null;
        if ((f.getName().contains("Private") ||
            (!same_package && f.getName().contains("Package")) ||
            (!same_package && f.getName().contains("Protected"))) &&
            !(protected_class && f.getName().contains("Public"))) {
          subClassAccessExceptionClass = IllegalAccessException.class;
        }
        Class<?> mainClassAccessExceptionClass = null;
        if ((f.getName().contains("Private") ||
            (!same_package && f.getName().contains("Package")) ||
            (!same_package && f.getName().contains("Protected"))) &&
            !(protected_class && f.getName().contains("Public"))) {
          mainClassAccessExceptionClass = IllegalAccessException.class;
        }

        this.getValue(f, validInst, typeChar, subClassAccessExceptionClass);
        localInst.getValue(f, validInst, typeChar, mainClassAccessExceptionClass);

        // Check things that can get beyond the IllegalAccessException.
        if (subClassAccessExceptionClass == null) {
          // Check NPE.
          Class<?> npeClass = null;
          if (!f.getName().contains("Static")) {
            npeClass = NullPointerException.class;
          }

          this.getValue(f, null, typeChar, npeClass);
          if (mainClassAccessExceptionClass == null) {
            localInst.getValue(f, null, typeChar, npeClass);
          }

          // Check access of wrong field type for valid instance.
          for (int i = 0; i < typeChars.length(); i++) {
            char otherChar = typeChars.charAt(i);
            Class<?> illArgClass = compatibleTypes(typeChar, otherChar) ?
                null : IllegalArgumentException.class;
            this.getValue(f, validInst, otherChar, illArgClass);
            if (mainClassAccessExceptionClass == null) {
              localInst.getValue(f, validInst, otherChar, illArgClass);
            }
          }

          if (!f.getName().contains("Static")) {
            // Wrong object.
            this.getValue(f, plainObj, typeChar, IllegalArgumentException.class);
            if (mainClassAccessExceptionClass == null) {
              localInst.getValue(f, plainObj, typeChar, IllegalArgumentException.class);
            }
          }
        }
      }

      for (Method m : methods) {
        Class<?> subClassAccessExceptionClass = null;
        if (m.getName().contains("Private") ||
            (!same_package && m.getName().contains("Package")) ||
            (!same_package && m.getName().contains("Protected"))) {
          subClassAccessExceptionClass = IllegalAccessException.class;
        }
        this.invoke(m, validInst, subClassAccessExceptionClass);
      }
    }
    System.out.println("good");
  }

  /*
   * [this is a clone of Main.getValue() -- the class issuing the
   * reflection call is significant]
   */
  public Object getValue(Field field, Object obj, char type,
      Class expectedException) {
    Object result = null;
    try {
      switch (type) {
        case 'Z':
          result = field.getBoolean(obj);
          break;
        case 'B':
          result = field.getByte(obj);
          break;
        case 'S':
          result = field.getShort(obj);
          break;
        case 'C':
          result = field.getChar(obj);
          break;
        case 'I':
          result = field.getInt(obj);
          break;
        case 'J':
          result = field.getLong(obj);
          break;
        case 'F':
          result = field.getFloat(obj);
          break;
        case 'D':
          result = field.getDouble(obj);
          break;
        case 'L':
          result = field.get(obj);
          break;
        default:
          throw new RuntimeException("bad type '" + type + "'");
      }

      /* success; expected? */
      if (expectedException != null) {
        System.err.println("ERROR: call succeeded for field " + field +
            " with a read of type '" + type +
            "', was expecting " + expectedException);
        Thread.dumpStack();
      }
    } catch (Exception ex) {
      if (expectedException == null) {
        System.err.println("ERROR: call failed unexpectedly: "
            + ex.getClass());
        ex.printStackTrace();
      } else {
        if (!expectedException.equals(ex.getClass())) {
          System.err.println("ERROR: incorrect exception: wanted "
              + expectedException.getName() + ", got "
              + ex.getClass());
          ex.printStackTrace();
        }
      }
    }

    return result;
  }

  public Object invoke(Method method, Object obj, Class expectedException) {
    Object result = null;
    try {
      result = method.invoke(obj);
      /* success; expected? */
      if (expectedException != null) {
        System.err.println("ERROR: call succeeded for method " + method + "', was expecting " +
                           expectedException);
        Thread.dumpStack();
      }
    } catch (Exception ex) {
      if (expectedException == null) {
        System.err.println("ERROR: call failed unexpectedly: " + ex.getClass());
        ex.printStackTrace();
      } else {
        if (!expectedException.equals(ex.getClass())) {
          System.err.println("ERROR: incorrect exception: wanted " + expectedException.getName() +
                             ", got " + ex.getClass());
          ex.printStackTrace();
        }
      }
    }
    return result;
  }
}


text:
package mil.nga.geopackage.extension.schema.constraints;

import java.sql.SQLException;

import org.junit.Test;

import mil.nga.geopackage.CreateGeoPackageTestCase;
import mil.nga.geopackage.TestSetupTeardown;

/**
 * Test Data Column Constraints from a created database
 *
 * @author osbornb
 */
public class DataColumnConstraintsCreateTest extends CreateGeoPackageTestCase {

	/**
	 * Constructor
	 */
	public DataColumnConstraintsCreateTest() {

	}

	/**
	 * Test reading
	 *
	 * @throws SQLException
	 */
	@Test
	public void testRead() throws SQLException {

		DataColumnConstraintsUtils.testRead(geoPackage,
				TestSetupTeardown.CREATE_DATA_COLUMN_CONSTRAINTS_COUNT);

	}

	/**
	 * Test updating
	 *
	 * @throws SQLException
	 */
	@Test
	public void testUpdate() throws SQLException {

		DataColumnConstraintsUtils.testUpdate(geoPackage);

	}

	/**
	 * Test creating
	 *
	 * @throws SQLException
	 */
	@Test
	public void testCreate() throws SQLException {

		DataColumnConstraintsUtils.testCreate(geoPackage);

	}

	/**
	 * Test deleting
	 *
	 * @throws SQLException
	 */
	@Test
	public void testDelete() throws SQLException {

		DataColumnConstraintsUtils.testDelete(geoPackage);

	}

}

redpajama_set_name: RedPajamaGithub


text:
This project consists of two sections
1. Stock data collection
2. Stock data API

##### Stock Data collection

The stock data collection scripts are stored in scripts folder, there are two programs

1. createTickerFromFile.js

   The createTickerFrom file gets data from '|' delimited data file containing ticker symbol, name and exchange and loads into mongodb document using mongoose.js, the structure of the document is

````
var Ticker = new Schema({
        ticker: {type: String, trim:true, required: true, index: { unique: true, sparse: true } }
        ,name:        String······
        ,exchange:     String
        ,profile:     [Profile]·····
        //,dataTypes              : {type: [DataTypes],required:true}

    });

````
Profile is not implemented yet

2. getStock.js

	The getStock program collects data every minute (default) and stores it in the collection called stock, described below

````
var Stock = new Schema({
     id: Number
     ,t: String
     ,e: String
     ,l: Number
     ,l_fix: Number
     ,l_cur: Number·
     ,s: Number
     ,ltt: String
     ,lt_dts: Date
     ,c: String
     ,c_fix: String
     ,cp: Number
     ,cp_fix: Number
     ,ccol: String
     ,pcls_fix: Number
    });
````

Google financial services api is used for collecting the data

##### Stock data API
###### Standard Error codes and messages
###standard error codes and messages
the following standard error codes can be emitted as output for any end point

| Status      | Message                                           |
|-------------|---------------------------------------------------|
| 200         | Success                                           |
| 400         | Bad request - malformed request                   |
| 401         | not authorized                                    |
| 500         | failure - something went wrong in the code        |

and the following error codes related to data submitted and results returned

| Status      | Message                                           |
|-------------|---------------------------------------------------|
| 1000        | incorrect input - one or more fields missing      |
| 1001        | no result found                                   |
| 1002        | more than one result found - expecting just one   |
| 1003        | one result found - expecting more than one        |
| 1004        | one result found - expecting no result            |

The stock data api is a express server supporting the following end points

###### Root / [Index]
| parameter   | value                                                                |
|-------------| ---------------------------------------------------------------------|
| end point   | /                                              |
| verb        | GET                                                                 |

Just displays the success message, To be IMPLEMENTED

###### Tickers

| parameter   | value                                                                |
|-------------| ---------------------------------------------------------------------|
| end point   | /ticker                                               |
| verb        | GET                                                                 |

Displays the ticker from ````Tickers```` collections above

###### Data
| parameter   | value                                                                |
|-------------| ---------------------------------------------------------------------|
| end point   | /data?ticker=""&limit=""  // e.g AAPL                                             |
| verb        | GET                                                                 |

Displays all the stock data for a given ticker ordered by date-timestamp desc

The limit parameter limits the number of rows returned

example : /data?ticker=AAPL&limit=10

If the URL query syntax is incorrect you will get ````{
status: 1000,
message: "incorrect input - one or more fields missing"
}````

if no data found you will get ````{
status: 1001,
message: "no result found"
}````

### Installation instructions

to set up the framework and library

1. git clone git@github.com:GOPINATH-GS4/stock.git
2. npm install
3. Install mongodd, please refer to
[Mongodb Installation](http://docs.mongodb.org/manual/installation/ "Link to mongodb install document")

##### Creating Ticker master data

create data before starting the getStock.js program, an example file called ````dfile```` is provided under scripts directory

node createTickerFromFile.js dfile

#### Running stock data collection

nohup node getStock.js &

#### Starting the server

Under the root folder execute

. ./.env.development

start mongodb

node server.js

All data will be stored into a database called stock


text:
package net.alloyggp.tournament.internal;

import net.alloyggp.escaperope.rope.Rope;
import net.alloyggp.escaperope.rope.StringRope;
import net.alloyggp.escaperope.rope.ropify.Weaver;
import net.alloyggp.tournament.api.TScore;

public class SimpleScore implements TScore {
    private final int score;

    public SimpleScore(int score) {
        this.score = score;
    }

    public static SimpleScore create(int score) {
        return new SimpleScore(score);
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + score;
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        SimpleScore other = (SimpleScore) obj;
        if (score != other.score) {
            return false;
        }
        return true;
    }

    @Override
    public int compareTo(TScore other) {
        if (!(other instanceof SimpleScore)) {
            throw new IllegalArgumentException();
        }
        return Integer.compare(score, ((SimpleScore)other).score);
    }

    @Override
    public String toString() {
        return getDescription();
    }

    @Override
    public String getDescription() {
        return Integer.toString(score);
    }

    public static final Weaver<TScore> WEAVER = new Weaver<TScore>() {
        @Override
        public Rope toRope(TScore object) {
            SimpleScore score = (SimpleScore) object;
            return StringRope.create(Integer.toString(score.score));
        }

        @Override
        public TScore fromRope(Rope rope) {
            return create(Integer.parseInt(rope.asString()));
        }
    };
}


text:
package profiles

import (
	"fmt"
	"log"
	"os"
	"strconv"
	"sync"
	"sync/atomic"
	"time"

	"gopkg.in/mgo.v2"
	"gopkg.in/mgo.v2/bson"
)

/*
	basic insert only profile, insert a doc of 400 bytes
*/

type Person struct {
	Name    int64
	UID     bson.ObjectId `bson:"_id,omitempty"`
	Group   int
	Payload string
}

var Payload [40]int
var Payload1 [120]byte
var Payload2 [120]byte
var Payload3 [120]byte
var Payload4 [120]byte
var Payload5 [120]byte
var Payload6 [120]byte

var stageInsert bool

type insertProfile struct {
	UID int64

	indexTTL time.Duration

	initProfile sync.Once

	session *mgo.Session
}

var _insertProfile insertProfile
var _payload_string_lens int

// func Int2ObjId(i int64) string {
// 	// return string represenation of UID
// }

func (i insertProfile) SendNext(s *mgo.Session, worker_id int) error {
	var err error
	c := s.DB(getDBName(default_db_name_prefix)).C(getCollectionName(default_col_name_prefix))

	_u := atomic.AddInt64(&_insertProfile.UID, 1) // to make this unique
	_g := rands[worker_id].Int()

	doc := bson.M{
		"_id":   _u,
		"group": _g,
		//"group":   rands[worker_id].Int(),
		"payload": randomString(_payload_string_lens, worker_id),
	}

	if stageInsert {
		var dbName, colName string

		for i := 1; i <= _multi_db; i++ { // start from 1
			dbName = fmt.Sprint(default_db_name_prefix, i)

			for j := 1; j <= _multi_col; j++ {
				colName = fmt.Sprint(default_col_name_prefix, j)

				c = s.DB(dbName).C(colName)

				if _profile_use_legacy_write {
					err = c.Insert(doc)
				} else {
					var results interface{}

					err = c.Database.Run(bson.D{{"insert", c.Name},
						{"documents", []bson.M{doc}}}, results)
				}

				panicOnError(err)
			}
		}

	} else {
		if _profile_use_legacy_write {
			err = c.Insert(doc)
		} else {
			var results interface{}

			err = c.Database.Run(bson.D{{"insert", c.Name},
				{"documents", []bson.M{doc}}}, results)
		}

		// panicOnError(err)
	}
	return err // never come here when there is error
}

func InitSimpleTest(session *mgo.Session, _initdb bool) {
	log.Println("Initialize simple DB. with initdb flag ", _initdb)

	_initdb = true

	if !_initdb {
		panic("flag is false")
	}

	// drop the colelction here  TODO?  FIXME:
	if _initdb {
		log.Println(". Init DB, drop collections")
		session.DB(_db_name).C("people").DropCollection()
		// may drop DB here as well TODO:
	} // this will be moved to each profile. FIXME:

	var dbName, colName string

	indexGroup := mgo.Index{
		Key:         []string{"group"},
		ExpireAfter: _cappedCollInsertProfile.indexTTL,
	}

	for i := 1; i <= _multi_db; i++ {
		dbName = fmt.Sprint(default_db_name_prefix, i)

		for j := 1; j <= _multi_col; j++ {
			colName = fmt.Sprint(default_col_name_prefix, j)
			collection := session.DB(dbName).C(colName)

			if _initdb {
				fmt.Println("Drop collection ", dbName+"."+colName)
				collection.DropCollection()
				// may drop DB here as well TODO:
			} // this will be moved to each profile. FIXME:

			fmt.Println("Create index for ", dbName+"."+colName)
			err := collection.EnsureIndex(indexGroup)
			if err != nil {
				panic(err)
			}
		}
	}
}

func (i insertProfile) SetupTest(s *mgo.Session, _initdb bool) error {
	i.session = s

	f := func() {
		InitSimpleTest(s, _initdb)
	}

	_insertProfile.initProfile.Do(f)
	return nil
}

func (i insertProfile) CsvString(total_time float64) string {
	return ""
}

func (i insertProfile) CsvHeader() string {
	return ""
}

func init() {
	// fmt.Println("Init INSERT profile")

	atomic.StoreInt64(&_insertProfile.UID, -1) // UID starts with 1

	registerProfile("INSERT", func() Profile {
		return Profile(_insertProfile) // use the same instance
	})

	_insertProfile.indexTTL = time.Duration(getOSEnvFlagInt("HT_INDEX_TTL", 0)) * time.Second

	s := os.Getenv("HT_STAGE_INSERT")
	if s == "" {
		stageInsert = false
	} else {
		stageInsert = true
	}

	s = os.Getenv("HT_INSERT_PAYLOAD_STRING_LENGTH")
	if s == "" {
		_payload_string_lens = 256
	} else {
		l, err := strconv.ParseInt(s, 10, 64)

		if err != nil {
			log.Fatalln("Cannot parse environment variable HT_INSERT_PAYLOAD_STRING_LENGTH, got ", s, " expecting an integer")
		}
		_payload_string_lens = int(l)
	}
}


text:
#ifndef _ASM_S390_SETUP_H
#define _ASM_S390_SETUP_H

#include <uapi/asm/setup.h>

#define PARMAREA		0x10400

#ifndef __ASSEMBLY__

#include <asm/lowcore.h>
#include <asm/types.h>

#define IPL_DEVICE        (*(unsigned long *)  (0x10400))
#define INITRD_START      (*(unsigned long *)  (0x10408))
#define INITRD_SIZE       (*(unsigned long *)  (0x10410))
#define OLDMEM_BASE	  (*(unsigned long *)  (0x10418))
#define OLDMEM_SIZE	  (*(unsigned long *)  (0x10420))
#define COMMAND_LINE      ((char *)            (0x10480))

extern int memory_end_set;
extern unsigned long memory_end;
extern unsigned long max_physmem_end;

extern void detect_memory_memblock(void);

/*
 * Machine features detected in head.S
 */

#define MACHINE_FLAG_VM		(1UL << 0)
#define MACHINE_FLAG_IEEE	(1UL << 1)
#define MACHINE_FLAG_CSP	(1UL << 2)
#define MACHINE_FLAG_MVPG	(1UL << 3)
#define MACHINE_FLAG_DIAG44	(1UL << 4)
#define MACHINE_FLAG_IDTE	(1UL << 5)
#define MACHINE_FLAG_DIAG9C	(1UL << 6)
#define MACHINE_FLAG_KVM	(1UL << 8)
#define MACHINE_FLAG_ESOP	(1UL << 9)
#define MACHINE_FLAG_EDAT1	(1UL << 10)
#define MACHINE_FLAG_EDAT2	(1UL << 11)
#define MACHINE_FLAG_LPAR	(1UL << 12)
#define MACHINE_FLAG_LPP	(1UL << 13)
#define MACHINE_FLAG_TOPOLOGY	(1UL << 14)
#define MACHINE_FLAG_TE		(1UL << 15)
#define MACHINE_FLAG_TLB_LC	(1UL << 17)
#define MACHINE_FLAG_VX		(1UL << 18)
#define MACHINE_FLAG_CAD	(1UL << 19)

#define MACHINE_IS_VM		(S390_lowcore.machine_flags & MACHINE_FLAG_VM)
#define MACHINE_IS_KVM		(S390_lowcore.machine_flags & MACHINE_FLAG_KVM)
#define MACHINE_IS_LPAR		(S390_lowcore.machine_flags & MACHINE_FLAG_LPAR)

#define MACHINE_HAS_DIAG9C	(S390_lowcore.machine_flags & MACHINE_FLAG_DIAG9C)
#define MACHINE_HAS_ESOP	(S390_lowcore.machine_flags & MACHINE_FLAG_ESOP)
#define MACHINE_HAS_PFMF	MACHINE_HAS_EDAT1
#define MACHINE_HAS_HPAGE	MACHINE_HAS_EDAT1

#define MACHINE_HAS_IDTE	(S390_lowcore.machine_flags & MACHINE_FLAG_IDTE)
#define MACHINE_HAS_DIAG44	(S390_lowcore.machine_flags & MACHINE_FLAG_DIAG44)
#define MACHINE_HAS_EDAT1	(S390_lowcore.machine_flags & MACHINE_FLAG_EDAT1)
#define MACHINE_HAS_EDAT2	(S390_lowcore.machine_flags & MACHINE_FLAG_EDAT2)
#define MACHINE_HAS_LPP		(S390_lowcore.machine_flags & MACHINE_FLAG_LPP)
#define MACHINE_HAS_TOPOLOGY	(S390_lowcore.machine_flags & MACHINE_FLAG_TOPOLOGY)
#define MACHINE_HAS_TE		(S390_lowcore.machine_flags & MACHINE_FLAG_TE)
#define MACHINE_HAS_TLB_LC	(S390_lowcore.machine_flags & MACHINE_FLAG_TLB_LC)
#define MACHINE_HAS_VX		(S390_lowcore.machine_flags & MACHINE_FLAG_VX)
#define MACHINE_HAS_CAD		(S390_lowcore.machine_flags & MACHINE_FLAG_CAD)

/*
 * Console mode. Override with conmode=
 */
extern unsigned int console_mode;
extern unsigned int console_devno;
extern unsigned int console_irq;

extern char vmhalt_cmd[];
extern char vmpoff_cmd[];

#define CONSOLE_IS_UNDEFINED	(console_mode == 0)
#define CONSOLE_IS_SCLP		(console_mode == 1)
#define CONSOLE_IS_3215		(console_mode == 2)
#define CONSOLE_IS_3270		(console_mode == 3)
#define SET_CONSOLE_SCLP	do { console_mode = 1; } while (0)
#define SET_CONSOLE_3215	do { console_mode = 2; } while (0)
#define SET_CONSOLE_3270	do { console_mode = 3; } while (0)

#define NSS_NAME_SIZE	8
extern char kernel_nss_name[];

#ifdef CONFIG_PFAULT
extern int pfault_init(void);
extern void pfault_fini(void);
#else /* CONFIG_PFAULT */
#define pfault_init()		({-1;})
#define pfault_fini()		do { } while (0)
#endif /* CONFIG_PFAULT */

extern void cmma_init(void);

extern void (*_machine_restart)(char *command);
extern void (*_machine_halt)(void);
extern void (*_machine_power_off)(void);

#else /* __ASSEMBLY__ */

#define IPL_DEVICE        0x10400
#define INITRD_START      0x10408
#define INITRD_SIZE       0x10410
#define OLDMEM_BASE	  0x10418
#define OLDMEM_SIZE	  0x10420
#define COMMAND_LINE      0x10480

#endif /* __ASSEMBLY__ */
#endif /* _ASM_S390_SETUP_H */


text:
package edu.rpi.tw.string;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URISyntaxException;

import edu.rpi.tw.data.rdf.sesame.vocabulary.TetherlessWorld;

public class WikimediaURIMapper extends URIMapper {

   protected String prefix;

   /**
    *
    * @param topic
    * @return
    */
   public static String map(String topic) {
      return WikimediaURIMapper.map(topic, true);
   }

   /**
    * @param topic
    * @param capitalize
    * @return
    */
   public static String map(String topic, boolean capitalize) {  // TODO: reconcile with xsl version
      topic = topic.replace(" ","_");   // space
      topic = topic.replace(",","-2C"); // comma
      topic = topic.replace("'","-27"); // apostrophe
      topic = topic.replace(":","-3A"); // colon
      topic = topic.replace("(","-28");
      topic = topic.replace(")","-29");
      topic = topic.replace("|","_");   // pipe
      topic = topic.replace("@","-40");
      topic = topic.replace("&","-26"); // ampersand
      topic = topic.replace("`","-60"); // back tick
      topic = topic.replace("\\?","-3F"); // question mark
      //topic = topic.replace("�","-E2-80-98");
      topic = topic.replace("%", "-25");
      topic = topic.replace("\\W$", "");
      topic = topic.replace("\\W", "_");
      topic = topic.replace("/", "");
      // Capitalize first character of local name
      if( capitalize && topic.length() > 1 ) {
         //System.out.println(topic + " " + topic.substring(0,1).toUpperCase() + topic.substring(1,topic.length()-1));
         topic = topic.substring(0,1).toUpperCase() + topic.substring(1,topic.length());
      }
      return topic;
   }
   // TODO: | char is not a valid URI character
   public static URI name(String baseURI, String localName) {
      return asURI(baseURI + WikimediaURIMapper.map(localName));
   }

   public static final String USAGE = "usage: WikimediaURIMapper {- baseURI prefix | [localName]* }";

   /**
    * - baseURI prefix
    * Read local names from stdin using the given baseURI and prefix
    *
    * [localName]*
    * Provide a full URI for given localNames within the RL namespace.
    *
    * @param args
    */
   public static void main(String args[]) {
      if( args.length < 1 ) {
         System.err.println(USAGE);
         System.exit(1);
      }

      if( "-".equalsIgnoreCase(args[0]) ) {
         String baseURI = args.length > 1 ? args[1] : "";
         String prefix  = args.length > 2 ? args[2]+":" : ":";
         if( baseURI.length() > 0 ) {
            System.out.println("@prefix "+prefix+" <"+baseURI+"> .\n");
         }
         BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
         try {
            String identifyingLabel = null;
            while( (identifyingLabel = br.readLine()) != null ) {
               System.out.println(prefix+map(identifyingLabel)+"\n"+
                                  "   p:idlabel \""+identifyingLabel+"\";\n"+
                                  "."
               );
            }
         } catch (IOException e1) {
            e1.printStackTrace();
         }
      } else {
         for( int i = 0; i < args.length; i++ ) {
            URI itemURI = null;
            try {
               itemURI = new URI(TetherlessWorld.BASE_URI+map(args[i]));
            } catch (URISyntaxException e) {
               e.printStackTrace(System.err);
            }
            System.out.println(map(args[i]));
         }
      }
   }
}


text:
<?php

namespace Symfony\Component\DependencyInjection\Tests;

use PHPUnit\Framework\TestCase;
use Symfony\Component\DependencyInjection\Container;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\EnvVarProcessor;

class EnvVarProcessorTest extends TestCase
{
    const TEST_CONST = 'test';

    /**
     * @dataProvider validStrings
     */
    public function testGetEnvString($value, $processed)
    {
        $container = new ContainerBuilder();
        $container->setParameter('env(foo)', $value);
        $container->compile();

        $processor = new EnvVarProcessor($container);

        $result = $processor->getEnv('string', 'foo', function () {
            $this->fail('Should not be called');
        });

        $this->assertSame($processed, $result);
    }

    public function validStrings()
    {
        return [
            ['hello', 'hello'],
            ['true', 'true'],
            ['false', 'false'],
            ['null', 'null'],
            ['1', '1'],
            ['0', '0'],
            ['1.1', '1.1'],
            ['1e1', '1e1'],
        ];
    }

    /**
     * @dataProvider validBools
     */
    public function testGetEnvBool($value, $processed)
    {
        $processor = new EnvVarProcessor(new Container());

        $result = $processor->getEnv('bool', 'foo', function ($name) use ($value) {
            $this->assertSame('foo', $name);

            return $value;
        });

        $this->assertSame($processed, $result);
    }

    public function validBools()
    {
        return [
            ['true', true],
            ['false', false],
            ['null', false],
            ['1', true],
            ['0', false],
            ['1.1', true],
            ['1e1', true],
        ];
    }

    /**
     * @dataProvider validInts
     */
    public function testGetEnvInt($value, $processed)
    {
        $processor = new EnvVarProcessor(new Container());

        $result = $processor->getEnv('int', 'foo', function ($name) use ($value) {
            $this->assertSame('foo', $name);

            return $value;
        });

        $this->assertSame($processed, $result);
    }

    public function validInts()
    {
        return [
            ['1', 1],
            ['1.1', 1],
            ['1e1', 10],
        ];
    }

    /**
     * @dataProvider invalidInts
     */
    public function testGetEnvIntInvalid($value)
    {
        $this->expectException('Symfony\Component\DependencyInjection\Exception\RuntimeException');
        $this->expectExceptionMessage('Non-numeric env var');
        $processor = new EnvVarProcessor(new Container());

        $processor->getEnv('int', 'foo', function ($name) use ($value) {
            $this->assertSame('foo', $name);

            return $value;
        });
    }

    public function invalidInts()
    {
        return [
            ['foo'],
            ['true'],
            ['null'],
        ];
    }

    /**
     * @dataProvider validFloats
     */
    public function testGetEnvFloat($value, $processed)
    {
        $processor = new EnvVarProcessor(new Container());

        $result = $processor->getEnv('float', 'foo', function ($name) use ($value) {
            $this->assertSame('foo', $name);

            return $value;
        });

        $this->assertSame($processed, $result);
    }

    public function validFloats()
    {
        return [
            ['1', 1.0],
            ['1.1', 1.1],
            ['1e1', 10.0],
        ];
    }

    /**
     * @dataProvider invalidFloats
     */
    public function testGetEnvFloatInvalid($value)
    {
        $this->expectException('Symfony\Component\DependencyInjection\Exception\RuntimeException');
        $this->expectExceptionMessage('Non-numeric env var');
        $processor = new EnvVarProcessor(new Container());

        $processor->getEnv('float', 'foo', function ($name) use ($value) {
            $this->assertSame('foo', $name);

            return $value;
        });
    }

    public function invalidFloats()
    {
        return [
            ['foo'],
            ['true'],
            ['null'],
        ];
    }

    /**
     * @dataProvider validConsts
     */
    public function testGetEnvConst($value, $processed)
    {
        $processor = new EnvVarProcessor(new Container());

        $result = $processor->getEnv('const', 'foo', function ($name) use ($value) {
            $this->assertSame('foo', $name);

            return $value;
        });

        $this->assertSame($processed, $result);
    }

    public function validConsts()
    {
        return [
            ['Symfony\Component\DependencyInjection\Tests\EnvVarProcessorTest::TEST_CONST', self::TEST_CONST],
            ['E_ERROR', E_ERROR],
        ];
    }

    /**
     * @dataProvider invalidConsts
     */
    public function testGetEnvConstInvalid($value)
    {
        $this->expectException('Symfony\Component\DependencyInjection\Exception\RuntimeException');
        $this->expectExceptionMessage('undefined constant');
        $processor = new EnvVarProcessor(new Container());

        $processor->getEnv('const', 'foo', function ($name) use ($value) {
            $this->assertSame('foo', $name);

            return $value;
        });
    }

    public function invalidConsts()
    {
        return [
            ['Symfony\Component\DependencyInjection\Tests\EnvVarProcessorTest::UNDEFINED_CONST'],
            ['UNDEFINED_CONST'],
        ];
    }

    public function testGetEnvBase64()
    {
        $processor = new EnvVarProcessor(new Container());

        $result = $processor->getEnv('base64', 'foo', function ($name) {
            $this->assertSame('foo', $name);

            return base64_encode('hello');
        });

        $this->assertSame('hello', $result);
    }

    public function testGetEnvTrim()
    {
        $processor = new EnvVarProcessor(new Container());

        $result = $processor->getEnv('trim', 'foo', function ($name) {
            $this->assertSame('foo', $name);

            return " hello\n";
        });

        $this->assertSame('hello', $result);
    }

    /**
     * @dataProvider validJson
     */
    public function testGetEnvJson($value, $processed)
    {
        $processor = new EnvVarProcessor(new Container());

        $result = $processor->getEnv('json', 'foo', function ($name) use ($value) {
            $this->assertSame('foo', $name);

            return $value;
        });

        $this->assertSame($processed, $result);
    }

    public function validJson()
    {
        return [
            ['[1]', [1]],
            ['{"key": "value"}', ['key' => 'value']],
            [null, null],
        ];
    }

    public function testGetEnvInvalidJson()
    {
        $this->expectException('Symfony\Component\DependencyInjection\Exception\RuntimeException');
        $this->expectExceptionMessage('Syntax error');
        $processor = new EnvVarProcessor(new Container());

        $processor->getEnv('json', 'foo', function ($name) {
            $this->assertSame('foo', $name);

            return 'invalid_json';
        });
    }

    /**
     * @dataProvider otherJsonValues
     */
    public function testGetEnvJsonOther($value)
    {
        $this->expectException('Symfony\Component\DependencyInjection\Exception\RuntimeException');
        $this->expectExceptionMessage('Invalid JSON env var');
        $processor = new EnvVarProcessor(new Container());

        $processor->getEnv('json', 'foo', function ($name) use ($value) {
            $this->assertSame('foo', $name);

            return json_encode($value);
        });
    }

    public function otherJsonValues()
    {
        return [
            [1],
            [1.1],
            [true],
            [false],
            ['foo'],
        ];
    }

    public function testGetEnvUnknown()
    {
        $this->expectException('Symfony\Component\DependencyInjection\Exception\RuntimeException');
        $this->expectExceptionMessage('Unsupported env var prefix');
        $processor = new EnvVarProcessor(new Container());

        $processor->getEnv('unknown', 'foo', function ($name) {
            $this->assertSame('foo', $name);

            return 'foo';
        });
    }

    public function testGetEnvKeyInvalidKey()
    {
        $this->expectException('Symfony\Component\DependencyInjection\Exception\RuntimeException');
        $this->expectExceptionMessage('Invalid env "key:foo": a key specifier should be provided.');
        $processor = new EnvVarProcessor(new Container());

        $processor->getEnv('key', 'foo', function ($name) {
            $this->fail('Should not get here');
        });
    }

    /**
     * @dataProvider noArrayValues
     */
    public function testGetEnvKeyNoArrayResult($value)
    {
        $this->expectException('Symfony\Component\DependencyInjection\Exception\RuntimeException');
        $this->expectExceptionMessage('Resolved value of "foo" did not result in an array value.');
        $processor = new EnvVarProcessor(new Container());

        $processor->getEnv('key', 'index:foo', function ($name) use ($value) {
            $this->assertSame('foo', $name);

            return $value;
        });
    }

    public function noArrayValues()
    {
        return [
            [null],
            ['string'],
            [1],
            [true],
        ];
    }

    /**
     * @dataProvider invalidArrayValues
     */
    public function testGetEnvKeyArrayKeyNotFound($value)
    {
        $this->expectException('Symfony\Component\DependencyInjection\Exception\EnvNotFoundException');
        $this->expectExceptionMessage('Key "index" not found in');
        $processor = new EnvVarProcessor(new Container());

        $processor->getEnv('key', 'index:foo', function ($name) use ($value) {
            $this->assertSame('foo', $name);

            return $value;
        });
    }

    public function invalidArrayValues()
    {
        return [
            [[]],
            [['index2' => 'value']],
            [['index', 'index2']],
        ];
    }

    /**
     * @dataProvider arrayValues
     */
    public function testGetEnvKey($value)
    {
        $processor = new EnvVarProcessor(new Container());

        $this->assertSame($value['index'], $processor->getEnv('key', 'index:foo', function ($name) use ($value) {
            $this->assertSame('foo', $name);

            return $value;
        }));
    }

    public function arrayValues()
    {
        return [
            [['index' => 'password']],
            [['index' => 'true']],
            [['index' => false]],
            [['index' => '1']],
            [['index' => 1]],
            [['index' => '1.1']],
            [['index' => 1.1]],
            [['index' => []]],
            [['index' => ['val1', 'val2']]],
        ];
    }

    public function testGetEnvKeyChained()
    {
        $processor = new EnvVarProcessor(new Container());

        $this->assertSame('password', $processor->getEnv('key', 'index:file:foo', function ($name) {
            $this->assertSame('file:foo', $name);

            return [
                'index' => 'password',
            ];
        }));
    }

    /**
     * @dataProvider validNullables
     */
    public function testGetEnvNullable($value, $processed)
    {
        $processor = new EnvVarProcessor(new Container());
        $result = $processor->getEnv('default', ':foo', function ($name) use ($value) {
            $this->assertSame('foo', $name);

            return $value;
        });
        $this->assertSame($processed, $result);
    }

    public function validNullables()
    {
        return [
            ['hello', 'hello'],
            ['', null],
            ['null', 'null'],
            ['Null', 'Null'],
            ['NULL', 'NULL'],
         ];
    }

    public function testRequireMissingFile()
    {
        $this->expectException('Symfony\Component\DependencyInjection\Exception\EnvNotFoundException');
        $this->expectExceptionMessage('missing-file');
        $processor = new EnvVarProcessor(new Container());

        $processor->getEnv('require', '/missing-file', function ($name) {
            return $name;
        });
    }

    public function testRequireFile()
    {
        $path = __DIR__.'/Fixtures/php/return_foo_string.php';

        $processor = new EnvVarProcessor(new Container());

        $result = $processor->getEnv('require', $path, function ($name) use ($path) {
            $this->assertSame($path, $name);

            return $path;
        });

        $this->assertEquals('foo', $result);
    }

    /**
     * @dataProvider validCsv
     */
    public function testGetEnvCsv($value, $processed)
    {
        $processor = new EnvVarProcessor(new Container());

        $result = $processor->getEnv('csv', 'foo', function ($name) use ($value) {
            $this->assertSame('foo', $name);

            return $value;
        });

        $this->assertSame($processed, $result);
    }

    public function validCsv()
    {
        $complex = <<<'CSV'
,"""","foo""","\""",\,foo\
CSV;

        return [
            ['', [null]],
            [',', ['', '']],
            ['1', ['1']],
            ['1,2," 3 "', ['1', '2', ' 3 ']],
            ['\\,\\\\', ['\\', '\\\\']],
            [$complex, \PHP_VERSION_ID >= 70400 ? ['', '"', 'foo"', '\\"', '\\', 'foo\\'] : ['', '"', 'foo"', '\\"",\\,foo\\']],
            [null, null],
        ];
    }
}


text:
package io.leopard.data.dfs.service;

import java.io.IOException;

public interface DfsDao {

	void write(String filename, byte[] data, long uid) throws IOException;

	byte[] read(String filename) throws IOException;

}


text:
package fleet

import (
	"bytes"
	"sync"
	"testing"
	"text/tabwriter"

	"github.com/coreos/fleet/machine"
	"github.com/coreos/fleet/schema"
)

func TestListUnits(t *testing.T) {
	t.Parallel()

	testUnitStates := []*schema.UnitState{
		&schema.UnitState{
			Name:               "deis-controller.service",
			MachineID:          "123456",
			SystemdLoadState:   "loaded",
			SystemdActiveState: "active",
			SystemdSubState:    "running",
			Hash:               "abcd",
		},
		&schema.UnitState{
			Name:               "deis-router@1.service",
			MachineID:          "654321",
			SystemdLoadState:   "loaded",
			SystemdActiveState: "active",
			SystemdSubState:    "running",
			Hash:               "dcba",
		},
	}

	testMachines := []machine.MachineState{
		machine.MachineState{
			ID:       "123456",
			PublicIP: "1.1.1.1",
			Metadata: nil,
			Version:  "",
		},
		machine.MachineState{
			ID:       "654321",
			PublicIP: "2.2.2.2",
			Metadata: nil,
			Version:  "",
		},
	}

	testWriter := bytes.Buffer{}
	testTabWriter := new(tabwriter.Writer)
	testTabWriter.Init(&testWriter, 0, 8, 1, '\t', 0)

	c := &FleetClient{Fleet: &stubFleetClient{testUnitStates: testUnitStates,
		testMachineStates: testMachines, unitStatesMutex: &sync.Mutex{}},
		out: testTabWriter}

	err := c.ListUnits()

	if err != nil {
		t.Fatal(err)
	}

	expected := `UNIT			MACHINE			LOAD	ACTIVE	SUB
deis-controller.service	123456.../1.1.1.1	loaded	active	running
deis-router@1.service	654321.../2.2.2.2	loaded	active	running
`

	actual := testWriter.String()

	if expected != actual {
		t.Errorf("Expected '%s', Got '%s'", expected, actual)
	}
}


text:
var path = require('path');
var constants = require('../../../tasks/util/constants');

var DEFAULT_FORMAT = 'png';

/**
 * Return paths to baseline, test-image and diff images for a given mock name.
 *
 * @param {string} mockName
 * @param {string} format
 * @return {object}
 *      baseline
 *      test
 *      diff
 */
module.exports = function getImagePaths(mockName, format) {
    format = format || DEFAULT_FORMAT;

    return {
        baseline: join(constants.pathToTestImageBaselines, mockName, format),
        test: join(constants.pathToTestImages, mockName, format),
        diff: join(constants.pathToTestImagesDiff, 'diff-' + mockName, format)
    };
};

function join(basePath, fileName, format) {
    return path.join(basePath, fileName) + '.' + format;
}


text:
import { expect } from 'chai';
import _ from 'lodash';

import yourCode from '../src/tdd/yourCode';

describe('TDD lunch and learn function', () => {
    it('should return an array', () => {
        const results = yourCode();
        expect(_.isArray(results)).to.equal(true);
    });
});


text:
<?php

namespace backend\models;

use dektrium\user\models\User as baseUser;

class User extends baseUser{

}


text:
import time
import wx

from enable.savage.svg.backends.wx import renderer
from traitsui.wx.constants import WindowColor

class RenderPanel(wx.PyPanel):
    def __init__(self, parent, document=None):
        wx.PyPanel.__init__(self, parent)
        self.lastRender = None
        self.document = document
        self.zoom_x = 100
        self.zoom_y = 100
        self.offset = wx.Point(0,0)
        self.SetBackgroundStyle(wx.BG_STYLE_CUSTOM)
        self.Bind(wx.EVT_PAINT, self.OnPaint)
        self.Bind(wx.EVT_MOUSEWHEEL, self.OnWheel)
        self.Bind(wx.EVT_MOTION, self.OnMotion)
        self.Bind(wx.EVT_LEFT_DOWN, self.OnLeftDown)
        self.Bind(wx.EVT_LEFT_UP, self.OnLeftUp)
        self.Bind(wx.EVT_MIDDLE_UP, self.OnMiddleClick)
        self.Bind(wx.EVT_ENTER_WINDOW, self.OnEnterWindow)
        self.Bind(wx.EVT_LEAVE_WINDOW, self.OnLeaveWindow)

    def OnPaint(self, evt):
        start = time.time()
        dc = wx.BufferedPaintDC(self)
        dc.SetBackground(wx.Brush(self.GetBackgroundColour()))
        dc.Clear()
        if not self.document:
            dc.DrawText("No Document", 20, 20)
            return
        gc = wx.GraphicsContext_Create(dc)

        gc.Translate(*self.offset)
        gc.Scale(float(self.zoom_x) / 100, float(self.zoom_y) / 100)

        self.document.render(gc)
        self.lastRender = time.time() - start

    def GetBackgroundColour(self):
        return WindowColor

    def GetBestSize(self):
        if not self.document:
            return (-1,-1)

        return wx.Size(*(self.document.getSize()))

    def OnWheel(self, evt):
        delta = (evt.m_wheelRotation / evt.m_wheelDelta) * 10
        self.zoom_x += delta
        self.zoom_y += delta
        self.Refresh()

    def OnLeftDown(self, evt):
        self.SetCursor(wx.StockCursor(wx.CURSOR_HAND))
        self.CaptureMouse()
        self.offsetFrom = evt.GetPosition()
        evt.Skip()

    def OnLeftUp(self, evt):
        if self.HasCapture():
            self.ReleaseMouse()
        self.SetCursor(wx.NullCursor)
        evt.Skip()

    def OnMotion(self, evt):
        if not self.HasCapture():
            return
        self.offset += (evt.GetPosition() - self.offsetFrom)
        self.offsetFrom = evt.GetPosition()
        self.Refresh()

    def OnMiddleClick(self, evt):
        self.offset = wx.Point(0,0)
        self.zoom_x = 100
        self.zoom_y = 100
        self.Refresh()

    def OnEnterWindow(self, evt):
        pass

    def OnLeaveWindow(self, evt):
        pass


text:
package main

import (
	"bufio"
	"fmt"
	"io/ioutil"
	"os"
	"os/exec"
	"path/filepath"
	"strings"
	"time"

	"github.com/docker/docker/pkg/integration/checker"
	"github.com/docker/docker/pkg/mount"
	"github.com/go-check/check"
	"github.com/kr/pty"
)

// #6509
func (s *DockerSuite) TestRunRedirectStdout(c *check.C) {
	checkRedirect := func(command string) {
		_, tty, err := pty.Open()
		if err != nil {
			c.Fatalf("Could not open pty: %v", err)
		}
		cmd := exec.Command("sh", "-c", command)
		cmd.Stdin = tty
		cmd.Stdout = tty
		cmd.Stderr = tty
		if err := cmd.Start(); err != nil {
			c.Fatalf("start err: %v", err)
		}
		ch := make(chan error)
		go func() {
			ch <- cmd.Wait()
			close(ch)
		}()

		select {
		case <-time.After(10 * time.Second):
			c.Fatal("command timeout")
		case err := <-ch:
			if err != nil {
				c.Fatalf("wait err=%v", err)
			}
		}
	}

	checkRedirect(dockerBinary + " run -i busybox cat /etc/passwd | grep -q root")
	checkRedirect(dockerBinary + " run busybox cat /etc/passwd | grep -q root")
}

// Test recursive bind mount works by default
func (s *DockerSuite) TestRunWithVolumesIsRecursive(c *check.C) {
	tmpDir, err := ioutil.TempDir("", "docker_recursive_mount_test")
	if err != nil {
		c.Fatal(err)
	}

	defer os.RemoveAll(tmpDir)

	// Create a temporary tmpfs mount.
	tmpfsDir := filepath.Join(tmpDir, "tmpfs")
	if err := os.MkdirAll(tmpfsDir, 0777); err != nil {
		c.Fatalf("failed to mkdir at %s - %s", tmpfsDir, err)
	}
	if err := mount.Mount("tmpfs", tmpfsDir, "tmpfs", ""); err != nil {
		c.Fatalf("failed to create a tmpfs mount at %s - %s", tmpfsDir, err)
	}

	f, err := ioutil.TempFile(tmpfsDir, "touch-me")
	if err != nil {
		c.Fatal(err)
	}
	defer f.Close()

	runCmd := exec.Command(dockerBinary, "run", "--name", "test-data", "--volume", fmt.Sprintf("%s:/tmp:ro", tmpDir), "busybox:latest", "ls", "/tmp/tmpfs")
	out, stderr, exitCode, err := runCommandWithStdoutStderr(runCmd)
	if err != nil && exitCode != 0 {
		c.Fatal(out, stderr, err)
	}
	if !strings.Contains(out, filepath.Base(f.Name())) {
		c.Fatal("Recursive bind mount test failed. Expected file not found")
	}
}

func (s *DockerSuite) TestRunDeviceDirectory(c *check.C) {
	testRequires(c, NativeExecDriver)
	if _, err := os.Stat("/dev/snd"); err != nil {
		c.Skip("Host does not have /dev/snd")
	}

	out, _ := dockerCmd(c, "run", "--device", "/dev/snd:/dev/snd", "busybox", "sh", "-c", "ls /dev/snd/")
	if actual := strings.Trim(out, "\r\n"); !strings.Contains(out, "timer") {
		c.Fatalf("expected output /dev/snd/timer, received %s", actual)
	}

	out, _ = dockerCmd(c, "run", "--device", "/dev/snd:/dev/othersnd", "busybox", "sh", "-c", "ls /dev/othersnd/")
	if actual := strings.Trim(out, "\r\n"); !strings.Contains(out, "seq") {
		c.Fatalf("expected output /dev/othersnd/seq, received %s", actual)
	}
}

// TestRunDetach checks attaching and detaching with the escape sequence.
func (s *DockerSuite) TestRunAttachDetach(c *check.C) {
	name := "attach-detach"
	cmd := exec.Command(dockerBinary, "run", "--name", name, "-it", "busybox", "cat")
	stdout, err := cmd.StdoutPipe()
	if err != nil {
		c.Fatal(err)
	}
	cpty, tty, err := pty.Open()
	if err != nil {
		c.Fatal(err)
	}
	defer cpty.Close()
	cmd.Stdin = tty
	if err := cmd.Start(); err != nil {
		c.Fatal(err)
	}
	c.Assert(waitRun(name), check.IsNil)

	if _, err := cpty.Write([]byte("hello\n")); err != nil {
		c.Fatal(err)
	}

	out, err := bufio.NewReader(stdout).ReadString('\n')
	if err != nil {
		c.Fatal(err)
	}
	if strings.TrimSpace(out) != "hello" {
		c.Fatalf("expected 'hello', got %q", out)
	}

	// escape sequence
	if _, err := cpty.Write([]byte{16}); err != nil {
		c.Fatal(err)
	}
	time.Sleep(100 * time.Millisecond)
	if _, err := cpty.Write([]byte{17}); err != nil {
		c.Fatal(err)
	}

	ch := make(chan struct{})
	go func() {
		cmd.Wait()
		ch <- struct{}{}
	}()

	running, err := inspectField(name, "State.Running")
	if err != nil {
		c.Fatal(err)
	}
	if running != "true" {
		c.Fatal("expected container to still be running")
	}

	go func() {
		exec.Command(dockerBinary, "kill", name).Run()
	}()

	select {
	case <-ch:
	case <-time.After(10 * time.Millisecond):
		c.Fatal("timed out waiting for container to exit")
	}
}

// "test" should be printed
func (s *DockerSuite) TestRunEchoStdoutWithCPUQuota(c *check.C) {
	testRequires(c, cpuCfsQuota)

	out, _, err := dockerCmdWithError("run", "--cpu-quota", "8000", "--name", "test", "busybox", "echo", "test")
	if err != nil {
		c.Fatalf("failed to run container: %v, output: %q", err, out)
	}
	out = strings.TrimSpace(out)
	if out != "test" {
		c.Errorf("container should've printed 'test'")
	}

	out, err = inspectField("test", "HostConfig.CpuQuota")
	c.Assert(err, check.IsNil)

	if out != "8000" {
		c.Fatalf("setting the CPU CFS quota failed")
	}
}

func (s *DockerSuite) TestRunWithCpuPeriod(c *check.C) {
	testRequires(c, cpuCfsPeriod)

	if _, _, err := dockerCmdWithError("run", "--cpu-period", "50000", "--name", "test", "busybox", "true"); err != nil {
		c.Fatalf("failed to run container: %v", err)
	}

	out, err := inspectField("test", "HostConfig.CpuPeriod")
	c.Assert(err, check.IsNil)
	if out != "50000" {
		c.Fatalf("setting the CPU CFS period failed")
	}
}

func (s *DockerSuite) TestRunWithKernelMemory(c *check.C) {
	testRequires(c, kernelMemorySupport)

	dockerCmd(c, "run", "--kernel-memory", "50M", "--name", "test1", "busybox", "true")

	out, err := inspectField("test1", "HostConfig.KernelMemory")
	c.Assert(err, check.IsNil)
	c.Assert(out, check.Equals, "52428800")

	out, _, err = dockerCmdWithError("run", "--kernel-memory", "-16m", "--name", "test2", "busybox", "echo", "test")
	expected := "invalid size"
	c.Assert(err, check.NotNil)
	c.Assert(out, checker.Contains, expected)
}

// "test" should be printed
func (s *DockerSuite) TestRunEchoStdoutWitCPUShares(c *check.C) {
	testRequires(c, cpuShare)
	out, _ := dockerCmd(c, "run", "--cpu-shares", "1000", "busybox", "echo", "test")
	if out != "test\n" {
		c.Errorf("container should've printed 'test', got %q instead", out)
	}
}

// "test" should be printed
func (s *DockerSuite) TestRunEchoStdoutWithCPUSharesAndMemoryLimit(c *check.C) {
	testRequires(c, cpuShare)
	testRequires(c, memoryLimitSupport)
	out, _, _ := dockerCmdWithStdoutStderr(c, "run", "--cpu-shares", "1000", "-m", "16m", "busybox", "echo", "test")
	if out != "test\n" {
		c.Errorf("container should've printed 'test', got %q instead", out)
	}
}

func (s *DockerSuite) TestRunWithCpuset(c *check.C) {
	testRequires(c, cgroupCpuset)
	if _, code := dockerCmd(c, "run", "--cpuset", "0", "busybox", "true"); code != 0 {
		c.Fatalf("container should run successfully with cpuset of 0")
	}
}

func (s *DockerSuite) TestRunWithCpusetCpus(c *check.C) {
	testRequires(c, cgroupCpuset)
	if _, code := dockerCmd(c, "run", "--cpuset-cpus", "0", "busybox", "true"); code != 0 {
		c.Fatalf("container should run successfully with cpuset-cpus of 0")
	}
}

func (s *DockerSuite) TestRunWithCpusetMems(c *check.C) {
	testRequires(c, cgroupCpuset)
	if _, code := dockerCmd(c, "run", "--cpuset-mems", "0", "busybox", "true"); code != 0 {
		c.Fatalf("container should run successfully with cpuset-mems of 0")
	}
}

func (s *DockerSuite) TestRunWithBlkioWeight(c *check.C) {
	testRequires(c, blkioWeight)
	if _, code := dockerCmd(c, "run", "--blkio-weight", "300", "busybox", "true"); code != 0 {
		c.Fatalf("container should run successfully with blkio-weight of 300")
	}
}

func (s *DockerSuite) TestRunWithBlkioInvalidWeight(c *check.C) {
	testRequires(c, blkioWeight)
	if _, _, err := dockerCmdWithError("run", "--blkio-weight", "5", "busybox", "true"); err == nil {
		c.Fatalf("run with invalid blkio-weight should failed")
	}
}

func (s *DockerSuite) TestRunOOMExitCode(c *check.C) {
	testRequires(c, oomControl)
	errChan := make(chan error)
	go func() {
		defer close(errChan)
		//changing memory to 40MB from 4MB due to an issue with GCCGO that test fails to start the container.
		out, exitCode, _ := dockerCmdWithError("run", "-m", "40MB", "busybox", "sh", "-c", "x=a; while true; do x=$x$x$x$x; done")
		if expected := 137; exitCode != expected {
			errChan <- fmt.Errorf("wrong exit code for OOM container: expected %d, got %d (output: %q)", expected, exitCode, out)
		}
	}()

	select {
	case err := <-errChan:
		c.Assert(err, check.IsNil)
	case <-time.After(30 * time.Second):
		c.Fatal("Timeout waiting for container to die on OOM")
	}
}

// "test" should be printed
func (s *DockerSuite) TestRunEchoStdoutWithMemoryLimit(c *check.C) {
	testRequires(c, memoryLimitSupport)
	out, _, _ := dockerCmdWithStdoutStderr(c, "run", "-m", "16m", "busybox", "echo", "test")
	out = strings.Trim(out, "\r\n")

	if expected := "test"; out != expected {
		c.Fatalf("container should've printed %q but printed %q", expected, out)
	}
}

// TestRunWithoutMemoryswapLimit sets memory limit and disables swap
// memory limit, this means the processes in the container can use
// 16M memory and as much swap memory as they need (if the host
// supports swap memory).
func (s *DockerSuite) TestRunWithoutMemoryswapLimit(c *check.C) {
	testRequires(c, NativeExecDriver)
	testRequires(c, memoryLimitSupport)
	testRequires(c, swapMemorySupport)
	dockerCmd(c, "run", "-m", "16m", "--memory-swap", "-1", "busybox", "true")
}

func (s *DockerSuite) TestRunWithSwappiness(c *check.C) {
	testRequires(c, memorySwappinessSupport)
	dockerCmd(c, "run", "--memory-swappiness", "0", "busybox", "true")
}

func (s *DockerSuite) TestRunWithSwappinessInvalid(c *check.C) {
	testRequires(c, memorySwappinessSupport)
	out, _, err := dockerCmdWithError("run", "--memory-swappiness", "101", "busybox", "true")
	if err == nil {
		c.Fatalf("failed. test was able to set invalid value, output: %q", out)
	}
}

func (s *DockerSuite) TestStopContainerSignal(c *check.C) {
	out, _ := dockerCmd(c, "run", "--stop-signal", "SIGUSR1", "-d", "busybox", "/bin/sh", "-c", `trap 'echo "exit trapped"; exit 0' USR1; while true; do sleep 1; done`)
	containerID := strings.TrimSpace(out)

	if err := waitRun(containerID); err != nil {
		c.Fatal(err)
	}

	dockerCmd(c, "stop", containerID)
	out, _ = dockerCmd(c, "logs", containerID)

	if !strings.Contains(out, "exit trapped") {
		c.Fatalf("Expected `exit trapped` in the log, got %v", out)
	}
}

func (s *DockerSuite) TestRunSwapLessThanMemoryLimit(c *check.C) {
	testRequires(c, memoryLimitSupport)
	testRequires(c, swapMemorySupport)
	out, _, err := dockerCmdWithError("run", "-m", "16m", "--memory-swap", "15m", "busybox", "echo", "test")
	expected := "Minimum memoryswap limit should be larger than memory limit"
	c.Assert(err, check.NotNil)

	if !strings.Contains(out, expected) {
		c.Fatalf("Expected output to contain %q, not %q", out, expected)
	}
}


text:
#include "rawobj.h"
#include "repository.h"
#include <node_buffer.h>

#define ID_PROPERTY String::NewSymbol("id")
#define DATA_PROPERTY String::NewSymbol("data")
#define TYPE_PROPERTY String::NewSymbol("type")

namespace gitteh {

Persistent<FunctionTemplate> RawObject::constructor_template;

void RawObject::Init(Handle<Object> target) {
	HandleScope scope;

	Local<FunctionTemplate> t = FunctionTemplate::New(New);
	constructor_template = Persistent<FunctionTemplate>::New(t);
	constructor_template->SetClassName(String::NewSymbol("RawObject"));
	t->InstanceTemplate()->SetInternalFieldCount(1);

	NODE_SET_PROTOTYPE_METHOD(t, "save", Save);
}

Handle<Value> RawObject::New(const Arguments& args) {
	HandleScope scope;

	REQ_ARGS(1);
	REQ_EXT_ARG(0, theObj);

	RawObject *obj = new RawObject();
	obj->Wrap(args.This());

	obj->obj_ = static_cast<git_rawobj*>(theObj->Value());

	return args.This();
}

Handle<Value> RawObject::Save(const Arguments& args) {
	HandleScope scope;

	RawObject *obj = ObjectWrap::Unwrap<RawObject>(args.This());

	Handle<Object> thisObj = args.This();

	CHECK_PROPERTY(DATA_PROPERTY);
	CHECK_PROPERTY(TYPE_PROPERTY);

	if(!Buffer::HasInstance(thisObj->Get(DATA_PROPERTY))) {
		THROW_ERROR("Data is not a valid Buffer.");
	}

	Handle<Object> bufferObj = Handle<Object>::Cast(
			thisObj->Get(DATA_PROPERTY));

	git_otype type = git_object_string2type(*String::Utf8Value(
			thisObj->Get(TYPE_PROPERTY)));

	if(type == GIT_OBJ_BAD) {
		THROW_ERROR("Invalid type.");
	}

	obj->obj_->type = type;
	obj->obj_->len = Buffer::Length(bufferObj);
	obj->obj_->data = Buffer::Data(bufferObj);

	git_oid newId;
	int res = git_odb_write(&newId, obj->repository_->odb_, obj->obj_);
	if(res != GIT_SUCCESS)
		THROW_GIT_ERROR("Couldn't save raw object.", res);

	const char* oidStr = git_oid_allocfmt(&newId);
	args.This()->ForceSet(ID_PROPERTY, String::New(oidStr), (PropertyAttribute)(ReadOnly | DontDelete));

	return Undefined();
}

RawObject::~RawObject() {
	delete obj_;
}

struct rawobj_data {
	char id[40];
	std::string *type;
	int len;
	void *data;
};

void RawObject::processInitData(void *data) {
	HandleScope scope;
	Handle<Object> jsObject = handle_;

	if(data != NULL) {
		rawobj_data *rawObjData = static_cast<rawobj_data*>(data);

		jsObject->Set(ID_PROPERTY, String::New(rawObjData->id, 40),
				(PropertyAttribute)(ReadOnly | DontDelete));

		Buffer *buf = Buffer::New(static_cast<char*>(rawObjData->data),
				rawObjData->len);
		Local<Object> globalObj = Context::GetCurrent()->Global();
		Local<Function> bufferConstructor = Local<Function>::Cast(
				globalObj->Get(String::New("Buffer")));
		Handle<Value> constructorArgs[3] = { buf->handle_, Integer::New(
				rawObjData->len), Integer::New(0) };
		Local<Object> actualBuffer = bufferConstructor->NewInstance(3, constructorArgs);
		jsObject->Set(DATA_PROPERTY, actualBuffer);
		jsObject->Set(TYPE_PROPERTY, String::New(rawObjData->type->c_str()));

		delete rawObjData->type;
		delete rawObjData;
	}
	else {
		jsObject->Set(ID_PROPERTY, Null(), (PropertyAttribute)(ReadOnly | DontDelete));
		jsObject->Set(DATA_PROPERTY, Null());

		repository_->lockRepository();
		jsObject->Set(TYPE_PROPERTY, String::New(git_object_type2string(GIT_OBJ_BAD)));
		repository_->unlockRepository();
	}
}

void* RawObject::loadInitData() {
	rawobj_data *data = new rawobj_data;

	repository_->lockRepository();
	git_oid id;
	int res = git_rawobj_hash(&id, obj_);
	if(res == GIT_SUCCESS) {
		// TODO: what should we do if this fails?
		git_oid_fmt(data->id, &id);
	}

	data->type = new std::string(git_object_type2string(obj_->type));
	data->len = obj_->len;
	data->data = malloc(data->len);
	memcpy(data->data, obj_->data, data->len);

	repository_->unlockRepository();

	return data;
}

void RawObject::setOwner(void *owner) {
	repository_ = static_cast<Repository*>(owner);
}

} // namespace gitteh


text:
import { addDisposableDomListener } from 'browser/Lifecycle';
import { IRenderService } from 'browser/services/Services';
import { Disposable, toDisposable } from 'common/Lifecycle';
import { IBufferService, IDecorationService, IInternalDecoration } from 'common/services/Services';

export class BufferDecorationRenderer extends Disposable {
  private readonly _container: HTMLElement;
  private readonly _decorationElements: Map<IInternalDecoration, HTMLElement> = new Map();

  private _animationFrame: number | undefined;
  private _altBufferIsActive: boolean = false;
  private _dimensionsChanged: boolean = false;

  constructor(
    private readonly _screenElement: HTMLElement,
    @IBufferService private readonly _bufferService: IBufferService,
    @IDecorationService private readonly _decorationService: IDecorationService,
    @IRenderService private readonly _renderService: IRenderService
  ) {
    super();

    this._container = document.createElement('div');
    this._container.classList.add('xterm-decoration-container');
    this._screenElement.appendChild(this._container);

    this.register(this._renderService.onRenderedViewportChange(() => this._doRefreshDecorations()));
    this.register(this._renderService.onDimensionsChange(() => {
      this._dimensionsChanged = true;
      this._queueRefresh();
    }));
    this.register(addDisposableDomListener(window, 'resize', () => this._queueRefresh()));
    this.register(this._bufferService.buffers.onBufferActivate(() => {
      this._altBufferIsActive = this._bufferService.buffer === this._bufferService.buffers.alt;
    }));
    this.register(this._decorationService.onDecorationRegistered(() => this._queueRefresh()));
    this.register(this._decorationService.onDecorationRemoved(decoration => this._removeDecoration(decoration)));
    this.register(toDisposable(() => {
      this._container.remove();
      this._decorationElements.clear();
    }));
  }

  private _queueRefresh(): void {
    if (this._animationFrame !== undefined) {
      return;
    }
    this._animationFrame = this._renderService.addRefreshCallback(() => {
      this._doRefreshDecorations();
      this._animationFrame = undefined;
    });
  }

  private _doRefreshDecorations(): void {
    for (const decoration of this._decorationService.decorations) {
      this._renderDecoration(decoration);
    }
    this._dimensionsChanged = false;
  }

  private _renderDecoration(decoration: IInternalDecoration): void {
    this._refreshStyle(decoration);
    if (this._dimensionsChanged) {
      this._refreshXPosition(decoration);
    }
  }

  private _createElement(decoration: IInternalDecoration): HTMLElement {
    const element = document.createElement('div');
    element.classList.add('xterm-decoration');
    element.style.width = `${Math.round((decoration.options.width || 1) * this._renderService.dimensions.css.cell.width)}px`;
    element.style.height = `${(decoration.options.height || 1) * this._renderService.dimensions.css.cell.height}px`;
    element.style.top = `${(decoration.marker.line - this._bufferService.buffers.active.ydisp) * this._renderService.dimensions.css.cell.height}px`;
    element.style.lineHeight = `${this._renderService.dimensions.css.cell.height}px`;

    const x = decoration.options.x ?? 0;
    if (x && x > this._bufferService.cols) {
      // exceeded the container width, so hide
      element.style.display = 'none';
    }
    this._refreshXPosition(decoration, element);

    return element;
  }

  private _refreshStyle(decoration: IInternalDecoration): void {
    const line = decoration.marker.line - this._bufferService.buffers.active.ydisp;
    if (line < 0 || line >= this._bufferService.rows) {
      // outside of viewport
      if (decoration.element) {
        decoration.element.style.display = 'none';
        decoration.onRenderEmitter.fire(decoration.element);
      }
    } else {
      let element = this._decorationElements.get(decoration);
      if (!element) {
        element = this._createElement(decoration);
        decoration.element = element;
        this._decorationElements.set(decoration, element);
        this._container.appendChild(element);
      }
      element.style.top = `${line * this._renderService.dimensions.css.cell.height}px`;
      element.style.display = this._altBufferIsActive ? 'none' : 'block';
      decoration.onRenderEmitter.fire(element);
    }
  }

  private _refreshXPosition(decoration: IInternalDecoration, element: HTMLElement | undefined = decoration.element): void {
    if (!element) {
      return;
    }
    const x = decoration.options.x ?? 0;
    if ((decoration.options.anchor || 'left') === 'right') {
      element.style.right = x ? `${x * this._renderService.dimensions.css.cell.width}px` : '';
    } else {
      element.style.left = x ? `${x * this._renderService.dimensions.css.cell.width}px` : '';
    }
  }

  private _removeDecoration(decoration: IInternalDecoration): void {
    this._decorationElements.get(decoration)?.remove();
    this._decorationElements.delete(decoration);
    decoration.dispose();
  }
}


text:
import { CodeEditorWidget } from 'vs/editor/browser/widget/codeEditorWidget';
import { Disposable, DisposableStore } from 'vs/base/common/lifecycle';
import { IEditorOptions } from 'vs/editor/common/config/editorOptions';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { getResizesObserver } from 'vs/workbench/contrib/notebook/browser/view/renderers/sizeObserver';
import { INotebookEditor, CellRenderTemplate, CellFocusMode, CellEditState } from 'vs/workbench/contrib/notebook/browser/notebookBrowser';
import { CancellationTokenSource } from 'vs/base/common/cancellation';
import { raceCancellation } from 'vs/base/common/async';
import { MarkdownCellViewModel } from 'vs/workbench/contrib/notebook/browser/viewModel/markdownCellViewModel';
import { EDITOR_TOP_PADDING, EDITOR_BOTTOM_PADDING } from 'vs/workbench/contrib/notebook/browser/constants';
import { ITextModel } from 'vs/editor/common/model';
import { IDimension } from 'vs/base/browser/dom';

export class StatefullMarkdownCell extends Disposable {
	private editor: CodeEditorWidget | null = null;
	private cellContainer: HTMLElement;
	private editingContainer?: HTMLElement;

	private localDisposables: DisposableStore;

	constructor(
		private notebookEditor: INotebookEditor,
		private viewCell: MarkdownCellViewModel,
		private templateData: CellRenderTemplate,
		editorOptions: IEditorOptions,
		instantiationService: IInstantiationService
	) {
		super();

		this.cellContainer = templateData.cellContainer;
		this.editingContainer = templateData.editingContainer;
		this.localDisposables = new DisposableStore();
		this._register(this.localDisposables);

		const viewUpdate = () => {
			if (viewCell.editState === CellEditState.Editing) {
				// switch to editing mode
				let width = viewCell.layoutInfo.editorWidth;
				const lineNum = viewCell.lineCount;
				const lineHeight = viewCell.layoutInfo.fontInfo?.lineHeight || 17;
				const totalHeight = Math.max(lineNum, 1) * lineHeight + EDITOR_TOP_PADDING + EDITOR_BOTTOM_PADDING;

				if (this.editor) {
					// not first time, we don't need to create editor or bind listeners
					this.editingContainer!.style.display = 'block';
					viewCell.attachTextEditor(this.editor!);
					if (notebookEditor.getActiveCell() === viewCell) {
						this.editor!.focus();
					}

					this.bindEditorListeners(this.editor!.getModel()!);
				} else {
					this.editingContainer!.style.display = 'block';
					this.editingContainer!.innerHTML = '';
					this.editor = instantiationService.createInstance(CodeEditorWidget, this.editingContainer!, {
						...editorOptions,
						dimension: {
							width: width,
							height: totalHeight
						}
					}, {});

					const cts = new CancellationTokenSource();
					this._register({ dispose() { cts.dispose(true); } });
					raceCancellation(viewCell.resolveTextModel(), cts.token).then(model => {
						if (!model) {
							return;
						}

						this.editor!.setModel(model);
						if (notebookEditor.getActiveCell() === viewCell) {
							this.editor!.focus();
						}

						const realContentHeight = this.editor!.getContentHeight();
						if (realContentHeight !== totalHeight) {
							this.editor!.layout(
								{
									width: width,
									height: realContentHeight
								}
							);
						}

						viewCell.attachTextEditor(this.editor!);

						if (viewCell.editState === CellEditState.Editing) {
							this.editor!.focus();
						}

						this.bindEditorListeners(model, {
							width: width,
							height: totalHeight
						});
					});
				}

				const clientHeight = this.cellContainer.clientHeight;
				notebookEditor.layoutNotebookCell(viewCell, totalHeight + 32 + clientHeight);
				this.editor.focus();
			} else {
				this.viewCell.detachTextEditor();
				if (this.editor) {
					// switch from editing mode
					this.editingContainer!.style.display = 'none';
					const clientHeight = templateData.container.clientHeight;
					notebookEditor.layoutNotebookCell(viewCell, clientHeight);
				} else {
					// first time, readonly mode
					this.editingContainer!.style.display = 'none';

					this.cellContainer.innerHTML = '';
					let markdownRenderer = viewCell.getMarkdownRenderer();
					let renderedHTML = viewCell.getHTML();
					if (renderedHTML) {
						this.cellContainer.appendChild(renderedHTML);
					}

					this.localDisposables.add(markdownRenderer.onDidUpdateRender(() => {
						const clientHeight = templateData.container.clientHeight;
						notebookEditor.layoutNotebookCell(viewCell, clientHeight);
					}));

					this.localDisposables.add(viewCell.onDidChangeContent(() => {
						this.cellContainer.innerHTML = '';
						let renderedHTML = viewCell.getHTML();
						if (renderedHTML) {
							this.cellContainer.appendChild(renderedHTML);
						}
					}));
				}
			}
		};

		this._register(viewCell.onDidChangeCellEditState(() => {
			this.localDisposables.clear();
			viewUpdate();
		}));

		this._register(viewCell.onDidChangeFocusMode(() => {
			if (viewCell.focusMode === CellFocusMode.Editor) {
				this.editor?.focus();
			}
		}));

		viewUpdate();
	}

	bindEditorListeners(model: ITextModel, dimension?: IDimension) {
		this.localDisposables.add(model.onDidChangeContent(() => {
			this.viewCell.setText(model.getLinesContent());
			let clientHeight = this.cellContainer.clientHeight;
			this.cellContainer.innerHTML = '';
			let renderedHTML = this.viewCell.getHTML();
			if (renderedHTML) {
				this.cellContainer.appendChild(renderedHTML);
				clientHeight = this.cellContainer.clientHeight;
			}

			this.notebookEditor.layoutNotebookCell(this.viewCell, this.editor!.getContentHeight() + 32 + clientHeight);
		}));

		this.localDisposables.add(this.editor!.onDidContentSizeChange(e => {
			let viewLayout = this.editor!.getLayoutInfo();

			if (e.contentHeightChanged) {
				this.editor!.layout(
					{
						width: viewLayout.width,
						height: e.contentHeight
					}
				);
				const clientHeight = this.cellContainer.clientHeight;
				this.notebookEditor.layoutNotebookCell(this.viewCell, e.contentHeight + 32 + clientHeight);
			}
		}));

		this.localDisposables.add(this.editor!.onDidChangeCursorSelection((e) => {
			if (e.source === 'restoreState') {
				// do not reveal the cell into view if this selection change was caused by restoring editors...
				return;
			}

			const primarySelection = this.editor!.getSelection();

			if (primarySelection) {
				this.notebookEditor.revealLineInView(this.viewCell, primarySelection!.positionLineNumber);
			}
		}));

		let cellWidthResizeObserver = getResizesObserver(this.templateData.editingContainer!, dimension, () => {
			let newWidth = cellWidthResizeObserver.getWidth();
			let realContentHeight = this.editor!.getContentHeight();
			let layoutInfo = this.editor!.getLayoutInfo();

			// the dimension generated by the resize observer are float numbers, let's round it a bit to avoid relayout.
			if (newWidth < layoutInfo.width - 0.3 || layoutInfo.width + 0.3 < newWidth) {
				this.editor!.layout(
					{
						width: newWidth,
						height: realContentHeight
					}
				);
			}
		});

		cellWidthResizeObserver.startObserving();
		this.localDisposables.add(cellWidthResizeObserver);

		let markdownRenderer = this.viewCell.getMarkdownRenderer();
		this.cellContainer.innerHTML = '';
		let renderedHTML = this.viewCell.getHTML();
		if (renderedHTML) {
			this.cellContainer.appendChild(renderedHTML);
			this.localDisposables.add(markdownRenderer.onDidUpdateRender(() => {
				const clientHeight = this.cellContainer.clientHeight;
				this.notebookEditor.layoutNotebookCell(this.viewCell, clientHeight);
			}));
		}
	}

	dispose() {
		this.viewCell.detachTextEditor();
		super.dispose();
	}
}


text:
from django.db import models
from django.utils.translation import ugettext_lazy as _

from mezzanine.conf import settings
from mezzanine.core.fields import FileField
from mezzanine.core.models import Displayable, Ownable, RichText, Slugged
from mezzanine.generic.fields import CommentsField, RatingField
from mezzanine.utils.models import AdminThumbMixin

class BlogPost(Displayable, Ownable, RichText, AdminThumbMixin):
    """
    A blog post.
    """

    categories = models.ManyToManyField("BlogCategory",
                                        verbose_name=_("Categories"),
                                        blank=True, related_name="blogposts")
    allow_comments = models.BooleanField(verbose_name=_("Allow comments"),
                                         default=True)
    comments = CommentsField(verbose_name=_("Comments"))
    rating = RatingField(verbose_name=_("Rating"))
    featured_image = FileField(verbose_name=_("Featured Image"), null=True,
                               upload_to="blog", max_length=255, blank=True)

    admin_thumb_field = "featured_image"

    class Meta:
        verbose_name = _("Blog post")
        verbose_name_plural = _("Blog posts")
        ordering = ("-publish_date",)

    @models.permalink
    def get_absolute_url(self):
        url_name = "blog_post_detail"
        kwargs = {"slug": self.slug}
        if settings.BLOG_URLS_USE_DATE:
            url_name = "blog_post_detail_date"
            month = str(self.publish_date.month)
            if len(month) == 1:
                month = "0" + month
            kwargs.update({"month": month, "year": self.publish_date.year})
        return (url_name, (), kwargs)

class BlogCategory(Slugged):
    """
    A category for grouping blog posts into a series.
    """

    class Meta:
        verbose_name = _("Blog Category")
        verbose_name_plural = _("Blog Categories")

    @models.permalink
    def get_absolute_url(self):
        return ("blog_post_list_category", (), {"slug": self.slug})