text:
package org.apache.drill.exec.store.avro;

import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import org.apache.avro.Schema;
import org.apache.avro.Schema.Type;
import org.apache.avro.SchemaBuilder;
import org.apache.avro.file.DataFileWriter;
import org.apache.avro.generic.GenericArray;
import org.apache.avro.generic.GenericData;
import org.apache.avro.generic.GenericDatumWriter;
import org.apache.avro.generic.GenericRecord;

import com.google.common.base.Charsets;
import org.apache.drill.exec.util.JsonStringArrayList;
import org.apache.drill.exec.util.JsonStringHashMap;
import org.apache.drill.exec.util.Text;

/**
 * Utilities for generating Avro test data.
 */
public class AvroTestUtil {

  public static final int RECORD_COUNT = 10_000;
  public static int ARRAY_SIZE = 20;

  /**
   * Class to write records to an Avro file while simultaneously
   * constructing a corresponding list of records in the format taken in
   * by the Drill test builder to describe expected results.
   */
  public static class AvroTestRecordWriter implements Closeable {
    private final List<Map<String, Object>> expectedRecords;
    GenericData.Record currentAvroRecord;
    TreeMap<String, Object> currentExpectedRecord;
    private Schema schema;
    private final DataFileWriter<GenericData.Record> writer;
    private final String filePath;

    private AvroTestRecordWriter(Schema schema, File file) {
      writer = new DataFileWriter<GenericData.Record>(new GenericDatumWriter<GenericData.Record>(schema));
      try {
        writer.create(schema, file);
      } catch (IOException e) {
        throw new RuntimeException("Error creating file in Avro test setup.", e);
      }
      this.schema = schema;
      currentExpectedRecord = new TreeMap<>();
      expectedRecords = new ArrayList<>();
      filePath = file.getAbsolutePath();
    }

    public void startRecord() {
      currentAvroRecord = new GenericData.Record(schema);
      currentExpectedRecord = new TreeMap<>();
    }

    public void put(String key, Object value) {
      currentAvroRecord.put(key, value);
      // convert binary values into byte[], the format they will be given
      // in the Drill result set in the test framework
      currentExpectedRecord.put("`" + key + "`", convertAvroValToDrill(value, true));
    }

    // TODO - fix this the test wrapper to prevent the need for this hack
    // to make the root behave differently than nested fields for String vs. Text
    private Object convertAvroValToDrill(Object value, boolean root) {
      if (value instanceof ByteBuffer) {
        ByteBuffer bb = ((ByteBuffer)value);
        byte[] drillVal = new byte[((ByteBuffer)value).remaining()];
        bb.get(drillVal);
        bb.position(0);
        value = drillVal;
      } else if (!root && value instanceof CharSequence) {
        value = new Text(value.toString());
      } else if (value instanceof GenericData.Array) {
        GenericData.Array array = ((GenericData.Array) value);
        final JsonStringArrayList<Object> drillList = new JsonStringArrayList<>();
        for (Object o : array) {
          drillList.add(convertAvroValToDrill(o, false));
        }
        value = drillList;
      } else if (value instanceof GenericData.EnumSymbol) {
        value = value.toString();
      } else if (value instanceof GenericData.Record) {
        GenericData.Record rec = ((GenericData.Record) value);
        final JsonStringHashMap<String, Object> newRecord = new JsonStringHashMap<>();
        for (Schema.Field field : rec.getSchema().getFields()) {
          Object val = rec.get(field.name());
          newRecord.put(field.name(), convertAvroValToDrill(val, false));
        }
        value = newRecord;
      }
      return value;
    }

    public void endRecord() throws IOException {
      writer.append(currentAvroRecord);
      expectedRecords.add(currentExpectedRecord);
    }

    @Override
    public void close() throws IOException {
      writer.close();
    }

    public String getFilePath() {
      return filePath;
    }

    public List<Map<String, Object>>getExpectedRecords() {
      return expectedRecords;
    }
  }

  public static AvroTestRecordWriter generateSimplePrimitiveSchema_NoNullValues() throws Exception {
    return generateSimplePrimitiveSchema_NoNullValues(RECORD_COUNT);
  }

  public static AvroTestRecordWriter generateSimplePrimitiveSchema_NoNullValues(int numRecords) throws Exception {

    final Schema schema = SchemaBuilder.record("AvroRecordReaderTest")
            .namespace("org.apache.drill.exec.store.avro")
            .fields()
            .name("a_string").type().stringType().noDefault()
            .name("b_int").type().intType().noDefault()
            .name("c_long").type().longType().noDefault()
            .name("d_float").type().floatType().noDefault()
            .name("e_double").type().doubleType().noDefault()
            .name("f_bytes").type().bytesType().noDefault()
            .name("g_null").type().nullType().noDefault()
            .name("h_boolean").type().booleanType().noDefault()
            .endRecord();

    final File file = File.createTempFile("avro-primitive-test", ".avro");
    file.deleteOnExit();

    final AvroTestRecordWriter record = new AvroTestRecordWriter(schema, file);
    try {
      ByteBuffer bb = ByteBuffer.allocate(2);
      bb.put(0, (byte) 'a');

      for (int i = 0; i < numRecords; i++) {
        bb.put(1, (byte) ('0' + (i % 10)));
        bb.position(0);
        record.startRecord();
        record.put("a_string", "a_" + i);
        record.put("b_int", i);
        record.put("c_long", (long) i);
        record.put("d_float", (float) i);
        record.put("e_double", (double) i);
        record.put("f_bytes", bb);
        record.put("g_null", null);
        record.put("h_boolean", (i % 2 == 0));
        record.endRecord();
      }
    } finally {
      record.close();
    }

    return record;
  }

  public static AvroTestRecordWriter generateUnionSchema_WithNullValues() throws Exception {

    final Schema schema = SchemaBuilder.record("AvroRecordReaderTest")
            .namespace("org.apache.drill.exec.store.avro")
            .fields()
            .name("a_string").type().stringType().noDefault()
            .name("b_int").type().intType().noDefault()
            .name("c_long").type().longType().noDefault()
            .name("d_float").type().floatType().noDefault()
            .name("e_double").type().doubleType().noDefault()
            .name("f_bytes").type().bytesType().noDefault()
            .name("g_null").type().nullType().noDefault()
            .name("h_boolean").type().booleanType().noDefault()
            .name("i_union").type().optional().doubleType()
            .endRecord();

    final File file = File.createTempFile("avro-primitive-test", ".avro");
    file.deleteOnExit();

    final AvroTestRecordWriter record = new AvroTestRecordWriter(schema, file);
    try {

      ByteBuffer bb = ByteBuffer.allocate(1);
      bb.put(0, (byte) 1);

      for (int i = 0; i < RECORD_COUNT; i++) {
        record.startRecord();
        record.put("a_string", "a_" + i);
        record.put("b_int", i);
        record.put("c_long", (long) i);
        record.put("d_float", (float) i);
        record.put("e_double", (double) i);
        record.put("f_bytes", bb);
        record.put("g_null", null);
        record.put("h_boolean", (i % 2 == 0));
        record.put("i_union", (i % 2 == 0 ? (double) i : null));
        record.endRecord();
      }
    } finally {
      record.close();
    }

    return record;
  }

  public static AvroTestRecordWriter generateUnionSchema_WithNonNullValues() throws Exception {

    final Schema schema = SchemaBuilder.record("AvroRecordReaderTest")
            .namespace("org.apache.drill.exec.store.avro")
            .fields()
            .name("a_string").type().stringType().noDefault()
            .name("b_int").type().intType().noDefault()
            .name("c_long").type().longType().noDefault()
            .name("d_float").type().floatType().noDefault()
            .name("e_double").type().doubleType().noDefault()
            .name("f_bytes").type().bytesType().noDefault()
            .name("g_null").type().nullType().noDefault()
            .name("h_boolean").type().booleanType().noDefault()
            .name("i_union").type().unionOf().doubleType().and().longType().endUnion().noDefault()
            .endRecord();

    final File file = File.createTempFile("avro-primitive-test", ".avro");
    file.deleteOnExit();

    final AvroTestRecordWriter record = new AvroTestRecordWriter(schema, file);
    try {

      ByteBuffer bb = ByteBuffer.allocate(1);
      bb.put(0, (byte) 1);

      for (int i = 0; i < RECORD_COUNT; i++) {
        record.startRecord();
        record.put("a_string", "a_" + i);
        record.put("b_int", i);
        record.put("c_long", (long) i);
        record.put("d_float", (float) i);
        record.put("e_double", (double) i);
        record.put("f_bytes", bb);
        record.put("g_null", null);
        record.put("h_boolean", (i % 2 == 0));
        record.put("i_union", (i % 2 == 0 ? (double) i : (long) i));
        record.endRecord();
      }
    } finally {
      record.close();
    }

    return record;
  }

  public static AvroTestRecordWriter generateSimpleEnumSchema_NoNullValues() throws Exception {

    final String[] symbols = { "E_SYM_A", "E_SYM_B", "E_SYM_C", "E_SYM_D" };

    final Schema schema = SchemaBuilder.record("AvroRecordReaderTest")
            .namespace("org.apache.drill.exec.store.avro")
            .fields()
            .name("a_string").type().stringType().noDefault()
            .name("b_enum").type().enumeration("my_enum").symbols(symbols).noDefault()
            .endRecord();

    final File file = File.createTempFile("avro-primitive-test", ".avro");
    file.deleteOnExit();

    final Schema enumSchema = schema.getField("b_enum").schema();

    final AvroTestRecordWriter record = new AvroTestRecordWriter(schema, file);
    try {

      for (int i = 0; i < RECORD_COUNT; i++) {
        record.startRecord();
        record.put("a_string", "a_" + i);
        final GenericData.EnumSymbol symbol =
                new GenericData.EnumSymbol(enumSchema, symbols[(i + symbols.length) % symbols.length]);
        record.put("b_enum", symbol);
        record.endRecord();
      }
    } finally {
      record.close();
    }

    return record;
  }

  public static AvroTestRecordWriter generateSimpleArraySchema_NoNullValues() throws Exception {

    final File file = File.createTempFile("avro-array-test", ".avro");
    file.deleteOnExit();

    final Schema schema = SchemaBuilder.record("AvroRecordReaderTest")
            .namespace("org.apache.drill.exec.store.avro")
            .fields()
            .name("a_string").type().stringType().noDefault()
            .name("b_int").type().intType().noDefault()
            .name("c_string_array").type().array().items().stringType().noDefault()
            .name("d_int_array").type().array().items().intType().noDefault()
            .name("e_float_array").type().array().items().floatType().noDefault()
            .endRecord();

    final AvroTestRecordWriter record = new AvroTestRecordWriter(schema, file);
    try {
      for (int i = 0; i < RECORD_COUNT; i++) {
        record.startRecord();
        record.put("a_string", "a_" + i);
        record.put("b_int", i);
        {
          GenericArray<String> array = new GenericData.Array<>(ARRAY_SIZE, schema.getField("c_string_array").schema());
          for (int j = 0; j < ARRAY_SIZE; j++) {
            array.add(j, "c_string_array_" + i + "_" + j);
          }
          record.put("c_string_array", array);
        }
        {
          GenericArray<Integer> array = new GenericData.Array<>(ARRAY_SIZE, schema.getField("d_int_array").schema());
          for (int j = 0; j < ARRAY_SIZE; j++) {
            array.add(j, i * j);
          }
          record.put("d_int_array", array);
        }
        {
          GenericArray<Float> array = new GenericData.Array<>(ARRAY_SIZE, schema.getField("e_float_array").schema());
          for (int j = 0; j < ARRAY_SIZE; j++) {
            array.add(j, (float) (i * j));
          }
          record.put("e_float_array", array);
        }
        record.endRecord();
      }

    } finally {
      record.close();
    }
    return record;
  }

  public static AvroTestRecordWriter generateSimpleNestedSchema_NoNullValues() throws Exception {

    final File file = File.createTempFile("avro-nested-test", ".avro");
    file.deleteOnExit();

    final Schema schema = SchemaBuilder.record("AvroRecordReaderTest")
            .namespace("org.apache.drill.exec.store.avro")
            .fields()
            .name("a_string").type().stringType().noDefault()
            .name("b_int").type().intType().noDefault()
            .name("c_record").type().record("my_record_1")
              .namespace("foo.blah.org")
              .fields()
              .name("nested_1_string").type().stringType().noDefault()
              .name("nested_1_int").type().intType().noDefault()
              .endRecord()
            .noDefault()
            .endRecord();

    final Schema nestedSchema = schema.getField("c_record").schema();

    final AvroTestRecordWriter record = new AvroTestRecordWriter(schema, file);
    try {
      for (int i = 0; i < RECORD_COUNT; i++) {
        record.startRecord();
        record.put("a_string", "a_" + i);
        record.put("b_int", i);

        final GenericRecord nestedRecord = new GenericData.Record(nestedSchema);
        nestedRecord.put("nested_1_string", "nested_1_string_" +  i);
        nestedRecord.put("nested_1_int", i * i);

        record.put("c_record", nestedRecord);
        record.endRecord();
      }
    } finally {
      record.close();
    }

    return record;
  }

  public static AvroTestRecordWriter generateUnionNestedArraySchema_withNullValues() throws Exception {

    final File file = File.createTempFile("avro-nested-test", ".avro");
    file.deleteOnExit();

    final Schema schema = SchemaBuilder.record("AvroRecordReaderTest")
            .namespace("org.apache.drill.exec.store.avro")
            .fields()
            .name("a_string").type().stringType().noDefault()
            .name("b_int").type().intType().noDefault()
            .name("c_array").type().optional().array().items().record("my_record_1")
            .namespace("foo.blah.org").fields()
            .name("nested_1_string").type().optional().stringType()
            .name("nested_1_int").type().optional().intType()
            .endRecord()
            .endRecord();

    final Schema nestedSchema = schema.getField("c_array").schema();
    final Schema arraySchema = nestedSchema.getTypes().get(1);
    final Schema itemSchema = arraySchema.getElementType();

    final AvroTestRecordWriter record = new AvroTestRecordWriter(schema, file);
    try {
      for (int i = 0; i < RECORD_COUNT; i++) {
        record.startRecord();
        record.put("a_string", "a_" + i);
        record.put("b_int", i);

        if (i % 2 == 0) {
          GenericArray<GenericRecord> array = new GenericData.Array<>(1, arraySchema);
          final GenericRecord nestedRecord = new GenericData.Record(itemSchema);
          nestedRecord.put("nested_1_string", "nested_1_string_" +  i);
          nestedRecord.put("nested_1_int", i * i);
          array.add(nestedRecord);
          record.put("c_array", array);
        }
        record.endRecord();
      }
    } finally {
      record.close();
    }

    return record;
  }

  public static AvroTestRecordWriter generateMapSchema_withNullValues() throws Exception {

    final File file = File.createTempFile("avro-nested-test", ".avro");
    file.deleteOnExit();

    final Schema schema = SchemaBuilder.record("AvroRecordReaderTest")
            .namespace("org.apache.drill.exec.store.avro")
            .fields()
            .name("a_string").type().stringType().noDefault()
            .name("b_int").type().intType().noDefault()
            .name("c_map").type().optional().map().values(Schema.create(Type.STRING))
            .endRecord();

    final AvroTestRecordWriter record = new AvroTestRecordWriter(schema, file);
    try {
      for (int i = 0; i < RECORD_COUNT; i++) {
        record.startRecord();
        record.put("a_string", "a_" + i);
        record.put("b_int", i);

        if (i % 2 == 0) {
          Map<String, String> strMap = new HashMap<>();
          strMap.put("key1", "nested_1_string_" +  i);
          strMap.put("key2", "nested_1_string_" +  (i + 1 ));
          record.put("c_map", strMap);
        }
        record.endRecord();
      }
    } finally {
      record.close();
    }

    return record;
  }

  public static AvroTestRecordWriter generateMapSchemaComplex_withNullValues() throws Exception {

    final File file = File.createTempFile("avro-nested-test", ".avro");
    file.deleteOnExit();

    final Schema schema = SchemaBuilder.record("AvroRecordReaderTest")
            .namespace("org.apache.drill.exec.store.avro")
            .fields()
            .name("a_string").type().stringType().noDefault()
            .name("b_int").type().intType().noDefault()
            .name("c_map").type().optional().map().values(Schema.create(Type.STRING))
            .name("d_map").type().optional().map().values(Schema.createArray(Schema.create(Type.DOUBLE)))
            .endRecord();

    final Schema arrayMapSchema = schema.getField("d_map").schema();
    final Schema arrayItemSchema = arrayMapSchema.getTypes().get(1).getValueType();

    final AvroTestRecordWriter record = new AvroTestRecordWriter(schema, file);
    try {
      for (int i = 0; i < RECORD_COUNT; i++) {
        record.startRecord();
        record.put("a_string", "a_" + i);
        record.put("b_int", i);

        if (i % 2 == 0) {
          Map<String, String> c_map = new HashMap<>();
          c_map.put("key1", "nested_1_string_" +  i);
          c_map.put("key2", "nested_1_string_" +  (i + 1 ));
          record.put("c_map", c_map);
        } else {
          Map<String, GenericArray<Double>> d_map = new HashMap<>();
          GenericArray<Double> array = new GenericData.Array<>(ARRAY_SIZE, arrayItemSchema);
          for (int j = 0; j < ARRAY_SIZE; j++) {
            array.add((double)j);
          }
          d_map.put("key1", array);
          d_map.put("key2", array);

          record.put("d_map", d_map);
        }
        record.endRecord();
      }
    } finally {
      record.close();
    }

    return record;
  }

  public static AvroTestRecordWriter generateUnionNestedSchema_withNullValues() throws Exception {

    final File file = File.createTempFile("avro-nested-test", ".avro");
    file.deleteOnExit();

    final Schema schema = SchemaBuilder.record("AvroRecordReaderTest")
            .namespace("org.apache.drill.exec.store.avro")
            .fields()
            .name("a_string").type().stringType().noDefault()
            .name("b_int").type().intType().noDefault()
            .name("c_record").type().optional().record("my_record_1")
            .namespace("foo.blah.org").fields()
            .name("nested_1_string").type().optional().stringType()
            .name("nested_1_int").type().optional().intType()
            .endRecord()
            .endRecord();

    final Schema nestedSchema = schema.getField("c_record").schema();
    final Schema optionalSchema = nestedSchema.getTypes().get(1);

    final AvroTestRecordWriter record = new AvroTestRecordWriter(schema, file);
    try {
      for (int i = 0; i < RECORD_COUNT; i++) {
        record.startRecord();
        record.put("a_string", "a_" + i);
        record.put("b_int", i);

        if (i % 2 == 0) {
          final GenericRecord nestedRecord = new GenericData.Record(optionalSchema);
          nestedRecord.put("nested_1_string", "nested_1_string_" +  i);
          nestedRecord.put("nested_1_int", i * i);
          record.put("c_record", nestedRecord);
        }
        record.endRecord();
      }
    } finally {
      record.close();
    }

    return record;
  }

  public static AvroTestRecordWriter generateDoubleNestedSchema_NoNullValues() throws Exception {

    final File file = File.createTempFile("avro-double-nested-test", ".avro");
    file.deleteOnExit();

    final Schema schema = SchemaBuilder.record("AvroRecordReaderTest")
            .namespace("org.apache.drill.exec.store.avro")
            .fields()
            .name("a_string").type().stringType().noDefault()
            .name("b_int").type().intType().noDefault()
            .name("c_record").type().record("my_record_1")
              .namespace("foo.blah.org")
              .fields()
              .name("nested_1_string").type().stringType().noDefault()
              .name("nested_1_int").type().intType().noDefault()
              .name("nested_1_record").type().record("my_double_nested_record_1")
                .namespace("foo.blah.org.rot")
                .fields()
                .name("double_nested_1_string").type().stringType().noDefault()
                .name("double_nested_1_int").type().intType().noDefault()
                .endRecord()
                .noDefault()
              .endRecord()
              .noDefault()
            .endRecord();

    final Schema nestedSchema = schema.getField("c_record").schema();
    final Schema doubleNestedSchema = nestedSchema.getField("nested_1_record").schema();

    final AvroTestRecordWriter record = new AvroTestRecordWriter(schema, file);
    try {
      for (int i = 0; i < RECORD_COUNT; i++) {
        record.startRecord();
        record.put("a_string", "a_" + i);
        record.put("b_int", i);

        final GenericRecord nestedRecord = new GenericData.Record(nestedSchema);
        nestedRecord.put("nested_1_string", "nested_1_string_" +  i);
        nestedRecord.put("nested_1_int", i * i);

        final GenericRecord doubleNestedRecord = new GenericData.Record(doubleNestedSchema);
        doubleNestedRecord.put("double_nested_1_string", "double_nested_1_string_" + i + "_" + i);
        doubleNestedRecord.put("double_nested_1_int", i * i * i);

        nestedRecord.put("nested_1_record", doubleNestedRecord);
        record.put("c_record", nestedRecord);

        record.endRecord();
      }
    } finally {
      record.close();
    }

    return record;
  }

  public static String generateLinkedList() throws Exception {

    final File file = File.createTempFile("avro-linkedlist", ".avro");
    file.deleteOnExit();

    final Schema schema = SchemaBuilder.record("LongList")
            .namespace("org.apache.drill.exec.store.avro")
            .aliases("LinkedLongs")
            .fields()
            .name("value").type().optional().longType()
            .name("next").type().optional().type("LongList")
            .endRecord();

    final DataFileWriter<GenericRecord> writer = new DataFileWriter<GenericRecord>(new GenericDatumWriter<GenericRecord>(schema));
    writer.create(schema, file);
    GenericRecord previousRecord = null;
    try {
      for (int i = 0; i < RECORD_COUNT; i++) {
        GenericRecord record = (GenericRecord) (previousRecord == null ? new GenericData.Record(schema) : previousRecord.get("next"));
        record.put("value", (long) i);
        if (previousRecord != null) {
          writer.append(previousRecord);
        }
        GenericRecord nextRecord = new GenericData.Record(record.getSchema());
        record.put("next", nextRecord);
        previousRecord = record;
      }
      writer.append(previousRecord);
    } finally {
      writer.close();
    }

    return file.getAbsolutePath();
  }

  public static AvroTestRecordWriter generateStringAndUtf8Data() throws Exception {

    final Schema schema = SchemaBuilder.record("AvroRecordReaderTest")
            .namespace("org.apache.drill.exec.store.avro")
            .fields()
            .name("a_string").type().stringBuilder().prop("avro.java.string", "String").endString().noDefault()
            .name("b_utf8").type().stringType().noDefault()
            .endRecord();

    final File file = File.createTempFile("avro-primitive-test", ".avro");
    file.deleteOnExit();

    final AvroTestRecordWriter record = new AvroTestRecordWriter(schema, file);
    try {

      ByteBuffer bb = ByteBuffer.allocate(1);
      bb.put(0, (byte) 1);

      for (int i = 0; i < RECORD_COUNT; i++) {
        record.startRecord();
        record.put("a_string", "a_" + i);
        record.put("b_utf8", "b_" + i);
        record.endRecord();
      }
    } finally {
      record.close();
    }

    return record;
  }
}


text:
Learning Golang(https://golang.org/) for api implementation and ReactJS(https://facebook.github.io/react/) for frontend implementation

# Development env
### setup and build docker containers
1. Setup docker(https://www.docker.com/) and docker-compose(https://docs.docker.com/compose/)
1. Run `cp docker-compose.local.yml docker-compose.override.yml`
1. Run `docker-compose build`
1. Run `docker-compose up -d`

### env and config files
1. Run `cp .env.example .env`
2. Modify `.env` file as you wish
2. Run `mkdir server/settings/secret && cd server/settings/secret`
2. Run `openssl genrsa -out jwt.rsa 1024`
2. Run `openssl rsa -in jwt.rsa -pubout > jwt.rsa.pub`
2. Run `cd ../../..`

### run docker container for compiling and running of server
1. Run `docker-compose exec server bash`
3. Run `go get -u github.com/govend/govend` to install package manager
3. Run `govend -v` to download dependencies

### develoment server cycle commands
1. Run `go install` for compiling and installing of server in docker container
4. Run `server` for starting of server

redpajama_set_name: RedPajamaGithub


text:
<?php

declare(strict_types = 1);

namespace KoolKode\Async;

/**
 * Custom SPL classloader that can load optimized implementations based on KOOLKODE_ASYNC_OPTIMIZATIONS constant values.
 *
 * @codeCoverageIgnore
 *
 * @author Martin Schröder
 */
final class OptimizationLoader
{
    /**
     * Registered class replacements.
     *
     * @var array
     */
    private static $replacements = [];

    /**
     * Register an optimized version of a class.
     *
     * @param string $key Name being used to activate the optimization in KOOLKODE_ASYNC_OPTIMIZATIONS.
     * @param string $typeName Name of the class to be replaced.
     * @param string $optimizedType Name of the optimized replacement class.
     */
    public static function optimize(string $key, string $typeName, string $optimizedType): void
    {
        self::$replacements[$typeName][$key] = $optimizedType;
    }

    /**
     * Register the loader as SPL classloader.
     */
    public static function register(): void
    {
        \spl_autoload_register([
            static::class,
            'autoload'
        ], false, true);
    }

    /**
     * Triggered by SPL autoload when a class needs to be loaded.
     */
    public static function autoload(string $typeName): bool
    {
        static $enabled;

        if (\defined('KOOLKODE_ASYNC_OPTIMIZATIONS')) {
            if ($enabled === null) {
                $enabled = \array_map('trim', \explode(',', \strtolower(\KOOLKODE_ASYNC_OPTIMIZATIONS)));
            }

            if (isset(self::$replacements[$typeName])) {
                foreach ($enabled as $key) {
                    if (isset(self::$replacements[$typeName][$key])) {
                        return \class_alias(self::$replacements[$typeName][$key], $typeName, true);
                    }
                }
            }
        }

        return false;
    }
}


text:
using Leak.Networking.Core;

namespace Leak.Networking.Tests
{
    public class NetworkMemory : NetworkPoolMemory, DataBlockFactory
    {
        public NetworkPoolMemoryBlock Allocate(int size)
        {
            return new NetworkBlock(new byte[size], 0, size);
        }

        public DataBlockFactory AsFactory()
        {
            return this;
        }

        public DataBlock Transcient(byte[] data, int offset, int count)
        {
            return new NetworkBlock(data, offset, count);
        }

        public DataBlock Pooled(int size, DataBlockCallback callback)
        {
            byte[] data = new byte[size];
            DataBlock block = new NetworkBlock(data, 0, size);

            callback?.Invoke(data, 0, size);
            return block;
        }
    }
}


text:
function menu_checked_postset(src,eventdata)
%menu_checked_postset  PostSet event handler for linked QUATTRO WW/WL menus
%
%   menu_checked_postset(SRC,EVENT)

disp('hi');


text:
require 'ansible/ruby/modules/base'

module Ansible
  module Ruby
    module Modules
      # Manage packages with the I(pacman) package manager, which is used by Arch Linux and its variants.
      class Pacman < Base
        # @return [Array<String>, String, nil] Name or list of names of the packages to install, upgrade, or remove.
        attribute :name
        validates :name, type: TypeGeneric.new(String)

        # @return [:absent, :latest, :present, nil] Desired state of the package.
        attribute :state
        validates :state, expression_inclusion: {:in=>[:absent, :latest, :present], :message=>"%{value} needs to be :absent, :latest, :present"}, allow_nil: true

        # @return [Symbol, nil] When removing a package, also remove its dependencies, provided that they are not required by other packages and were not explicitly installed by a user.
        attribute :recurse
        validates :recurse, type: Symbol

        # @return [Symbol, nil] When removing package - force remove package, without any checks. When update_cache - force redownload repo databases.
        attribute :force
        validates :force, type: Symbol

        # @return [Symbol, nil] Whether or not to refresh the master package lists. This can be run as part of a package installation or as a separate step.
        attribute :update_cache
        validates :update_cache, type: Symbol

        # @return [Symbol, nil] Whether or not to upgrade whole system.
        attribute :upgrade
        validates :upgrade, type: Symbol
      end
    end
  end
end


text:
Make sure these checkboxes are checked before submitting your issue. Thanks you!

* [ ] Don't post questions here. This bugtracker is for issues and feature requests only. Use the [community mailing list](https://groups.google.com/forum/#!forum/gatling) instead.
* Regarding issues:
  * [ ] Check that you can reproduce your issue with latest version of the plugin
  * [ ] Search this bugtracker for any similar issue that might have already been reported (and possibly fixed and available as a SNAPSHOT version)
  * [ ] Provide a way for Gatling To Liferay developers to reproduce your problem, e.g. step-by-step instructions against a public facing website, or a sample application that demonstrates your problem.
* Regarding feature requests:
  * [ ] Explain your use case, not the implementation you have in mind.


text:
// Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chromecast/media/audio/mixer_service/output_stream_connection.h"

#include <limits>
#include <utility>

#include "base/logging.h"
#include "base/memory/aligned_memory.h"
#include "chromecast/media/audio/mixer_service/mixer_service_transport.pb.h"
#include "chromecast/media/audio/net/common.pb.h"
#include "chromecast/media/audio/net/conversions.h"
#include "chromecast/net/io_buffer_pool.h"

namespace chromecast {
namespace media {
namespace mixer_service {

namespace {

int GetFrameSize(const OutputStreamParams& params) {
  return audio_service::GetSampleSizeBytes(params.sample_format()) *
         params.num_channels();
}

int GetFillSizeFrames(const OutputStreamParams& params) {
  if (params.has_fill_size_frames()) {
    return params.fill_size_frames();
  }
  // Use 10 ms by default.
  return params.sample_rate() / 100;
}

enum MessageTypes : int {
  kInitial = 1,
  kStartTimestamp,
  kPlaybackRate,
  kAudioClockRate,
  kStreamVolume,
  kPauseResume,
  kEndOfStream,
  kTimestampAdjustment,
};

}  // namespace

OutputStreamConnection::OutputStreamConnection(Delegate* delegate,
                                               const OutputStreamParams& params)
    : delegate_(delegate),
      params_(std::make_unique<OutputStreamParams>(params)),
      frame_size_(GetFrameSize(params)),
      fill_size_frames_(GetFillSizeFrames(params)),
      buffer_pool_(base::MakeRefCounted<IOBufferPool>(
          MixerSocket::kAudioMessageHeaderSize +
              fill_size_frames_ * frame_size_,
          std::numeric_limits<size_t>::max(),
          true /* threadsafe */)),
      audio_buffer_(buffer_pool_->GetBuffer()) {
  DCHECK(delegate_);
  DCHECK_GT(params_->sample_rate(), 0);
  DCHECK_GT(params_->num_channels(), 0);
  params_->set_fill_size_frames(fill_size_frames_);
}

OutputStreamConnection::~OutputStreamConnection() = default;

void OutputStreamConnection::Connect() {
  MixerConnection::Connect();
}

void OutputStreamConnection::SendNextBuffer(int filled_frames, int64_t pts) {
  SendAudioBuffer(std::move(audio_buffer_), filled_frames, pts);
  audio_buffer_ = buffer_pool_->GetBuffer();
}

void OutputStreamConnection::SendAudioBuffer(
    scoped_refptr<net::IOBuffer> audio_buffer,
    int filled_frames,
    int64_t pts) {
  if (!socket_) {
    LOG(INFO) << "Tried to send buffer without a connection";
    return;
  }
  if (sent_eos_) {
    // Don't send any more data after the EOS buffer.
    return;
  }

  if (filled_frames == 0) {
    // Send explicit end-of-stream message.
    sent_eos_ = true;
    Generic message;
    message.mutable_eos_played_out();
    socket_->SendProto(kEndOfStream, message);
    return;
  }
  if (socket_->SendAudioBuffer(std::move(audio_buffer),
                               filled_frames * frame_size_, pts)) {
    LOG_IF(INFO, dropping_audio_) << "Stopped dropping audio";
    dropping_audio_ = false;
  } else {
    LOG_IF(WARNING, !dropping_audio_) << "Dropping audio";
    dropping_audio_ = true;
  }
}

void OutputStreamConnection::SetVolumeMultiplier(float multiplier) {
  volume_multiplier_ = multiplier;
  if (socket_) {
    Generic message;
    message.mutable_set_stream_volume()->set_volume(multiplier);
    socket_->SendProto(kStreamVolume, message);
  }
}

void OutputStreamConnection::SetStartTimestamp(int64_t start_timestamp,
                                               int64_t pts) {
  start_timestamp_ = start_timestamp;
  start_pts_ = pts;

  if (socket_) {
    Generic message;
    message.mutable_set_start_timestamp()->set_start_timestamp(start_timestamp);
    message.mutable_set_start_timestamp()->set_start_pts(pts);
    socket_->SendProto(kStartTimestamp, message);
  }
}

void OutputStreamConnection::SetPlaybackRate(float playback_rate) {
  playback_rate_ = playback_rate;
  if (socket_) {
    Generic message;
    message.mutable_set_playback_rate()->set_playback_rate(playback_rate);
    socket_->SendProto(kPlaybackRate, message);
  }
}

void OutputStreamConnection::SetAudioClockRate(double rate) {
  audio_clock_rate_ = rate;
  if (socket_) {
    Generic message;
    message.mutable_set_audio_clock_rate()->set_rate(rate);
    socket_->SendProto(kAudioClockRate, message);
  }
}

void OutputStreamConnection::Pause() {
  paused_ = true;
  if (socket_) {
    Generic message;
    message.mutable_set_paused()->set_paused(true);
    socket_->SendProto(kPauseResume, message);
  }
}

void OutputStreamConnection::Resume() {
  paused_ = false;
  if (socket_) {
    Generic message;
    auto* pause_message = message.mutable_set_paused();
    pause_message->set_paused(false);
    socket_->SendProto(kPauseResume, message);
  }
}

void OutputStreamConnection::SendTimestampAdjustment(
    int64_t timestamp_adjustment) {
  if (socket_) {
    Generic message;
    auto* adjustment_message = message.mutable_timestamp_adjustment();
    adjustment_message->set_adjustment(timestamp_adjustment);
    socket_->SendProto(kTimestampAdjustment, message);
  }
}

void OutputStreamConnection::OnConnected(std::unique_ptr<MixerSocket> socket) {
  socket_ = std::move(socket);
  socket_->SetDelegate(this);

  Generic message;
  *(message.mutable_output_stream_params()) = *params_;
  if (start_timestamp_ != INT64_MIN) {
    message.mutable_set_start_timestamp()->set_start_timestamp(
        start_timestamp_);
    message.mutable_set_start_timestamp()->set_start_pts(start_pts_);
  }
  if (playback_rate_ != 1.0f) {
    message.mutable_set_playback_rate()->set_playback_rate(playback_rate_);
  }
  if (audio_clock_rate_ != 1.0) {
    message.mutable_set_audio_clock_rate()->set_rate(audio_clock_rate_);
  }
  if (volume_multiplier_ != 1.0f) {
    message.mutable_set_stream_volume()->set_volume(volume_multiplier_);
  }
  if (paused_) {
    message.mutable_set_paused()->set_paused(true);
  }
  socket_->SendProto(kInitial, message);
  delegate_->FillNextBuffer(
      audio_buffer_->data() + MixerSocket::kAudioMessageHeaderSize,
      fill_size_frames_, std::numeric_limits<int64_t>::min(), 0);
}

void OutputStreamConnection::OnConnectionError() {
  socket_.reset();
  if (sent_eos_) {
    delegate_->OnEosPlayed();
    return;
  }
  MixerConnection::Connect();
}

bool OutputStreamConnection::HandleMetadata(const Generic& message) {
  if (message.has_eos_played_out()) {
    delegate_->OnEosPlayed();
    return true;
  }

  if (message.has_push_result() && !sent_eos_) {
    delegate_->FillNextBuffer(
        audio_buffer_->data() + MixerSocket::kAudioMessageHeaderSize,
        fill_size_frames_, message.push_result().delay_timestamp(),
        message.push_result().delay());
  }

  if (message.has_ready_for_playback()) {
    delegate_->OnAudioReadyForPlayback(
        message.ready_for_playback().delay_microseconds());
  }

  if (message.has_error()) {
    delegate_->OnMixerError();
  }

  if (message.has_mixer_underrun()) {
    delegate_->OnMixerUnderrun(static_cast<Delegate::MixerUnderrunType>(
        message.mixer_underrun().type()));
  }
  return true;
}

}  // namespace mixer_service
}  // namespace media
}  // namespace chromecast


text:
// Copyright © 2013 onwards, Andrew Whewell
// All rights reserved.
//
// Redistribution and use of this software in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
//    * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
//    * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
//    * Neither the name of the author nor the names of the program's contributors may be used to endorse or promote products derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OF THE SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Test.Framework;
using VirtualRadar.Interface;

namespace Test.VirtualRadar.Interface
{
    [TestClass]
    public class FilterBoolTests
    {
        [TestMethod]
        public void FilterBool_Constructor_Initialises_To_Known_State_And_Properties_Work()
        {
            var filter = new FilterBool();
            TestUtilities.TestProperty(filter, r => r.Condition, FilterCondition.Invalid, FilterCondition.Equals);
            TestUtilities.TestProperty(filter, r => r.ReverseCondition, false);
            TestUtilities.TestProperty(filter, r => r.Value, false);

            filter = new FilterBool(true);
            TestUtilities.TestProperty(filter, r => r.Condition, FilterCondition.Equals, FilterCondition.Between);
            TestUtilities.TestProperty(filter, r => r.ReverseCondition, false);
            TestUtilities.TestProperty(filter, r => r.Value, true);
        }

        [TestMethod]
        public void FilterBool_Passes_Returns_Correct_Results()
        {
            foreach(FilterCondition condition in Enum.GetValues(typeof(FilterCondition))) {
                foreach(var reverseCondition in new bool[] { false, true }) {
                    foreach(var value in new bool[] { false, true }) {
                        foreach(var testValue in new bool?[] { null, false, true }) {
                            var filter = new FilterBool() {
                                Condition = condition,
                                ReverseCondition = reverseCondition,
                                Value = value
                            };

                            var result = filter.Passes(testValue);

                            var expectedResult = true;
                            if(condition == FilterCondition.Equals) {
                                expectedResult = testValue == null ? false : value == testValue;
                                if(reverseCondition) expectedResult = !expectedResult;
                            }

                            Assert.AreEqual(expectedResult, result, "{0}/{1}/{2}/{3}", condition, reverseCondition, value, testValue);
                        }
                    }
                }
            }
        }
    }
}


text:
#pragma once
#include <aws/ecs/ECS_EXPORTS.h>
#include <aws/ecs/ECSRequest.h>
#include <aws/core/utils/memory/stl/AWSVector.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/ecs/model/CapacityProviderField.h>
#include <utility>

namespace Aws
{
namespace ECS
{
namespace Model
{

  /**
   */
  class AWS_ECS_API DescribeCapacityProvidersRequest : public ECSRequest
  {
  public:
    DescribeCapacityProvidersRequest();

    // Service request name is the Operation name which will send this request out,
    // each operation should has unique request name, so that we can get operation's name from this request.
    // Note: this is not true for response, multiple operations may have the same response name,
    // so we can not get operation's name from response.
    inline virtual const char* GetServiceRequestName() const override { return "DescribeCapacityProviders"; }

    Aws::String SerializePayload() const override;

    Aws::Http::HeaderValueCollection GetRequestSpecificHeaders() const override;

    /**
     *
The short name or full Amazon Resource Name (ARN) of one or more capacity
     * providers. Up to 100 capacity providers can be described in an
     * action.

     */
    inline const Aws::Vector<Aws::String>& GetCapacityProviders() const{ return m_capacityProviders; }

    /**
     *
The short name or full Amazon Resource Name (ARN) of one or more capacity
     * providers. Up to 100 capacity providers can be described in an
     * action.

     */
    inline bool CapacityProvidersHasBeenSet() const { return m_capacityProvidersHasBeenSet; }

    /**
     *
The short name or full Amazon Resource Name (ARN) of one or more capacity
     * providers. Up to 100 capacity providers can be described in an
     * action.

     */
    inline void SetCapacityProviders(const Aws::Vector<Aws::String>& value) { m_capacityProvidersHasBeenSet = true; m_capacityProviders = value; }

    /**
     *
The short name or full Amazon Resource Name (ARN) of one or more capacity
     * providers. Up to 100 capacity providers can be described in an
     * action.

     */
    inline void SetCapacityProviders(Aws::Vector<Aws::String>&& value) { m_capacityProvidersHasBeenSet = true; m_capacityProviders = std::move(value); }

    /**
     *
The short name or full Amazon Resource Name (ARN) of one or more capacity
     * providers. Up to 100 capacity providers can be described in an
     * action.

     */
    inline DescribeCapacityProvidersRequest& WithCapacityProviders(const Aws::Vector<Aws::String>& value) { SetCapacityProviders(value); return *this;}

    /**
     *
The short name or full Amazon Resource Name (ARN) of one or more capacity
     * providers. Up to 100 capacity providers can be described in an
     * action.

     */
    inline DescribeCapacityProvidersRequest& WithCapacityProviders(Aws::Vector<Aws::String>&& value) { SetCapacityProviders(std::move(value)); return *this;}

    /**
     *
The short name or full Amazon Resource Name (ARN) of one or more capacity
     * providers. Up to 100 capacity providers can be described in an
     * action.

     */
    inline DescribeCapacityProvidersRequest& AddCapacityProviders(const Aws::String& value) { m_capacityProvidersHasBeenSet = true; m_capacityProviders.push_back(value); return *this; }

    /**
     *
The short name or full Amazon Resource Name (ARN) of one or more capacity
     * providers. Up to 100 capacity providers can be described in an
     * action.

     */
    inline DescribeCapacityProvidersRequest& AddCapacityProviders(Aws::String&& value) { m_capacityProvidersHasBeenSet = true; m_capacityProviders.push_back(std::move(value)); return *this; }

    /**
     *
The short name or full Amazon Resource Name (ARN) of one or more capacity
     * providers. Up to 100 capacity providers can be described in an
     * action.

     */
    inline DescribeCapacityProvidersRequest& AddCapacityProviders(const char* value) { m_capacityProvidersHasBeenSet = true; m_capacityProviders.push_back(value); return *this; }

    /**
     *
Specifies whether or not you want to see the resource tags for the capacity
     * provider. If TAGS is specified, the tags are included in the
     * response. If this field is omitted, tags aren't included in the response.

     */
    inline const Aws::Vector<CapacityProviderField>& GetInclude() const{ return m_include; }

    /**
     *
Specifies whether or not you want to see the resource tags for the capacity
     * provider. If TAGS is specified, the tags are included in the
     * response. If this field is omitted, tags aren't included in the response.

     */
    inline bool IncludeHasBeenSet() const { return m_includeHasBeenSet; }

    /**
     *
Specifies whether or not you want to see the resource tags for the capacity
     * provider. If TAGS is specified, the tags are included in the
     * response. If this field is omitted, tags aren't included in the response.

     */
    inline void SetInclude(const Aws::Vector<CapacityProviderField>& value) { m_includeHasBeenSet = true; m_include = value; }

    /**
     *
Specifies whether or not you want to see the resource tags for the capacity
     * provider. If TAGS is specified, the tags are included in the
     * response. If this field is omitted, tags aren't included in the response.

     */
    inline void SetInclude(Aws::Vector<CapacityProviderField>&& value) { m_includeHasBeenSet = true; m_include = std::move(value); }

    /**
     *
Specifies whether or not you want to see the resource tags for the capacity
     * provider. If TAGS is specified, the tags are included in the
     * response. If this field is omitted, tags aren't included in the response.

     */
    inline DescribeCapacityProvidersRequest& WithInclude(const Aws::Vector<CapacityProviderField>& value) { SetInclude(value); return *this;}

    /**
     *
Specifies whether or not you want to see the resource tags for the capacity
     * provider. If TAGS is specified, the tags are included in the
     * response. If this field is omitted, tags aren't included in the response.

     */
    inline DescribeCapacityProvidersRequest& WithInclude(Aws::Vector<CapacityProviderField>&& value) { SetInclude(std::move(value)); return *this;}

    /**
     *
Specifies whether or not you want to see the resource tags for the capacity
     * provider. If TAGS is specified, the tags are included in the
     * response. If this field is omitted, tags aren't included in the response.

     */
    inline DescribeCapacityProvidersRequest& AddInclude(const CapacityProviderField& value) { m_includeHasBeenSet = true; m_include.push_back(value); return *this; }

    /**
     *
Specifies whether or not you want to see the resource tags for the capacity
     * provider. If TAGS is specified, the tags are included in the
     * response. If this field is omitted, tags aren't included in the response.

     */
    inline DescribeCapacityProvidersRequest& AddInclude(CapacityProviderField&& value) { m_includeHasBeenSet = true; m_include.push_back(std::move(value)); return *this; }

    /**
     *
The maximum number of account setting results returned by
     * DescribeCapacityProviders in paginated output. When this parameter
     * is used, DescribeCapacityProviders only returns
     * maxResults results in a single page along with a
     * nextToken response element. The remaining results of the initial
     * request can be seen by sending another DescribeCapacityProviders
     * request with the returned nextToken value. This value can be
     * between 1 and 10. If this parameter is not used, then
     * DescribeCapacityProviders returns up to 10 results and a
     * nextToken value if applicable.

     */
    inline int GetMaxResults() const{ return m_maxResults; }

    /**
     *
The maximum number of account setting results returned by
     * DescribeCapacityProviders in paginated output. When this parameter
     * is used, DescribeCapacityProviders only returns
     * maxResults results in a single page along with a
     * nextToken response element. The remaining results of the initial
     * request can be seen by sending another DescribeCapacityProviders
     * request with the returned nextToken value. This value can be
     * between 1 and 10. If this parameter is not used, then
     * DescribeCapacityProviders returns up to 10 results and a
     * nextToken value if applicable.

     */
    inline bool MaxResultsHasBeenSet() const { return m_maxResultsHasBeenSet; }

    /**
     *
The maximum number of account setting results returned by
     * DescribeCapacityProviders in paginated output. When this parameter
     * is used, DescribeCapacityProviders only returns
     * maxResults results in a single page along with a
     * nextToken response element. The remaining results of the initial
     * request can be seen by sending another DescribeCapacityProviders
     * request with the returned nextToken value. This value can be
     * between 1 and 10. If this parameter is not used, then
     * DescribeCapacityProviders returns up to 10 results and a
     * nextToken value if applicable.

     */
    inline void SetMaxResults(int value) { m_maxResultsHasBeenSet = true; m_maxResults = value; }

    /**
     *
The maximum number of account setting results returned by
     * DescribeCapacityProviders in paginated output. When this parameter
     * is used, DescribeCapacityProviders only returns
     * maxResults results in a single page along with a
     * nextToken response element. The remaining results of the initial
     * request can be seen by sending another DescribeCapacityProviders
     * request with the returned nextToken value. This value can be
     * between 1 and 10. If this parameter is not used, then
     * DescribeCapacityProviders returns up to 10 results and a
     * nextToken value if applicable.

     */
    inline DescribeCapacityProvidersRequest& WithMaxResults(int value) { SetMaxResults(value); return *this;}

    /**
     *
The nextToken value returned from a previous paginated
     * DescribeCapacityProviders request where maxResults was
     * used and the results exceeded the value of that parameter. Pagination continues
     * from the end of the previous results that returned the nextToken
     * value.

This token should be treated as an opaque identifier that
     * is only used to retrieve the next items in a list and not for other programmatic
     * purposes.

     */
    inline const Aws::String& GetNextToken() const{ return m_nextToken; }

    /**
     *
The nextToken value returned from a previous paginated
     * DescribeCapacityProviders request where maxResults was
     * used and the results exceeded the value of that parameter. Pagination continues
     * from the end of the previous results that returned the nextToken
     * value.

This token should be treated as an opaque identifier that
     * is only used to retrieve the next items in a list and not for other programmatic
     * purposes.

     */
    inline bool NextTokenHasBeenSet() const { return m_nextTokenHasBeenSet; }

    /**
     *
The nextToken value returned from a previous paginated
     * DescribeCapacityProviders request where maxResults was
     * used and the results exceeded the value of that parameter. Pagination continues
     * from the end of the previous results that returned the nextToken
     * value.

This token should be treated as an opaque identifier that
     * is only used to retrieve the next items in a list and not for other programmatic
     * purposes.

     */
    inline void SetNextToken(const Aws::String& value) { m_nextTokenHasBeenSet = true; m_nextToken = value; }

    /**
     *
The nextToken value returned from a previous paginated
     * DescribeCapacityProviders request where maxResults was
     * used and the results exceeded the value of that parameter. Pagination continues
     * from the end of the previous results that returned the nextToken
     * value.

This token should be treated as an opaque identifier that
     * is only used to retrieve the next items in a list and not for other programmatic
     * purposes.

     */
    inline void SetNextToken(Aws::String&& value) { m_nextTokenHasBeenSet = true; m_nextToken = std::move(value); }

    /**
     *
The nextToken value returned from a previous paginated
     * DescribeCapacityProviders request where maxResults was
     * used and the results exceeded the value of that parameter. Pagination continues
     * from the end of the previous results that returned the nextToken
     * value.

This token should be treated as an opaque identifier that
     * is only used to retrieve the next items in a list and not for other programmatic
     * purposes.

     */
    inline void SetNextToken(const char* value) { m_nextTokenHasBeenSet = true; m_nextToken.assign(value); }

    /**
     *
The nextToken value returned from a previous paginated
     * DescribeCapacityProviders request where maxResults was
     * used and the results exceeded the value of that parameter. Pagination continues
     * from the end of the previous results that returned the nextToken
     * value.

This token should be treated as an opaque identifier that
     * is only used to retrieve the next items in a list and not for other programmatic
     * purposes.

     */
    inline DescribeCapacityProvidersRequest& WithNextToken(const Aws::String& value) { SetNextToken(value); return *this;}

    /**
     *
The nextToken value returned from a previous paginated
     * DescribeCapacityProviders request where maxResults was
     * used and the results exceeded the value of that parameter. Pagination continues
     * from the end of the previous results that returned the nextToken
     * value.

This token should be treated as an opaque identifier that
     * is only used to retrieve the next items in a list and not for other programmatic
     * purposes.

     */
    inline DescribeCapacityProvidersRequest& WithNextToken(Aws::String&& value) { SetNextToken(std::move(value)); return *this;}

    /**
     *
The nextToken value returned from a previous paginated
     * DescribeCapacityProviders request where maxResults was
     * used and the results exceeded the value of that parameter. Pagination continues
     * from the end of the previous results that returned the nextToken
     * value.

This token should be treated as an opaque identifier that
     * is only used to retrieve the next items in a list and not for other programmatic
     * purposes.

     */
    inline DescribeCapacityProvidersRequest& WithNextToken(const char* value) { SetNextToken(value); return *this;}

  private:

    Aws::Vector<Aws::String> m_capacityProviders;
    bool m_capacityProvidersHasBeenSet = false;

    Aws::Vector<CapacityProviderField> m_include;
    bool m_includeHasBeenSet = false;

    int m_maxResults;
    bool m_maxResultsHasBeenSet = false;

    Aws::String m_nextToken;
    bool m_nextTokenHasBeenSet = false;
  };

} // namespace Model
} // namespace ECS
} // namespace Aws


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// Licensed under the MIT license.

#if UNITY_ANDROID
using UnityEngine;

namespace Microsoft.AppCenter.Unity.Internal.Utility
{
    public class JavaNumberHelper
    {
        public static AndroidJavaObject Convert(int val)
        {
            AndroidJavaObject javaInteger = new AndroidJavaObject("java.lang.Integer", val);
            return javaInteger;
        }

        public static AndroidJavaObject Convert(long val)
        {
            AndroidJavaObject javaLong = new AndroidJavaObject("java.lang.Long", val);
            return javaLong;
        }

        public static AndroidJavaObject Convert(float val)
        {
            AndroidJavaObject javaFloat = new AndroidJavaObject("java.lang.Float", val);
            return javaFloat;
        }

        public static AndroidJavaObject Convert(double val)
        {
            AndroidJavaObject javaDouble = new AndroidJavaObject("java.lang.Double", val);
            return javaDouble;
        }

        //TODO how to support decimal?
    }
}
#endif


text:
title: Composite Relations
localeTitle: Relaciones compuestas
---
## Relaciones compuestas

Esto es un talón. [Ayuda a nuestra comunidad a expandirla](https://github.com/freecodecamp/guides/tree/master/src/pages/mathematics/relations/composite-relations/index.md) .

[Esta guía rápida de estilo ayudará a asegurar que su solicitud de extracción sea aceptada](https://github.com/freecodecamp/guides/blob/master/README.md) .

#### Más información:


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.6"/>
<title>nrf51AdvLogger: /home/prithvi/workspace-embedded/nrf51AdvLogger/include/observer.h Source File</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

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

nrf51AdvLogger
    1.0

Main Page

To Do List

Modules

Files

File List

Globals

include

observer.h

Go to the documentation of this file.

    1

   29

   30 /**

   31  * @defgroup adv-observer BLE Observer

   32  * Bluetooth Low Energy advertisement packets observer

   33  * @{

   34  *

   35  * @file

   36  * File to declare the global functions of the BLE observation routine

   37  * @author

   38  * Prithvi

   39  */

   40

   41 #ifndef OBSERVER_H_

   42 #define OBSERVER_H_

   43

   44 /** @brief Initialize the radio peripheral to be used for sniffing advertisement packets.

   45  * The code for this function is modified code from the MIT licensed code from this

   46  * <a href="https://devzone.nordicsemi.com/index.php/broadcaster-observer-low-level-implementation">

   47  * tread of Nordic Developer Zone</a>. */

   48 void obsvr_radio_init(void);

   49 /** Start the packet observation procedure */

   50 void obsvr_begin(void);

   51

   52 #endif /* OBSERVER_H_ */

   53 /**

   54  * @}

   55  */

obsvr_radio_init

void obsvr_radio_init()

Initialize the radio peripheral to be used for sniffing advertisement packets.

Definition: observer.c:380

obsvr_begin

void obsvr_begin()

Start the packet observation procedure.

Definition: observer.c:583

<address class="footer">
Generated on Wed May 21 2014 02:58:43 for nrf51AdvLogger by

 1.8.6
</address>


text:
layout: kanji-remain
v4: 2974
kanji: 薗
keyword: park [alternate]
strokes: 16
on-yomi: エン
permalink: /rtk/薗/
---

## Koohii stories:

1) [Katsuo] 7-10-2007(32): Parks in Japan are designed around water, rocks and trees. A park with flowers is considered to be an alternate park.

2) [blannk] 30-10-2009(6): In the old days parks had more flowers.

3) [mantixen] 2-8-2009(2): One alternate type of park has flowers in it. Some do, some don't.

4) [enryu] 5-9-2009(1): If the park gets full, just use the alternate park you know the one with flowers.

5) [Boy.pockets] 7-3-2011(): Parks in Japan are very conservative. Add flowers and they will call you [alternative].


text:
.tableRow:hover {
  background-color: #eeeeee;
}


text:
package types

// ExtendedStatsAggregation type.
//
// https://github.com/elastic/elasticsearch-specification/blob/4ca0cc05d3ae3fa06c2cd7be91905b656a474334/specification/_types/aggregations/metric.ts#L68-L70
type ExtendedStatsAggregation struct {
	Field   *string  `json:"field,omitempty"`
	Format  *string  `json:"format,omitempty"`
	Missing *Missing `json:"missing,omitempty"`
	Script  *Script  `json:"script,omitempty"`
	Sigma   *float64 `json:"sigma,omitempty"`
}

// NewExtendedStatsAggregation returns a ExtendedStatsAggregation.
func NewExtendedStatsAggregation() *ExtendedStatsAggregation {
	r := &ExtendedStatsAggregation{}

	return r
}


text:
"""
"""

import sys
import pytest
import bitcoin
import logging
import itertools
from binascii import hexlify, unhexlify

from granary.seed import Seed
import granary.seedlib as seedlib
import granary.ssss_wrapper as ssss_wrapper
from granary import electrum_v1_mnemonic

logging.basicConfig(level=logging.DEBUG)

seed1 = Seed()
seed2 = Seed()

SEED1_HEX = "1c63b7708849a5050cae9e4648c0a3ba73c9edf3e767a1a5be40280657221392"
SEED1_BIN = unhexlify(SEED1_HEX)
SEED1_FINGERPRINT = "80D246"
SEED1_MNEMONIC = "broccoli buffalo switch awesome olympic little crawl stable edge ecology cigar insane develop want sort undo payment combine mosquito exotic grace much exact execute"
SEED1_HD_ROOT = "xprv9s21ZrQH143K3ZbAyNipHBfPmvYCA53tpu87dyMgb4etKBJMCZHQT3rTYKnxY1q87LSNwBcJnzoTMyJaoTBWcBsZz1GgaQD84WqBEPyJ2ZS"

STRETCH_PASSWORD = "test"

SEED1_STRETCHED_HEX = "2e5780223c84c7da62801c17fe957439bd138a8d2c2e55a491efc0710abbe454"
SEED1_STRETCHED_BIN = unhexlify(SEED1_STRETCHED_HEX)

SEED1_BIN_CORRECT_HEX_SHARES = ['742bbfb654a8a7f49f49e28f2ab5d6296f9708b45899d330e331397793e9b126', 'bff7b85bac16476514e8dff9fcc4984e398e982e856e4e68ccdd7796a19f9637', '06bc4500fb83e7159277cb2bb1145d930b8617a731c33aa0d6794dc9b04d88d9', '284fb7805d6b864603aaa5145026048095bdb91b3e8174d89305ea54c573dc2e', '91044adb0afe26368535b1c61df6c15da7b536928a2c001089a1d00bd4a1c2c0']
SEED1_BIN_CORRECT_BIN_SHARES = [unhexlify(s) for s in SEED1_BIN_CORRECT_HEX_SHARES]
SEED1_BIN_INCORRECT_HEX_SHARES = SEED1_BIN_CORRECT_HEX_SHARES
SEED1_BIN_INCORRECT_HEX_SHARES[0] = 'ff' * 32
SEED1_BIN_INCORRECT_BIN_SHARES = [unhexlify(s) for s in SEED1_BIN_INCORRECT_HEX_SHARES]

SEED2_HEX = "6c0a51772406d63ab43e0d333541ce0378bdd86a891dfc2d432b94ccf5ed0d64"
SEED2_BIN = unhexlify(SEED2_HEX)
SEED2_FINGERPRINT = "0C5D0A"
SEED2_MNEMONIC = "hire family fruit elite hope bubble special script creek present inform alone mesh umbrella pretty casual wire head slab civil soon walk culture matter"
SEED2_ENCRYPTED = unhexlify("8175cd865fa8fe510a83d25aa1eca15ae74a53204dda31332bf5df6a56841c74")
SEED2_HD_ROOT = "xprv9s21ZrQH143K35CcAfAhex5VqGZrLRqcWS89PeQASWPvKipN4p3QB4VV56DMZLCwH5y7t2Mtqs66GJME1gB5ZVekon7rHsR5CLutfvosHSw"

# Test seedlib
def test_constants():
    assert seedlib.PBKDF2_ROUNDS == 200000
    assert seedlib.quorum_shares == 2
    assert seedlib.total_shares == 5

def test_fingerprint():
    assert(seedlib.fingerprint(SEED1_BIN) == SEED1_FINGERPRINT)
    assert(seedlib.fingerprint(SEED2_BIN) == SEED2_FINGERPRINT)

    assert(seedlib.fingerprint('\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00') == "EC37BB")
    assert(seedlib.fingerprint('\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff') == "9C4051")
    assert(seedlib.fingerprint("") == "52B855")

def test_bip39_mnemonic_decode_12_words():
    assert(seedlib.mnemonic_decode("abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about") == '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')

def test_bip39_mnemonic_decode_24_words():
    assert(seedlib.mnemonic_decode("legal winner thank year wave sausage worth useful legal winner thank year wave sausage worth useful legal winner thank year wave sausage worth title") == '\x7f\x7f\x7f\x7f\x7f\x7f\x7f\x7f\x7f\x7f\x7f\x7f\x7f\x7f\x7f\x7f\x7f\x7f\x7f\x7f\x7f\x7f\x7f\x7f\x7f\x7f\x7f\x7f\x7f\x7f\x7f\x7f')

def test_bip39_mnemonic_decode_exception_length():
    with pytest.raises(Exception) as exc:
        seedlib.mnemonic_decode("abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about")
    assert "Unexpected length of mnemonic sentence" in exc.value

def test_bip39_mnemonic_decode_exception_word():
    with pytest.raises(Exception) as exc:
        seedlib.mnemonic_decode("abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon bbq about")
    assert "Unable to map mnemonic word" in exc.value

def test_bip39_mnemonic_decode_exception_checksum():
    with pytest.raises(Exception) as exc:
        seedlib.mnemonic_decode("abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon zoo")
    assert "Mnemonic sentence does not match checksum" in exc.value

def test_electrumv1_mnemonic_encode():
    mnemonic = electrum_v1_mnemonic.mn_encode(SEED1_HEX[:32])
    print mnemonic
    assert mnemonic == ['grief', 'moonlight', 'utter', 'grant', 'enemy', 'unseen', 'upon', 'inch', 'motion', 'connection', 'explain', 'evening']

def test_ssss_combine_unindexed_exception():
    if not ssss_wrapper.ssss_installed():
        return True

    with pytest.raises(Exception) as exc:
        ssss_wrapper.ssss_combine_unindexed(SEED1_BIN_INCORRECT_BIN_SHARES[:2], SEED1_FINGERPRINT)
    assert "Failed to reconstruct key from shares!" in exc.value

def test_ssss_combine_unindexed_permutation():
    if not ssss_wrapper.ssss_installed():
        return True

    for permutation in itertools.permutations(SEED1_BIN_CORRECT_BIN_SHARES, seedlib.total_shares):
        reconstructed_key = ssss_wrapper.ssss_combine_unindexed(permutation, SEED1_FINGERPRINT)
        assert(reconstructed_key == SEED1_BIN)

def test_ssss_split():
    if not ssss_wrapper.ssss_installed():
        return True

    unindexed_binary_shares = ssss_wrapper.ssss_split(SEED1_BIN)
    print [hexlify(s) for s in unindexed_binary_shares]
    assert(len(unindexed_binary_shares) == seedlib.total_shares)
    reconstructed_key = ssss_wrapper.ssss_combine_unindexed(unindexed_binary_shares, SEED1_FINGERPRINT)
    assert(reconstructed_key == SEED1_BIN)

def test_stretching():
    print "Testing key stretching, this may take a while"
    stretched_key = seedlib.stretched_key(SEED1_BIN, STRETCH_PASSWORD)
    assert(stretched_key == SEED1_STRETCHED_BIN)

def test_encryption():
    ciphertext = seedlib.encrypt(SEED2_BIN, SEED1_STRETCHED_BIN)
    assert(ciphertext == SEED2_ENCRYPTED)

def test_decryption():
    plaintext = seedlib.decrypt(SEED2_ENCRYPTED, SEED2_FINGERPRINT, SEED1_STRETCHED_BIN)
    assert(plaintext == SEED2_BIN)

def test_filename_regex():
    filename = seedlib.master_filename_template % SEED2_FINGERPRINT
    extract_fingerprint = seedlib.regex_master_filename_fingerprint.search(filename).groupdict()['fingerprint']
    assert extract_fingerprint == SEED2_FINGERPRINT
    filename = seedlib.seed_filename_template % SEED2_FINGERPRINT
    extract_fingerprint = seedlib.regex_seed_filename_fingerprint.search(filename).groupdict()['fingerprint']
    assert extract_fingerprint == SEED2_FINGERPRINT

#
# test high-level Seed class
#

def test_seed_hex_init():
    seed1.from_hex(SEED1_HEX)
    seed2.from_hex(SEED2_HEX)
    hex_seed1 = seed1.as_hex()
    hex_seed2 = seed2.as_hex()
    assert hex_seed1 == SEED1_HEX
    assert hex_seed2 == SEED2_HEX

def test_seed_fingerprint():
    seed1.from_hex(SEED1_HEX)
    seed2.from_hex(SEED2_HEX)
    assert seed1.fingerprint() == SEED1_FINGERPRINT
    assert seed2.fingerprint() == SEED2_FINGERPRINT
    seed1.from_hex(SEED2_HEX)
    assert seed1.fingerprint() != SEED1_FINGERPRINT

def test_seed_mnemonic():
    seed1.from_hex(SEED1_HEX)
    seed2.from_hex(SEED2_HEX)
    mnemonic1 = seed1.as_mnemonic()
    mnemonic2 = seed2.as_mnemonic()
    print mnemonic1
    print mnemonic2
    assert mnemonic1 == SEED1_MNEMONIC
    assert mnemonic2 == SEED2_MNEMONIC
    seed1.from_mnemonic(mnemonic1)
    seed2.from_mnemonic(mnemonic2)
    assert seed1.fingerprint() == SEED1_FINGERPRINT
    assert seed2.fingerprint() == SEED2_FINGERPRINT

def test_seed_bin_init():
    SEED1_BIN = unhexlify(SEED1_HEX)
    SEED2_BIN = unhexlify(SEED2_HEX)
    seed1.from_bin(SEED1_BIN)
    seed2.from_bin(SEED2_BIN)
    assert seed1.fingerprint() == SEED1_FINGERPRINT
    assert seed2.fingerprint() == SEED2_FINGERPRINT

def test_seed_stretch():
    newseed = seed1.stretched(STRETCH_PASSWORD)
    assert newseed.as_hex() == SEED1_STRETCHED_HEX

def test_seed_as_HD_root():
    seed1.from_hex(SEED1_HEX)
    seed2.from_hex(SEED2_HEX)
    assert seed1.as_HD_root() == SEED1_HD_ROOT
    assert seed2.as_HD_root() == SEED2_HD_ROOT

def test_seed_BIP39_testvector():
    seed1.from_hex("3e141609b97933b66a060dcddc71fad1d91677db872031e85f4c015c5e7e8982")
    assert seed1.as_HD_root() == "xprv9s21ZrQH143K31xupMrCAi6gmQxGTZkY1W9TFaXLVenbdZ84jaYU82Gz7SkjgpV9oidDnYJu1W9SZ3nH35b6eeQirsi2dNmH37d215jjp9s"

def test_bip32_child():
    assert seedlib.bip32_child(SEED1_HD_ROOT, "0") == "xprv9uCvEJUAjfus2cWARqMRrbfrh6MZABFh8QNQ8RFHHKEeM5KXLWAyhS5xkGuyKooTNLGfdEdoxkDvtmjejbqcXU3LasEXNfW5GKxjcGLRkTC"
    assert seedlib.bip32_child(SEED1_HD_ROOT, "0'") == "xprv9uCvEJUK5LSqCFcMSES9umMNgtmezmUKFTFS7Sby2U1moXCmBtASNbhi6qJwivsos2zb6EgD1Gkou4y2nq9LXW25ySgGifLJ5soLBLA6Dqn"
    assert seedlib.bip32_child(SEED1_HD_ROOT, "0'/0") == "xprv9xPSmhRkqkW9Rchsj9nECbVHfAT84D7grszuSzG4HpSwXm2SZ5VvPp5QRqErhLReWBgTMJ9CUvB1t3Up7RfmXFTaiRyYCZhGRF3LANEjrVH"
    assert seedlib.bip32_child(SEED1_HD_ROOT, "44'/0'/0'/0/0") == "xprvA3hjLRaHBoxnpEPzZ1CEA83PFDd6FzVKtH96QGqBU5nCAU5yvovnUyk61kUpNw4U6x4rXTh7JUcRA4zxun4W8Ncbpu7X5UPd8cszNxjarAd"
    assert seedlib.bip32_child(SEED1_HD_ROOT, "44'/0'/0'/0/0") == seedlib.bip32_child(SEED1_HD_ROOT, "44H/0p/0'/0/0")
    try:
        k = seedlib.bip32_child(SEED1_HD_ROOT, "")
    except ValueError:
        pass

if __name__ == '__main__':
    pytest.main('-v')


text:
import os
import sys
import httplib
import unittest

sys.path.append("../..")

readmetext="This directory is the root of the ADMIRAL shared file system.\n"
mountpoint="mountadmiral"
readmefile="ADMIRAL.README"
hostname="zoo-admiral-silk.zoo.ox.ac.uk"

class TestFileAccess(unittest.TestCase):

    def setUp(self):
        #status=os.system('/sbin/mount.cifs //' +hostname+ '/files '+mountpoint+' -o rw,user=test_admiral,password=test_admiral,nounix,forcedirectio')
        status=os.system('/sbin/mount.cifs //' +hostname+ '/files '+mountpoint+' -o rw,user=ChrisHolland,password=Chris-2203,nounix,forcedirectio')
        self.assertEqual(status, 0, 'Mount failure')
        return

    def tearDown(self):
        os.system('/sbin/umount.cifs '+mountpoint)
        return

    # Test cases
    def testNull(self):
        assert (True), "True expected"
        return

    def testReadMe(self):
        # Test assumes ADMIRAL shared file system is mounted at mountpoint
        # Open README file
        f = open(mountpoint+'/'+readmefile)
        assert (f), "README file open failed"
        # Read first line
        l = f.readline()
        # Close file
        f.close()
        # Check first line
        self.assertEqual(l, readmetext, 'Unexpected README content')
        return

    def testCreateFile(self):
        f = open(mountpoint+'/testCreateFile.tmp','w+')
        assert (f), "File creation failed"
        f.write('Test creation of file\n')
        f.close()
        f = open(mountpoint+'/testCreateFile.tmp','r')
        l = f.readline()
        f.close()
        self.assertEqual(l, 'Test creation of file\n', 'Unexpected file content')
        return

    def testUpdateFile(self):
        filename = mountpoint+'/testUpdateFile.tmp'
        f = open(filename,'w+')
        assert (f), "File creation failed"
        f.write('Test creation of file\n')
        f.close()
        f = open(filename,'a+')
        f.write('Test update of file\n')
        f.close()
        f = open(filename,'r')
        l1 = f.readline()
        l2 = f.readline()
        f.close()
        self.assertEqual(l1, 'Test creation of file\n', 'Unexpected file content: l1')
        self.assertEqual(l2, 'Test update of file\n', 'Unexpected file content: l2')
        return

    def testRewriteFile(self):
        filename = mountpoint+'/testRewriteFile.tmp'
        f = open(filename,'w+')
        assert (f), "File creation failed"
        f.write('Test creation of file\n')
        f.close()
        f = open(filename,'w+')
        f.write('Test rewrite of file\n')
        f.close()
        f = open(filename,'r')
        l = f.readline()
        f.close()
        self.assertEqual(l, 'Test rewrite of file\n', 'Unexpected file content')
        return

    def testDeleteFile(self):
        filename1 = mountpoint+'/testCreateFile.tmp'
        filename2 = mountpoint+'/testRewriteFile.tmp'
        filename3 = mountpoint+'/testUpdateFile.tmp'
        # Test and delete first file
        try:
            s = os.stat(filename1)
        except:
            assert (False), "File "+filename1+" not found or other stat error"
        os.remove(filename1)
        try:
            s = os.stat(filename1)
            assert (False), "File "+filename1+" not deleted"
        except:
            pass
        # Test and delete second file
        try:
            s = os.stat(filename2)
        except:
            assert (False), "File "+filename2+" not found or other stat error"
        os.remove(filename2)
        try:
            s = os.stat(filename2)
            assert (False), "File "+filename2+" not deleted"
        except:
            pass
        # Test and delete third file
        try:
            s = os.stat(filename3)
        except:
            assert (False), "File "+filename3+" not found or other stat error"
        os.remove(filename3)
        try:
            s = os.stat(filename3)
            assert (False), "File "+filename3+" not deleted"
        except:
            pass
        return

    def testWebDAVFile(self):
        h1 = httplib.HTTPConnection('zakynthos.zoo.ox.ac.uk')
        h1.request('GET','/webdav')
        res=h1.getresponse()
        authreq = str(res.status) + ' ' + res.reason
        print authreq
        self.assertEqual(authreq, '401 Authorization Required', 'Unexpected response')

        return

    # Sentinel/placeholder tests

    def testUnits(self):
        assert (True)

    def testComponents(self):
        assert (True)

    def testIntegration(self):
        assert (True)

    def testPending(self):
        assert (False), "No pending test"

# Assemble test suite

from MiscLib import TestUtils

def getTestSuite(select="unit"):
    """
    Get test suite

    select  is one of the following:
            "unit"      return suite of unit tests only
            "component" return suite of unit and component tests
            "all"       return suite of unit, component and integration tests
            "pending"   return suite of pending tests
            name        a single named test to be run
    """
    testdict = {
        "unit":
            [ "testUnits"
            , "testNull"
            ],
        "component":
            [ "testComponents"
            , "testReadMe"
            , "testCreateFile"
            , "testRewriteFile"
            , "testUpdateFile"
            , "testDeleteFile"
            , "testWebDAVFile"
            ],
        "integration":
            [ "testIntegration"
            ],
        "pending":
            [ "testPending"
            ]
        }
    return TestUtils.getTestSuite(TestFileAccess, testdict, select=select)

# Run unit tests directly from command line
if __name__ == "__main__":
    TestUtils.runTests("TestFileAccess", getTestSuite, sys.argv)

# End.


text:
from datetime import datetime
from threading import _Timer,Thread,Event
import ctypes as C
from struct import unpack,pack
from lxml import etree
from numpy import pi
from time import sleep

class CustomTimer(_Timer):
    def __init__(self,interval,func,*args,**kwargs):
        super(CustomTimer,self).__init__(interval,func,*args,**kwargs)
        self.name = "timer(%.1f)"%(interval)

class RepeatTimer(Thread):
    def __init__(self, interval, func, args=[], kwargs={}):
        super(RepeatTimer,self).__init__()
        self.interval = interval
        self.func = func
        self.args = args
        self.kwargs = kwargs
        self.event = Event()
        self.event.set()
        self._timer = None
        self.daemon = True
        self.name = "RepeatTimer"

    def run(self):
        self.func(*self.args,**self.kwargs)
        while self.event.is_set():
            self._timer = CustomTimer(self.interval,
                                      self.func,
                                      self.args,
                                      self.kwargs)
            self._timer.start()
            self._timer.join()

    def cancel(self):
        self.event.clear()
        if self._timer is not None:
            self._timer.cancel()

    def trigger(self):
        self.callable(*self.args, **self.kwargs)
        if self._timer is not None:
            self._timer.cancel()

class NestedDict(dict):
    def __missing__(self, key):
        self[key] = NestedDict()
        return self[key]

def gen_xml_element(name,text=None,attributes=None):
    root = etree.Element(name)
    if attributes is not None:
        for key,val in attributes.items():
            root.attrib[key] = val
    if text is not None:
        root.text = text
    return root

def d2r(val):
    return pi*val/180.

def r2d(val):
    return 180.*val/pi

def nb_sleep(duration,ncycle,event):
    for _ in range(ncycle):
        if event.is_set():
            break
        sleep(duration)


text:
"""Type conversions for rdbms.

This module defines a dictionary called 'converters' which provides a mapping
for the encoders and decoders used for type conversion by rdbms.  The type of
key used in the dictionary determines whether the mapping represents an encoder
or decoder.

If the key is a Python type (from the types module) or class, the
mapping represents the callback function that will be used to encode values of
that type or class to a str for use in a database query.  The callback function
should match the following specification:

Encoder
  Args:
    arg: The argument to encode
    conversions_dict: The conversions dictionary that contains the mapping for
      this callback (useful for performing subsequent encodings for sequence
      types).

  Returns:
    The encoded value as a str.

If the key is a JDBC type constant int, the mapping represents the callback
function that will be used to decode values of that JDBC type to its respective
Python type.  The callback function should match the following specification:

Decoder
  Args:
    arg: The argument to decode.

  Returns:
    The decoded value as its appropriate Python type.
"""

import datetime
import decimal
import functools
import types

from google.storage.speckle.proto import jdbc_type

class Blob(str):
  """A blob type, appropriate for storing binary data of any length."""
  pass

def SwallowArgs(func):
  """Decorator to allow a single arg function to accept multiple arguments."""

  @functools.wraps(func)
  def Decorator(arg, *unused_args):
    return func(arg)
  return Decorator

@SwallowArgs
def Any2Str(arg):
  return str(arg)

Thing2Literal = Any2Str

@SwallowArgs
def Bool2Str(arg):
  return str(arg).lower()

@SwallowArgs
def Unicode2Str(arg):
  return arg.encode('utf-8')

@SwallowArgs
def Datetime2Str(arg):
  return ('%d-%02d-%02d %02d:%02d:%02d.%06d' %
          (arg.year, arg.month, arg.day, arg.hour,
           arg.minute, arg.second, arg.microsecond))

@SwallowArgs
def Date2Str(arg):
  return arg.strftime('%Y-%m-%d')

@SwallowArgs
def Time2Str(arg):
  return ('%02d:%02d:%02d.%06d' %
          (arg.hour, arg.minute, arg.second, arg.microsecond))

def Tuple2Str(arg, conversions_dict):
  if len(arg) > 1:
    raise TypeError('tuples of more than 1 element are not supported.')
  arg = arg[0]
  return conversions_dict[type(arg)](arg, conversions_dict)

def Str2Unicode(arg):
  return unicode(arg, 'utf-8')

def _Strptime(arg, strptime_format):
  """Wraps strptime to provide microsecond support on Python 2.5."""
  split_arg = arg.split('.')
  datetime_obj = datetime.datetime.strptime(split_arg[0], strptime_format)
  if len(split_arg) == 2:
    datetime_obj = datetime_obj.replace(microsecond=int(split_arg[1]))
  return datetime_obj

def Str2Date(arg):
  return _Strptime(arg, '%Y-%m-%d').date()

def Str2Time(arg):
  return _Strptime(arg, '%H:%M:%S').time()

def Str2Datetime(arg):
  return _Strptime(arg, '%Y-%m-%d %H:%M:%S')

conversions = {

    types.IntType: Any2Str,
    types.LongType: Any2Str,
    types.FloatType: Any2Str,
    types.TupleType: Tuple2Str,
    types.BooleanType: Bool2Str,
    types.StringType: Any2Str,
    types.UnicodeType: Unicode2Str,
    datetime.date: Date2Str,
    datetime.datetime: Datetime2Str,
    datetime.time: Time2Str,
    Blob: Any2Str,
    decimal.Decimal: Any2Str,

    jdbc_type.BIT: int,
    jdbc_type.SMALLINT: int,
    jdbc_type.INTEGER: int,
    jdbc_type.BIGINT: int,
    jdbc_type.TINYINT: int,
    jdbc_type.REAL: float,
    jdbc_type.DOUBLE: float,
    jdbc_type.NUMERIC: float,
    jdbc_type.DECIMAL: decimal.Decimal,
    jdbc_type.FLOAT: float,
    jdbc_type.CHAR: Str2Unicode,
    jdbc_type.VARCHAR: Str2Unicode,
    jdbc_type.LONGVARCHAR: Str2Unicode,
    jdbc_type.DATE: Str2Date,
    jdbc_type.TIME: Str2Time,
    jdbc_type.TIMESTAMP: Str2Datetime,
    jdbc_type.BINARY: Blob,
    jdbc_type.VARBINARY: Blob,
    jdbc_type.LONGVARBINARY: Blob,
    jdbc_type.BLOB: Blob,
    jdbc_type.CLOB: Str2Unicode,
    jdbc_type.NCLOB: Str2Unicode,
    jdbc_type.NCHAR: Str2Unicode,
    jdbc_type.NVARCHAR: Str2Unicode,
    jdbc_type.LONGNVARCHAR: Str2Unicode,

    jdbc_type.ARRAY: Str2Unicode,
    jdbc_type.NULL: Str2Unicode,
    jdbc_type.OTHER: Str2Unicode,
    jdbc_type.JAVA_OBJECT: Str2Unicode,
    jdbc_type.DISTINCT: Str2Unicode,
    jdbc_type.STRUCT: Str2Unicode,
    jdbc_type.REF: Str2Unicode,
    jdbc_type.DATALINK: Str2Unicode,
    jdbc_type.BOOLEAN: Str2Unicode,
    jdbc_type.ROWID: Str2Unicode,
    jdbc_type.SQLXML: Str2Unicode,
    }


text:
// Copyright 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.native_test;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Process;

import org.chromium.base.CommandLine;
import org.chromium.base.Log;
import org.chromium.base.annotations.JNINamespace;
import org.chromium.base.multidex.ChromiumMultiDexInstaller;
import org.chromium.base.test.util.UrlUtils;
import org.chromium.test.reporter.TestStatusReporter;

import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;

/**
 *  Helper to run tests inside Activity or NativeActivity.
 */
@JNINamespace("testing::android")
public class NativeTest {
    public static final String EXTRA_COMMAND_LINE_FILE =
            "org.chromium.native_test.NativeTest.CommandLineFile";
    public static final String EXTRA_COMMAND_LINE_FLAGS =
            "org.chromium.native_test.NativeTest.CommandLineFlags";
    public static final String EXTRA_RUN_IN_SUB_THREAD =
            "org.chromium.native_test.NativeTest.RunInSubThread";
    public static final String EXTRA_SHARD =
            "org.chromium.native_test.NativeTest.Shard";
    public static final String EXTRA_STDOUT_FILE =
            "org.chromium.native_test.NativeTest.StdoutFile";

    private static final String TAG = "cr_NativeTest";

    private String mCommandLineFilePath;
    private StringBuilder mCommandLineFlags = new StringBuilder();
    private TestStatusReporter mReporter;
    private boolean mRunInSubThread = false;
    private String mStdoutFilePath;

    private static class ReportingUncaughtExceptionHandler
            implements Thread.UncaughtExceptionHandler {

        private TestStatusReporter mReporter;
        private Thread.UncaughtExceptionHandler mWrappedHandler;

        public ReportingUncaughtExceptionHandler(TestStatusReporter reporter,
                Thread.UncaughtExceptionHandler wrappedHandler) {
            mReporter = reporter;
            mWrappedHandler = wrappedHandler;
        }

        @Override
        public void uncaughtException(Thread thread, Throwable ex) {
            mReporter.uncaughtException(Process.myPid(), ex);
            if (mWrappedHandler != null) mWrappedHandler.uncaughtException(thread, ex);
        }
    }

    public void preCreate(Activity activity) {
        ChromiumMultiDexInstaller.install(activity);
    }

    public void postCreate(Activity activity) {
        CommandLine.init(new String[]{});

        parseArgumentsFromIntent(activity, activity.getIntent());
        mReporter = new TestStatusReporter(activity);
        mReporter.testRunStarted(Process.myPid());
        Thread.setDefaultUncaughtExceptionHandler(
                new ReportingUncaughtExceptionHandler(mReporter,
                        Thread.getDefaultUncaughtExceptionHandler()));
    }

    private void parseArgumentsFromIntent(Activity activity, Intent intent) {
        Log.i(TAG, "Extras:");
        Bundle extras = intent.getExtras();
        if (extras != null) {
            for (String s : extras.keySet()) {
                Log.i(TAG, "  %s", s);
            }
        }

        mCommandLineFilePath = intent.getStringExtra(EXTRA_COMMAND_LINE_FILE);
        if (mCommandLineFilePath == null) {
            mCommandLineFilePath = "";
        } else {
            File commandLineFile = new File(mCommandLineFilePath);
            if (!commandLineFile.isAbsolute()) {
                mCommandLineFilePath = Environment.getExternalStorageDirectory() + "/"
                        + mCommandLineFilePath;
            }
            Log.i(TAG, "command line file path: %s", mCommandLineFilePath);
        }

        String commandLineFlags = intent.getStringExtra(EXTRA_COMMAND_LINE_FLAGS);
        if (commandLineFlags != null) mCommandLineFlags.append(commandLineFlags);

        mRunInSubThread = intent.hasExtra(EXTRA_RUN_IN_SUB_THREAD);

        ArrayList<String> shard = intent.getStringArrayListExtra(EXTRA_SHARD);
        if (shard != null) {
            StringBuilder filterFlag = new StringBuilder();
            filterFlag.append("--gtest_filter=");
            for (Iterator<String> test_iter = shard.iterator(); test_iter.hasNext();) {
                filterFlag.append(test_iter.next());
                if (test_iter.hasNext()) {
                    filterFlag.append(":");
                }
            }
            appendCommandLineFlags(filterFlag.toString());
        }

        mStdoutFilePath = intent.getStringExtra(EXTRA_STDOUT_FILE);
    }

    public void appendCommandLineFlags(String flags) {
        mCommandLineFlags.append(" ").append(flags);
    }

    public void postStart(final Activity activity, boolean forceRunInSubThread) {
        final Runnable runTestsTask = new Runnable() {
            @Override
            public void run() {
                runTests(activity);
            }
        };

        if (mRunInSubThread || forceRunInSubThread) {
            // Post a task that posts a task that creates a new thread and runs tests on it.

            // On L and M, the system posts a task to the main thread that prints to stdout
            // from android::Layout (https://goo.gl/vZA38p). Chaining the subthread creation
            // through multiple tasks executed on the main thread ensures that this task
            // runs before we start running tests s.t. its output doesn't interfere with
            // the test output. See crbug.com/678146 for additional context.

            final Handler handler = new Handler();
            final Runnable startTestThreadTask = new Runnable() {
                @Override
                public void run() {
                    new Thread(runTestsTask).start();
                }
            };
            final Runnable postTestStarterTask = new Runnable() {
                @Override
                public void run() {
                    handler.post(startTestThreadTask);
                }
            };
            handler.post(postTestStarterTask);
        } else {
            // Post a task to run the tests. This allows us to not block
            // onCreate and still run tests on the main thread.
            new Handler().post(runTestsTask);
        }
    }

    private void runTests(Activity activity) {
        nativeRunTests(mCommandLineFlags.toString(), mCommandLineFilePath, mStdoutFilePath,
                activity.getApplicationContext(), UrlUtils.getIsolatedTestRoot());
        activity.finish();
        mReporter.testRunFinished(Process.myPid());
    }

    // Signal a failure of the native test loader to python scripts
    // which run tests.  For example, we look for
    // RUNNER_FAILED build/android/test_package.py.
    private void nativeTestFailed() {
        Log.e(TAG, "[ RUNNER_FAILED ] could not load native library");
    }

    private native void nativeRunTests(String commandLineFlags, String commandLineFilePath,
            String stdoutFilePath, Context appContext, String testDataDir);
}


text:
.class Lnet/clickdev/music/adapters/ArtistDetailSongAdapter$ArtistHolder;
.super Lnet/clickdev/music/adapters/DetailSongAdapter$Holder;
.source "ArtistDetailSongAdapter.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Lnet/clickdev/music/adapters/ArtistDetailSongAdapter;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0xa
    name = "ArtistHolder"
.end annotation

# instance fields
.field album:Landroid/widget/TextView;

.field art:Landroid/widget/ImageView;

# direct methods
.method protected constructor <init>(Landroid/view/View;Lnet/clickdev/music/cache/ImageFetcher;)V
    .locals 1
    .param p1, "root"    # Landroid/view/View;
    .param p2, "fetcher"    # Lnet/clickdev/music/cache/ImageFetcher;

    .prologue
    .line 62
    invoke-direct {p0, p1, p2}, Lnet/clickdev/music/adapters/DetailSongAdapter$Holder;-><init>(Landroid/view/View;Lnet/clickdev/music/cache/ImageFetcher;)V

    .line 63
    const v0, 0x7f110005

    invoke-virtual {p1, v0}, Landroid/view/View;->findViewById(I)Landroid/view/View;

    move-result-object v0

    check-cast v0, Landroid/widget/ImageView;

    iput-object v0, p0, Lnet/clickdev/music/adapters/ArtistDetailSongAdapter$ArtistHolder;->art:Landroid/widget/ImageView;

    .line 64
    const v0, 0x7f110054

    invoke-virtual {p1, v0}, Landroid/view/View;->findViewById(I)Landroid/view/View;

    move-result-object v0

    check-cast v0, Landroid/widget/TextView;

    iput-object v0, p0, Lnet/clickdev/music/adapters/ArtistDetailSongAdapter$ArtistHolder;->album:Landroid/widget/TextView;

    .line 65
    return-void
.end method

# virtual methods
.method protected update(Lnet/clickdev/music/model/Song;)V
    .locals 7
    .param p1, "song"    # Lnet/clickdev/music/model/Song;

    .prologue
    .line 68
    iget-object v0, p0, Lnet/clickdev/music/adapters/ArtistDetailSongAdapter$ArtistHolder;->title:Landroid/widget/TextView;

    iget-object v1, p1, Lnet/clickdev/music/model/Song;->mSongName:Ljava/lang/String;

    invoke-virtual {v0, v1}, Landroid/widget/TextView;->setText(Ljava/lang/CharSequence;)V

    .line 69
    iget-object v0, p0, Lnet/clickdev/music/adapters/ArtistDetailSongAdapter$ArtistHolder;->album:Landroid/widget/TextView;

    iget-object v1, p1, Lnet/clickdev/music/model/Song;->mAlbumName:Ljava/lang/String;

    invoke-virtual {v0, v1}, Landroid/widget/TextView;->setText(Ljava/lang/CharSequence;)V

    .line 71
    iget-wide v0, p1, Lnet/clickdev/music/model/Song;->mAlbumId:J

    const-wide/16 v2, 0x0

    cmp-long v0, v0, v2

    if-ltz v0, :cond_0

    .line 72
    iget-object v1, p0, Lnet/clickdev/music/adapters/ArtistDetailSongAdapter$ArtistHolder;->fetcher:Lnet/clickdev/music/cache/ImageFetcher;

    iget-object v2, p1, Lnet/clickdev/music/model/Song;->mArtistName:Ljava/lang/String;

    iget-object v3, p1, Lnet/clickdev/music/model/Song;->mAlbumName:Ljava/lang/String;

    iget-wide v4, p1, Lnet/clickdev/music/model/Song;->mAlbumId:J

    iget-object v6, p0, Lnet/clickdev/music/adapters/ArtistDetailSongAdapter$ArtistHolder;->art:Landroid/widget/ImageView;

    invoke-virtual/range {v1 .. v6}, Lnet/clickdev/music/cache/ImageFetcher;->loadAlbumImage(Ljava/lang/String;Ljava/lang/String;JLandroid/widget/ImageView;)V

    .line 74
    :cond_0
    return-void
.end method