text:
/*
 *  This file is part of the Wayback archival access software
 *   (http://archive-access.sourceforge.net/projects/wayback/).
 *
 *  Licensed to the Internet Archive (IA) by one or more individual
 *  contributors.
 *
 *  The IA licenses this file to You under the Apache License, Version 2.0
 *  (the "License"); you may not use this file except in compliance with
 *  the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package org.archive.wayback.replay.mimetype;

import org.archive.wayback.core.Resource;

/**
 * ContentTypeSniffer looks into capture resource content
 * to determine actual content-type, which take precedence
 * over content-type declared in the HTTP header.
 * @see SelectorReplayRenderer
 */
public interface MimeTypeDetector {
	public String sniff(Resource resource);
}

redpajama_set_name: RedPajamaGithub


text:
package org.apache.hadoop.hbase.types;

import org.apache.hadoop.hbase.util.Order;
import org.apache.hadoop.hbase.util.PositionedByteRange;
import org.apache.yetus.audience.InterfaceAudience;

/**
 * An {@code DataType} that encodes fixed-length values encoded using
 * {@link org.apache.hadoop.hbase.util.Bytes#putBytes(
 * byte[], int, byte[], int, int)}. Intended to make it
 * easier to transition away from direct use of
 * {@link org.apache.hadoop.hbase.util.Bytes}.
 * @see org.apache.hadoop.hbase.util.Bytes#putBytes(byte[], int, byte[], int, int)
 * @see RawBytes
 * @see OrderedBlob
 * @see OrderedBlobVar
 */
@InterfaceAudience.Public
public class RawBytesFixedLength extends FixedLengthWrapper<byte[]> {

  /**
   * Create a {@code RawBytesFixedLength} using the specified {@code order}
   * and {@code length}.
   */
  public RawBytesFixedLength(Order order, int length) {
    super(new RawBytes(order), length);
  }

  /**
   * Create a {@code RawBytesFixedLength} of the specified {@code length}.
   */
  public RawBytesFixedLength(int length) {
    super(new RawBytes(), length);
  }

  /**
   * Read a {@code byte[]} from the buffer {@code src}.
   */
  public byte[] decode(PositionedByteRange src, int length) {
    return ((RawBytes) base).decode(src, length);
  }

  /**
   * Write {@code val} into {@code buff}, respecting {@code offset} and
   * {@code length}.
   */
  public int encode(PositionedByteRange dst, byte[] val, int voff, int vlen) {
    return ((RawBytes) base).encode(dst, val, voff, vlen);
  }
}


text:
## Team Kratos

- **Ivo Paunov** - @Github: [Ivo Paounov](https://github.com/IvoPaunov), @Telerik Academy: [ivo.paunov](https://telerikacademy.com/Users/ivo.paunov)
-  **Veselin Tsvetanov** - @Github: [Veselin Tsvetanov](https://github.com/veselints), @Telerik Academy: [veselints](https://telerikacademy.com/Users/veselints)
-  **Andrey Mitev** - @Github: [Andrey](https://github.com/AndrewMitev), @Telerik Academy: [AndreyMitev93](https://telerikacademy.com/Users/AndreyMitev93)
-  **Ventsislav Ivanov** - @Github: [DJBuro](https://github.com/DJBuro), @Telerik Academy: [ventsislav.a.ivanov](https://telerikacademy.com/Users/ventsislav.a.ivanov)
-  **Tsvetan Razsolkov** - @Github: [Tsvetan Razsolkov](https://github.com/TsvetanRazsolkov), @Telerik Academy: [cecunqk](https://telerikacademy.com/Users/cecunqk)

## [pSher](https://github.com/Kratos-TA/pSher)

[pSher](https://github.com/Kratos-TA/pSher) is a sample photo share system for Telerik Academy Web Services and Cloud Technologies course.
  This application provides functionality for the user to upload hers/his favourites pictures and to share them with other people around the world. All users have their own accounts, can view other users' pictures, leave a comment or like them.

[pSher](https://github.com/Kratos-TA/pSher) provides full support for CRUD operations - some of them: registration, login, showing / creating / updating / deleting / commenting / liking / filtering / searching uploaded images.

**RESTful application powered by:**

- [ASP.NET WebAPI](http://www.asp.net/web-api) - Repository Pattern + Service Pattern + dependency resolver (Ninject)
- [Microsoft SQL Server](http://www.microsoft.com/en-us/server-cloud/products/sql-server/)
- [SammyJS](http://sammyjs.org/)
- [Bootstrap](http://getbootstrap.com/)
- [jQuery](http://jquery.com/)

**APIs:**

- [Pubnub](http://www.pubnub.com/) - Simple and Real-time Communications API
- [GoogleDrive](https://developers.google.com/drive/v2/reference/) - Google Drive file management API

## Entity Relations diagram

## API Methods

##### Users #####
- **api/account/register - POST** - Registers a user.
- **api/account/logout - POST** - Logs user out.
- **api/users/login - POST** - Logs a user in and returns unique user access token.
- **api/users/{name} - GET** - Returns information about the first user with the specified name - id, username, first name, last name, email and a collection of the user's images.
- **api/users/{id} - PUT** - Updates information about the user with corresponding id - first name, last name and/or email address.
- **api/users/{id} - DELETE** - Deletes the user with corresponding id, all of hers/his albums and images(not from the database).

##### Albums #####
- **api/albums/ - GET** - Returns first 10 non-private albums sorted by name.
- **api/albums/{id} - GET** - Returns the album with the corresponding id, if it is not private or is requested by the user that created it. Else returns error message.
- **api/albums/?name=…&user=…&tags=…&page=…&pageSize=…  - GET** - Returns paged non-private albums, according to the specified parameters and ordered by album name.
- **api/albums - POST** - Creates new album.
- **api/albums/{id} - PUT** - Changes the album with the specified id.
- **api/albums/{id} - DELETE** - Deletes the album(not from the database).

##### Comments #####
- **api/comments - POST** - Creates a comment for a specified image from the logged in user.
- **api/comments/{id} - PUT** - Adds like or dislike to a specified comment.
- **api/comments{id} - DELETE** - Deletes the specified comment.

##### Images #####
- **api/images - GET** - Returns first 10 images ordered by date of uploading.
- **api/images/{id} - GET** - Returns the image with the specified id.
- **api/images?name=...&tags=...&page=...&pageSize=... - GET** - Returns paged non-private images, according to the specified parameters and ordered by date of uploading.
- **api/images - POST** - Creates new image.
- **api/images/{id} - PUT** - Receives an image model and updates the coresponding image in the database.
- **api/images/{id} - DELETE** - Deletes the image(not from the database).

##### Marks #####
- **api/marks - POST** - Creates new mark for a specified image with a specified value from the currently logged in user.
- **api/marks/{id} - PUT** - Changes the value of the mark with corresponding id.
- **api/marks/{id} - DELETE** - Deletes the mark with the specified id(not from the database).

## GitHub repository link - [pSher](https://github.com/Kratos-TA/pSher)

## [Original task requirements and description](https://github.com/TelerikAcademy/Web-Services-and-Cloud/tree/master/Teamwork)


text:
var map = L.map('map', {
    crs: L.CRS.Simple
}).setView([-800, 800], 0);

L.tileLayer('', {
    minZoom: 0,
    maxZoom: 2,
    attribution: 'Paradox Interactive / Erkki Mattila',
    tms: true,
    continuousWorld: true
}).addTo(map);

// Mapmode changer, information box

var info = L.control();

info.onAdd = function (map) {
    this._div = L.DomUtil.create('div', 'info');
    this.update();
    return this._div;
};

info.update = function (props, id, culture, religion) {
    this._div.innerHTML = 'What is this thing?

GitHub

Click on a province to zoom in
' + (props ? props.name: "") + '
' + (id ? id: "") + '
' + (culture ? culture: "") + '
' + (religion ? religion:"");
};

var mapmodes = L.control();

var current_mapmode = "religions";

mapmodes.onAdd = function(map) {
    this._div = L.DomUtil.create('div', 'mapmode');
    this.update();
    return this._div;
};

mapmodes.update = function() {
    this._div.innerHTML = '
Map mode

Religions
<button onClick="showReligions()">Religions</button> <button onClick="showCultures()">Cultures</button>';
};

mapmodes.setPosition('bottomright');
mapmodes.addTo(map);
info.addTo(map);

var geojson = L.geoJson(ckii_provdata, {
    style: style_religions,
    onEachFeature: onEachFeature
}).addTo(map);

function showCultures() {
    geojson.setStyle(style_cultures);
    mapmodes._div.childNodes[1].innerHTML = "Cultures"
    current_mapmode = "cultures"
}

function showReligions() {
    geojson.setStyle(style_religions);
    mapmodes._div.childNodes[1].innerHTML = "Religions"
    current_mapmode = "religions"
}

function getCultureColours(n, culture) {
    return n == "" ? "black" :
	culture_colours[culture];
}

function getReligionColours(n, religion) {
    return n == "" ? "black" :
	religion_colours[religion];
}

function style_religions(feature) {
    return {
	fillColor: getReligionColours(feature.properties.name, religions[feature.id]),
        weight: 2,
        opacity: 1,
        color: '#3B3B3B',
        dashArray: '3',
        fillOpacity: 1.0
    };
}

function style_cultures(feature) {
    return {
	fillColor: getCultureColours(feature.properties.name, cultures[feature.id]),
        weight: 2,
        opacity: 1,
        color: '#3B3B3B',
        dashArray: '3',
        fillOpacity: 1.0
    };
}

function highlightFeature(e) {
    var prov = e.target;

    prov.setStyle({
        weight: 2,
        color: 'red',
        dashArray: '',
        fillOpacity: 1
    });

    if (!L.Browser.ie && !L.Browser.opera) {
        prov.bringToFront();
    }
    info.update(prov.feature.properties, prov.feature.id, cultures[prov.feature.id], religions[prov.feature.id]);
}

function resetHighlight(e) {

    var prov = e.target;

    if (current_mapmode == "cultures")
	prov.setStyle(style_cultures(prov.feature));
    else
	prov.setStyle(style_religions(prov.feature));

    info.update();
}

function zoomToFeature(e) {
    map.fitBounds(e.target.getBounds());
}

function onEachFeature(feature, prov) {
    prov.on({
	mouseover: highlightFeature,
	mouseout: resetHighlight,
	click: zoomToFeature
    });
}


text:
package co.cask.cdap.io;

import co.cask.cdap.api.data.schema.Schema;
import co.cask.cdap.api.data.schema.UnsupportedTypeException;
import co.cask.cdap.api.flow.flowlet.StreamEvent;
import co.cask.cdap.common.io.BinaryDecoder;
import co.cask.cdap.common.io.BinaryEncoder;
import co.cask.cdap.internal.io.ASMDatumWriterFactory;
import co.cask.cdap.internal.io.ASMFieldAccessorFactory;
import co.cask.cdap.internal.io.DatumWriter;
import co.cask.cdap.internal.io.ReflectionDatumReader;
import co.cask.cdap.internal.io.ReflectionDatumWriter;
import co.cask.cdap.internal.io.ReflectionSchemaGenerator;
import com.google.common.base.Charsets;
import com.google.common.base.Objects;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.google.common.reflect.TypeToken;
import org.junit.Assert;
import org.junit.Ignore;
import org.junit.Test;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.net.URI;
import java.nio.ByteBuffer;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 *
 */
public class ASMDatumCodecTest {

  private static final ASMDatumWriterFactory DATUM_WRITER_FACTORY
    = new ASMDatumWriterFactory(new ASMFieldAccessorFactory());

  /**
   *
   */
  public enum TestEnum {
    VALUE1, VALUE2, VALUE3, VALUE4
  }

  private <T> Schema getSchema(TypeToken<T> type) throws UnsupportedTypeException {
    return new ReflectionSchemaGenerator().generate(type.getType());
  }

  private <T> DatumWriter<T> getWriter(TypeToken<T> type) throws UnsupportedTypeException {
    Schema schema =  getSchema(type);
    return DATUM_WRITER_FACTORY.create(type, schema);
  }

  @Test
  public void testShort() throws UnsupportedTypeException, IOException {
    TypeToken<Short> type = new TypeToken<Short>() { };
    PipedOutputStream os = new PipedOutputStream();
    PipedInputStream is = new PipedInputStream(os);
    DatumWriter<Short> writer = getWriter(type);
    writer.encode((short) 3000, new BinaryEncoder(os));

    ReflectionDatumReader<Short> reader = new ReflectionDatumReader<>(getSchema(type), type);
    short value = reader.read(new BinaryDecoder(is), getSchema(type));

    Assert.assertEquals((short) 3000, value);
  }

  @Test
  public void testInt() throws UnsupportedTypeException, IOException {
    TypeToken<Integer> type = new TypeToken<Integer>() { };
    PipedOutputStream os = new PipedOutputStream();
    PipedInputStream is = new PipedInputStream(os);
    DatumWriter<Integer> writer = getWriter(type);
    writer.encode(12234234, new BinaryEncoder(os));

    ReflectionDatumReader<Integer> reader = new ReflectionDatumReader<>(getSchema(type), type);
    int value = reader.read(new BinaryDecoder(is), getSchema(type));

    Assert.assertEquals(12234234, value);
  }

  @Test
  public void testDouble() throws UnsupportedTypeException, IOException {
    TypeToken<Double> type = new TypeToken<Double>() { };
    PipedOutputStream os = new PipedOutputStream();
    PipedInputStream is = new PipedInputStream(os);
    DatumWriter<Double> writer = getWriter(type);
    writer.encode(3.14d, new BinaryEncoder(os));

    ReflectionDatumReader<Double> reader = new ReflectionDatumReader<>(getSchema(type), type);
    double value = reader.read(new BinaryDecoder(is), getSchema(type));

    Assert.assertEquals(3.14d, value, 0.000001d);
  }

  @Test
  public void testString() throws UnsupportedTypeException, IOException {
    TypeToken<String> type = new TypeToken<String>() { };
    PipedOutputStream os = new PipedOutputStream();
    PipedInputStream is = new PipedInputStream(os);
    DatumWriter<String> writer = getWriter(type);
    writer.encode("Testing message", new BinaryEncoder(os));

    ReflectionDatumReader<String> reader = new ReflectionDatumReader<>(getSchema(type), type);
    String value = reader.read(new BinaryDecoder(is), getSchema(type));

    Assert.assertEquals("Testing message", value);
  }

  @Test
  public void testUUID() throws UnsupportedTypeException, IOException {
    TypeToken<UUID> type = new TypeToken<UUID>() { };
    PipedOutputStream os = new PipedOutputStream();
    PipedInputStream is = new PipedInputStream(os);
    DatumWriter<UUID> writer = getWriter(type);

    UUID uuid = UUID.randomUUID();
    writer.encode(uuid, new BinaryEncoder(os));

    ReflectionDatumReader<UUID> reader = new ReflectionDatumReader<>(getSchema(type), type);
    UUID value = reader.read(new BinaryDecoder(is), getSchema(type));

    Assert.assertEquals(uuid, value);
  }

  @Test
  public void testEnum() throws UnsupportedTypeException, IOException {
    TypeToken<TestEnum> type = new TypeToken<TestEnum>() { };
    PipedOutputStream os = new PipedOutputStream();
    PipedInputStream is = new PipedInputStream(os);
    DatumWriter<TestEnum> writer = getWriter(type);
    BinaryEncoder encoder = new BinaryEncoder(os);
    writer.encode(TestEnum.VALUE1, encoder);
    writer.encode(TestEnum.VALUE4, encoder);
    writer.encode(TestEnum.VALUE3, encoder);

    ReflectionDatumReader<TestEnum> reader = new ReflectionDatumReader<>(getSchema(type), type);

    TestEnum value = reader.read(new BinaryDecoder(is), getSchema(type));
    Assert.assertEquals(TestEnum.VALUE1, value);

    value = reader.read(new BinaryDecoder(is), getSchema(type));
    Assert.assertEquals(TestEnum.VALUE4, value);

    value = reader.read(new BinaryDecoder(is), getSchema(type));
    Assert.assertEquals(TestEnum.VALUE3, value);
  }

  @Test
  public void testPrimitiveArray() throws IOException, UnsupportedTypeException {
    TypeToken<int[]> type = new TypeToken<int[]>() { };
    PipedOutputStream os = new PipedOutputStream();
    PipedInputStream is = new PipedInputStream(os);

    int[] writeValue = {1, 2, 3, 4, -5, -6, -7, -8};
    DatumWriter<int[]> writer = getWriter(type);
    writer.encode(writeValue, new BinaryEncoder(os));

    ReflectionDatumReader<int[]> reader = new ReflectionDatumReader<>(getSchema(type), type);

    int[] value = reader.read(new BinaryDecoder(is), getSchema(type));
    Assert.assertArrayEquals(writeValue, value);
  }

  @Test
  public void testReferenceArray() throws IOException, UnsupportedTypeException {
    TypeToken<String[]> type = new TypeToken<String[]>() { };
    PipedOutputStream os = new PipedOutputStream();
    PipedInputStream is = new PipedInputStream(os);

    String[] writeValue = new String[] {"1", "2", null, "3"};
    DatumWriter<String[]> writer = getWriter(type);
    writer.encode(writeValue, new BinaryEncoder(os));

    ReflectionDatumReader<String[]> reader = new ReflectionDatumReader<>(getSchema(type), type);

    String[] value = reader.read(new BinaryDecoder(is), getSchema(type));
    Assert.assertArrayEquals(writeValue, value);
  }

  @Test
  public void testList() throws IOException, UnsupportedTypeException {
    TypeToken<List<Long>> type = new TypeToken<List<Long>>() { };
    PipedOutputStream os = new PipedOutputStream();
    PipedInputStream is = new PipedInputStream(os);

    List<Long> writeValue = ImmutableList.of(1L, 10L, 100L, 1000L);
    DatumWriter<List<Long>> writer = getWriter(type);
    writer.encode(writeValue, new BinaryEncoder(os));

    ReflectionDatumReader<List<Long>> reader = new ReflectionDatumReader<>(getSchema(type), type);

    List<Long> value = reader.read(new BinaryDecoder(is), getSchema(type));
    Assert.assertEquals(writeValue, value);
  }

  @Test
  public void testMap() throws IOException, UnsupportedTypeException {
    TypeToken<Map<String, List<String>>> type = new TypeToken<Map<String, List<String>>>() { };
    PipedOutputStream os = new PipedOutputStream();
    PipedInputStream is = new PipedInputStream(os);

    DatumWriter<Map<String, List<String>>> writer = getWriter(type);
    ImmutableMap<String, List<String>> map = ImmutableMap.<String, List<String>>of("k1", Lists.newArrayList("v1"),
                                                                "k2", Lists.newArrayList("v2", null));
    writer.encode(map, new BinaryEncoder(os));

    ReflectionDatumReader<Map<String, List<String>>> reader =
      new ReflectionDatumReader<>(getSchema(type), type);

    Assert.assertEquals(map, reader.read(new BinaryDecoder(is), getSchema(type)));
  }

  @Test
  public void testURI() throws IOException, UnsupportedTypeException {
    TypeToken<List<URI>> type = new TypeToken<List<URI>>() { };
    PipedOutputStream os = new PipedOutputStream();
    PipedInputStream is = new PipedInputStream(os);

    DatumWriter<List<URI>> writer = getWriter(type);
    List<URI> writeValue = ImmutableList.of(URI.create("http://www.abc.com"));
    writer.encode(writeValue, new BinaryEncoder(os));

    ReflectionDatumReader<List<URI>> reader = new ReflectionDatumReader<>(getSchema(type), type);
    Assert.assertEquals(writeValue, reader.read(new BinaryDecoder(is), getSchema(type)));
  }

  private static class Record {
    private int i;
    private String s;
    private List<String> list;
    private TestEnum e;

    Record(int i, String s, List<String> list, TestEnum e) {
      this.i = i;
      this.s = s;
      this.list = list;
      this.e = e;
    }

    @Override
    public boolean equals(Object o) {
      if (this == o) {
        return true;
      }
      if (o == null || getClass() != o.getClass()) {
        return false;
      }

      Record record = (Record) o;

      return i == record.i && e == record.e && list.equals(record.list) && s.equals(record.s);
    }

    @Override
    public int hashCode() {
      return Objects.hashCode(i, s, list, e);
    }
  }

  @Test
  public void testRecord() throws IOException, UnsupportedTypeException {
    TypeToken<Record> type = new TypeToken<Record>() { };
    PipedOutputStream os = new PipedOutputStream();
    PipedInputStream is = new PipedInputStream(os);

    DatumWriter<Record> writer = getWriter(type);
    Record writeValue = new Record(10, "testing", ImmutableList.of("a", "b", "c"), TestEnum.VALUE2);
    writer.encode(writeValue, new BinaryEncoder(os));

    ReflectionDatumReader<Record> reader = new ReflectionDatumReader<>(getSchema(type), type);
    Record value = reader.read(new BinaryDecoder(is), getSchema(type));

    Assert.assertEquals(writeValue, value);
  }

  @Test
  public void testRecordContainer() throws IOException, UnsupportedTypeException {
    TypeToken<List<Record>> type = new TypeToken<List<Record>>() { };
    PipedOutputStream os = new PipedOutputStream();
    PipedInputStream is = new PipedInputStream(os);

    DatumWriter<List<Record>> writer = getWriter(type);
    List<Record> writeValue = ImmutableList.of(
                                  new Record(10, "testing", ImmutableList.of("a", "b", "c"), TestEnum.VALUE2));
    writer.encode(writeValue, new BinaryEncoder(os));

    ReflectionDatumReader<List<Record>> reader = new ReflectionDatumReader<>(getSchema(type), type);
    List<Record> value = reader.read(new BinaryDecoder(is), getSchema(type));

    Assert.assertEquals(writeValue, value);
  }

  @Test
  public void testRecordArray() throws IOException, UnsupportedTypeException {
    TypeToken<Record[][]> type = new TypeToken<Record[][]>() { };
    PipedOutputStream os = new PipedOutputStream();
    PipedInputStream is = new PipedInputStream(os);

    DatumWriter<Record[][]> writer = getWriter(type);
    Record[][] writeValue = new Record[][] {{ new Record(10, "testing",
                                                         ImmutableList.of("a", "b", "c"), TestEnum.VALUE2)}};
    writer.encode(writeValue, new BinaryEncoder(os));

    ReflectionDatumReader<Record[][]> reader = new ReflectionDatumReader<>(getSchema(type), type);
    Record[][] value = reader.read(new BinaryDecoder(is), getSchema(type));

    Assert.assertArrayEquals(writeValue, value);
  }

  /**
   *
   */
  public static final class Node {
    public short data;
    public Short boxedData;
    public Node left;
    public Node right;

    public Node(short data, Node left, Node right) {
      this.data = data;
      this.boxedData = data;
      this.left = left;
      this.right = right;
    }

    @Override
    public boolean equals(Object o) {
      if (this == o) {
        return true;
      }
      if (o == null || getClass() != o.getClass()) {
        return false;
      }

      Node node = (Node) o;

      return data == node.data
               && (left  != null ? left.equals(node.left) : node.left == null)
               && (right != null ? right.equals(node.right) : node.right == null);
    }

    @Override
    public int hashCode() {
      return Objects.hashCode(data, left, right);
    }
  }

  @Test
  public void testTree() throws IOException, UnsupportedTypeException {
    TypeToken<Node> type = new TypeToken<Node>() { };
    PipedOutputStream os = new PipedOutputStream();
    PipedInputStream is = new PipedInputStream(os);

    DatumWriter<Node> writer = getWriter(type);
    Node root = new Node((short) 1,
                         new Node((short) 2, null,
                                  new Node((short) 3, null, null)),
                         new Node((short) 4,
                                  new Node((short) 5, null, null), null));
    writer.encode(root, new BinaryEncoder(os));

    ReflectionDatumReader<Node> reader = new ReflectionDatumReader<>(getSchema(type), type);
    Node value = reader.read(new BinaryDecoder(is), getSchema(type));

    Assert.assertEquals(root, value);
  }

  @Test
  public void testStreamEvent() throws IOException, UnsupportedTypeException {
    TypeToken<StreamEvent> type = new TypeToken<StreamEvent>() { };
    PipedOutputStream os = new PipedOutputStream();
    PipedInputStream is = new PipedInputStream(os);

    DatumWriter<StreamEvent> writer = getWriter(type);
    StreamEvent event = new StreamEvent(ImmutableMap.of("key", "value"),
                                        ByteBuffer.wrap("Testing message".getBytes(Charsets.UTF_8)));
    writer.encode(event, new BinaryEncoder(os));

    ReflectionDatumReader<StreamEvent> reader = new ReflectionDatumReader<>(getSchema(type), type);
    StreamEvent value = reader.read(new BinaryDecoder(is), getSchema(type));

    Assert.assertEquals(event.getHeaders(), value.getHeaders());
    Assert.assertEquals(event.getBody(), value.getBody());
  }

  @Ignore
  @Test
  public void testSpeed() throws UnsupportedTypeException, IOException {
    TypeToken<Node> type = new TypeToken<Node>() { };
    ByteArrayOutputStream os = new ByteArrayOutputStream(1024);

    long startTime;
    long endTime;

    Node writeValue = new Node((short) 1, new Node((short) 2, null, new Node((short) 3, null, null)),
                               new Node((short) 4, new Node((short) 5, null, null), null));

    DatumWriter<Node> writer = getWriter(type);
    startTime = System.nanoTime();
    for (int i = 0; i < 100000; i++) {
      os.reset();
      writer.encode(writeValue, new BinaryEncoder(os));
    }
    endTime = System.nanoTime();
    System.out.println("Time spent: " + TimeUnit.MILLISECONDS.convert(endTime - startTime, TimeUnit.NANOSECONDS));

    ReflectionDatumWriter<Node> datumWriter = new ReflectionDatumWriter<>(getSchema(type));
    startTime = System.nanoTime();
    for (int i = 0; i < 100000; i++) {
      os.reset();
      datumWriter.encode(writeValue, new BinaryEncoder(os));
    }
    endTime = System.nanoTime();
    System.out.println("Time spent: " + TimeUnit.MILLISECONDS.convert(endTime - startTime, TimeUnit.NANOSECONDS));

    writer = getWriter(type);
    startTime = System.nanoTime();
    for (int i = 0; i < 100000; i++) {
      os.reset();
      writer.encode(writeValue, new BinaryEncoder(os));
    }
    endTime = System.nanoTime();
    System.out.println("Time spent: " + TimeUnit.MILLISECONDS.convert(endTime - startTime, TimeUnit.NANOSECONDS));

    datumWriter = new ReflectionDatumWriter<>(getSchema(type));
    startTime = System.nanoTime();
    for (int i = 0; i < 100000; i++) {
      os.reset();
      datumWriter.encode(writeValue, new BinaryEncoder(os));
    }
    endTime = System.nanoTime();
    System.out.println("Time spent: " + TimeUnit.MILLISECONDS.convert(endTime - startTime, TimeUnit.NANOSECONDS));
  }
}


text:
package com.foilen.smalltools.db;

import java.io.File;
import java.io.IOException;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.Consumer;

import javax.annotation.PostConstruct;

import com.foilen.smalltools.hash.HashMd5sum;
import com.foilen.smalltools.reflection.ReflectionTools;
import com.foilen.smalltools.streamwrapper.RenamingOnCloseOutputStreamWrapper;
import com.foilen.smalltools.tools.AbstractBasics;
import com.foilen.smalltools.tools.AssertTools;
import com.foilen.smalltools.tools.FileTools;
import com.foilen.smalltools.tools.JsonTools;
import com.foilen.smalltools.tools.StringTools;
import com.foilen.smalltools.trigger.SmoothTrigger;

/**
 *

 * This is a simple DAO that can contain a single entity and it will be persisted to a single json file. Whenever {@link #save(Object)} is called, it will request the save of the file, but it won't be
 * saved right away to prevent over-usage of the disk. It will save to the file 2 seconds after the last {@link #save(Object)} call or maximum 10 seconds after the first {@link #save(Object)} call .
 *

 *
 *

 * Everytime you retrieve the entity, it will be a clone from the underlying entity. That means you can safely modify a saved or retrieved entity without worrying that it will be modifying the same
 * entity in the database or be modified by any other thread that retrieved it. You need to call {@link #save(Object)} to persist any changes.
 *

 *
 *

 * This DAO is not meant for heavy performance.
 *

 *
 *

 * Every actions are done in a cached in-memory entity to ensure to not over-use the disk for reading.
 *

 *
 * Usage:
 *

 *
Create your entity

 *
Create a DAO for your entity to persist

 *
Instantiate the DAO

 *
Use it

 *

 *
 *

 * // Create your entity
 * public class TestDbEntity {
 *
 *     private String id;
 *     private int number;
 *
 *     public TestDbEntity() {
 *     }
 *
 *     public TestDbEntity(String id, int number) {
 *         this.id = id;
 *         this.number = number;
 *     }
 *
 *     public String getId() {
 *         return id;
 *     }
 *
 *     public int getNumber() {
 *         return number;
 *     }
 *
 *     public void setId(String id) {
 *         this.id = id;
 *     }
 *
 *     public void setNumber(int number) {
 *         this.number = number;
 *     }
 * }
 *
 * // Create a DAO for your entity to persist
 * public static class TestSingleDao extends AbstractSingleJsonFileDao<TestDbEntity> {
 *
 *     private File dbFile;
 *     private File stagingFile;
 *
 *     public TestSingleDao(File dbFile) {
 *         this.dbFile = dbFile;
 *         this.stagingFile = new File(dbFile.getAbsolutePath() + "_tmp");
 *     }
 *
 *     @Override
 *     protected File getFinalFile() {
 *         return dbFile;
 *     }
 *
 *     @Override
 *     protected File getStagingFile() {
 *         return stagingFile;
 *     }
 *
 *     @Override
 *     protected Class<TestDbEntity> getType() {
 *         return TestDbEntity.class;
 *     }
 *
 * }
 *
 * // Instantiate the DAO
 * TestSingleDao dao = new TestSingleDao(dbFile);
 * dao.init(); // Called automatically if DAO is exposed as a Spring Bean
 *
 * // Use it
 * TestDbEntity entity = dao.load();
 * entity.setNumber(10);
 * dao.save(entity);
 *
 * // Use it in a transaction
 * dao.loadInTransaction(entity -> {
 *     entity.setNumber(entity.getNumber() + 1);
 * });
 *

 */
public abstract class AbstractSingleJsonFileDao<T> extends AbstractBasics {

    private String previousMd5sum;
    private T cached;

    private ReentrantLock transactionLock = new ReentrantLock();

    protected Runnable saveToFile = () -> {

        String cachedMd5sum = HashMd5sum.hashString(JsonTools.prettyPrint(cached));

        // Check if content is different
        if (StringTools.safeEquals(previousMd5sum, cachedMd5sum)) {
            logger.debug("Content didn't change. Skipping saving");
            return;
        }

        // Don't save if the content is null
        if (cached == null) {
            logger.debug("Content wasn't loaded yet. Skipping saving");
            return;
        }

        // Save
        logger.debug("Saving to {}", getFinalFile().getAbsolutePath());
        RenamingOnCloseOutputStreamWrapper out = FileTools.createStagingFile(getStagingFile(), getFinalFile(), true);
        try {
            JsonTools.writeToStream(out, cached);
            out.flush();
            out.setDeleteOnClose(false);
            out.close();
            previousMd5sum = cachedMd5sum;
        } catch (IOException e) {
            logger.error("Could not close the staging file {}", getStagingFile().getAbsolutePath(), e);
        }

    };

    private SmoothTrigger saveSmoothTrigger = new SmoothTrigger(2000, 10000, false, saveToFile).start();

    /**
     * Save to the file now.
     */
    public synchronized void flush() {
        saveToFile.run();
    }

    /**
     * Tell which file will contain the data.
     *
     * @return the file
     */
    protected abstract File getFinalFile();

    /**
     * Tell which file will be used as a staging file and be renamed to {@link #getFinalFile()} once well written.
     *
     * @return the file
     */
    protected abstract File getStagingFile();

    /**
     * Tell the type of the entity to load and save.
     *
     * @return the type
     */
    protected abstract Class<T> getType();

    /**
     * Call once before using if you are not using Spring.
     */
    @PostConstruct
    public synchronized void init() {
        Runtime.getRuntime().addShutdownHook(new Thread(() -> flush()));
    }

    /**
     * Get the last saved entity.
     *
     * @return the entity
     */
    public T load() {
        transactionLock.lock();
        try {
            if (cached != null) {
                logger.debug("Return cached");
                return JsonTools.clone(cached);
            }
            if (getFinalFile().exists()) {
                logger.debug("Loading from file");
                String json = FileTools.getFileAsString(getFinalFile());
                cached = JsonTools.readFromString(json, getType());
                if (cached == null) {
                    logger.debug("Loaded null");
                    cached = ReflectionTools.instantiate(getType());
                }
                previousMd5sum = HashMd5sum.hashString(json);
                return JsonTools.clone(cached);
            } else {
                logger.debug("New state");
                cached = ReflectionTools.instantiate(getType());
                return ReflectionTools.instantiate(getType());
            }
        } finally {
            transactionLock.unlock();
        }
    }

    /**
     * Get the last saved entity and keep a lock on it for the execution block. Once the execution completed, it will save the entity unless an exception is thrown.
     *
     * @param execution
     *            what to execute in the transaction. It gets the entity as its parameter
     */
    public void loadInTransaction(Consumer<T> execution) {

        AssertTools.assertFalse(transactionLock.isHeldByCurrentThread(), "Nested transactions are not supported");
        transactionLock.lock();
        try {
            T entity = load();
            execution.accept(entity);
            save(entity);
        } finally {
            transactionLock.unlock();
        }

    }

    /**
     * Persist the entity.
     *
     * @param entity
     *            the entity
     */
    public void save(T entity) {
        transactionLock.lock();
        try {
            cached = JsonTools.clone(entity);
            saveSmoothTrigger.request();
        } finally {
            transactionLock.unlock();
        }
    }

}


text:
SYNONYM

#### According to
Index Fungorum

#### Published in
Cat. Lich. Univers. 2: 417 (1923)

#### Original name
Graphis pallido-ochracea Kremp.

### Remarks
null


text:
package io.undertow.server.handlers.resource;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.nio.ByteBuffer;
import java.nio.file.Path;
import java.util.Date;
import java.util.List;

import io.undertow.UndertowLogger;
import io.undertow.io.IoCallback;
import io.undertow.io.Sender;
import io.undertow.server.HttpServerExchange;
import io.undertow.server.handlers.cache.DirectBufferCache;
import io.undertow.server.handlers.cache.LimitedBufferSlicePool;
import io.undertow.server.handlers.cache.ResponseCachingSender;
import io.undertow.util.DateUtils;
import io.undertow.util.ETag;
import io.undertow.util.MimeMappings;

/**
 * @author Stuart Douglas
 */
public class CachedResource implements Resource {

    private final CacheKey cacheKey;
    private final CachingResourceManager cachingResourceManager;
    private final Resource underlyingResource;
    private final boolean directory;
    private final Date lastModifiedDate;
    private final String lastModifiedDateString;
    private final ETag eTag;
    private final String name;
    private volatile long nextMaxAgeCheck;

    public CachedResource(final CachingResourceManager cachingResourceManager, final Resource underlyingResource, final String path) {
        this.cachingResourceManager = cachingResourceManager;
        this.underlyingResource = underlyingResource;
        this.directory = underlyingResource.isDirectory();
        this.lastModifiedDate = underlyingResource.getLastModified();
        if (lastModifiedDate != null) {
            this.lastModifiedDateString = DateUtils.toDateString(lastModifiedDate);
        } else {
            this.lastModifiedDateString = null;
        }
        this.eTag = underlyingResource.getETag();
        this.name = underlyingResource.getName();
        this.cacheKey = new CacheKey(cachingResourceManager, underlyingResource.getCacheKey());
        if (cachingResourceManager.getMaxAge() > 0) {
            nextMaxAgeCheck = System.currentTimeMillis() + cachingResourceManager.getMaxAge();
        } else {
            nextMaxAgeCheck = -1;
        }
    }

    @Override
    public String getPath() {
        return underlyingResource.getPath();
    }

    @Override
    public Date getLastModified() {
        return lastModifiedDate;
    }

    @Override
    public String getLastModifiedString() {
        return lastModifiedDateString;
    }

    @Override
    public ETag getETag() {
        return eTag;
    }

    @Override
    public String getName() {
        return name;
    }

    @Override
    public boolean isDirectory() {
        return directory;
    }

    @Override
    public List<Resource> list() {
        return underlyingResource.list();
    }

    @Override
    public String getContentType(final MimeMappings mimeMappings) {
        return underlyingResource.getContentType(mimeMappings);
    }

    public void invalidate() {
        final DirectBufferCache dataCache = cachingResourceManager.getDataCache();
        if(dataCache != null) {
            dataCache.remove(cacheKey);
        }
    }

    public boolean checkStillValid() {
        if (nextMaxAgeCheck > 0) {
            long time = System.currentTimeMillis();
            if (time > nextMaxAgeCheck) {
                nextMaxAgeCheck = time + cachingResourceManager.getMaxAge();
                if (!underlyingResource.getLastModified().equals(lastModifiedDate)) {
                    return false;
                }
            }
        }
        return true;
    }

    @Override
    public void serve(final Sender sender, final HttpServerExchange exchange, final IoCallback completionCallback) {
        final DirectBufferCache dataCache = cachingResourceManager.getDataCache();
        if(dataCache == null) {
            underlyingResource.serve(sender, exchange, completionCallback);
            return;
        }

        final DirectBufferCache.CacheEntry existing = dataCache.get(cacheKey);
        final Long length = getContentLength();
        //if it is not eligible to be served from the cache
        if (length == null || length > cachingResourceManager.getMaxFileSize()) {
            underlyingResource.serve(sender, exchange, completionCallback);
            return;
        }
        //it is not cached yet, install a wrapper to grab the data
        if (existing == null || !existing.enabled() || !existing.reference()) {
            Sender newSender = sender;

            final DirectBufferCache.CacheEntry entry;
            if (existing == null) {
                entry = dataCache.add(cacheKey, length.intValue(), cachingResourceManager.getMaxAge());
            } else {
                entry = existing;
            }

            if (entry != null && entry.buffers().length != 0 && entry.claimEnable()) {
                if (entry.reference()) {
                    newSender = new ResponseCachingSender(sender, entry, length);
                } else {
                    entry.disable();
                }
            }
            underlyingResource.serve(newSender, exchange, completionCallback);
        } else {
            //serve straight from the cache
            ByteBuffer[] buffers;
            boolean ok = false;
            try {
                LimitedBufferSlicePool.PooledByteBuffer[] pooled = existing.buffers();
                buffers = new ByteBuffer[pooled.length];
                for (int i = 0; i < buffers.length; i++) {
                    // Keep position from mutating
                    buffers[i] = pooled[i].getResource().duplicate();
                }
                ok = true;
            } finally {
                if (!ok) {
                    existing.dereference();
                }
            }
            sender.send(buffers, new DereferenceCallback(existing, completionCallback));
        }
    }

    @Override
    public Long getContentLength() {
        //we always use the underlying size unless the data is cached in the buffer cache
        //to prevent a mis-match between size on disk and cached size
        final DirectBufferCache dataCache = cachingResourceManager.getDataCache();
        if(dataCache == null) {
            return underlyingResource.getContentLength();
        }
        final DirectBufferCache.CacheEntry existing = dataCache.get(cacheKey);
        if(existing == null || !existing.enabled()) {
            return underlyingResource.getContentLength();
        }
        //we only return the
        return (long)existing.size();
    }

    @Override
    public String getCacheKey() {
        return cacheKey.cacheKey;
    }

    @Override
    public File getFile() {
        return underlyingResource.getFile();
    }

    @Override
    public Path getFilePath() {
        return underlyingResource.getFilePath();
    }

    @Override
    public File getResourceManagerRoot() {
        return underlyingResource.getResourceManagerRoot();
    }

    @Override
    public Path getResourceManagerRootPath() {
        return underlyingResource.getResourceManagerRootPath();
    }

    @Override
    public URL getUrl() {
        return underlyingResource.getUrl();
    }

    private static class DereferenceCallback implements IoCallback {

        private final DirectBufferCache.CacheEntry entry;
        private final IoCallback callback;

        public DereferenceCallback(DirectBufferCache.CacheEntry entry, final IoCallback callback) {
            this.entry = entry;
            this.callback = callback;
        }

        @Override
        public void onComplete(final HttpServerExchange exchange, final Sender sender) {
            try {
                entry.dereference();
            } finally {
                callback.onComplete(exchange, sender);
            }
        }

        @Override
        public void onException(final HttpServerExchange exchange, final Sender sender, final IOException exception) {
            UndertowLogger.REQUEST_IO_LOGGER.ioException(exception);
            try {
                entry.dereference();
            } finally {
                callback.onException(exchange, sender, exception);
            }
        }
    }

    static final class CacheKey {
        final CachingResourceManager manager;
        final String cacheKey;

        CacheKey(CachingResourceManager manager, String cacheKey) {
            this.manager = manager;
            this.cacheKey = cacheKey;
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;

            CacheKey cacheKey1 = (CacheKey) o;

            if (cacheKey != null ? !cacheKey.equals(cacheKey1.cacheKey) : cacheKey1.cacheKey != null) return false;
            if (manager != null ? !manager.equals(cacheKey1.manager) : cacheKey1.manager != null) return false;

            return true;
        }

        @Override
        public int hashCode() {
            int result = manager != null ? manager.hashCode() : 0;
            result = 31 * result + (cacheKey != null ? cacheKey.hashCode() : 0);
            return result;
        }
    }

}


text:
package org.opencb.hpg.bigdata.app.cli.local;

import org.junit.Before;
import org.junit.Test;

import java.net.URISyntaxException;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * Created by jtarraga on 10/01/17.
 */
public class VariantConvertCLITest {

    public Path vcfPath;
    public Path avroPath;
    public Path metaAvroPath;
    public Path parquetPath;
    public Path metaParquetPath;

    @Before
    public void init() throws URISyntaxException {
        String vcfFilename = "../hpg-bigdata-core/src/test/resources/org/opencb/hpg/bigdata/core/utils/VariantContextBlockIteratorTest.vcf";
        //String vcfFilename = "../hpg-bigdata-core/src/test/resources/org/opencb/hpg/bigdata/core/utils/VcfBlockIteratorTest.vcf";
        //String vcfFilename = "../../../data150/vcf/ALL.chr1.phase3_shapeit2_mvncall_integrated_v5a.20130502.genotypes.vcf";
        //String vcfFilename = "../../../data150/vcf/2.vcf";
        //String vcfFilename = "../../../data150/vcf/5k.vcf";
        //String vcfFilename = "../../../data150/vcf/100k.vcf";

        vcfPath = Paths.get(vcfFilename);
        avroPath = Paths.get("/tmp/" + vcfPath.getFileName() + ".avro");
        metaAvroPath = Paths.get(avroPath + ".meta.json");
        parquetPath = Paths.get("/tmp/" + vcfPath.getFileName() + ".parquet");
        metaParquetPath = Paths.get(parquetPath + ".meta.json");

        // Delete output files before testing
        deleteFiles();
    }

    public void deleteFiles() {
        if (avroPath != null) { avroPath.toFile().delete(); }
        if (metaAvroPath != null) { metaAvroPath.toFile().delete(); }
        if (parquetPath != null) { parquetPath.toFile().delete(); }
        if (metaParquetPath != null) { metaParquetPath.toFile().delete(); }
    }

    @Test
    public void vcf2avro() {
        try {
            StringBuilder commandLine = new StringBuilder();
            commandLine.append("variant convert");
            commandLine.append(" --log-level ERROR");
            commandLine.append(" -i ").append(vcfPath);
            commandLine.append(" -o ").append(avroPath);
            commandLine.append(" --to avro");
            commandLine.append(" --dataset test-dataset");
            commandLine.append(" -t 1");

            VariantQueryCLITest.execute(commandLine.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Test
    public void vcf2parquet() {
        try {
            StringBuilder commandLine = new StringBuilder();
            commandLine.append("variant convert");
            commandLine.append(" --log-level ERROR");
            commandLine.append(" -i ").append(vcfPath);
            commandLine.append(" -o ").append(parquetPath);
            commandLine.append(" --to parquet");
            commandLine.append(" --dataset test-dataset");
            commandLine.append(" -t 1");

            VariantQueryCLITest.execute(commandLine.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Test
    public void avro2parquet() {
        try {
            vcf2avro();

            StringBuilder commandLine = new StringBuilder();
            commandLine.append("variant convert");
            commandLine.append(" --log-level ERROR");
            commandLine.append(" -i ").append(avroPath);
            commandLine.append(" -o ").append(parquetPath);
            commandLine.append(" --from avro");
            commandLine.append(" --to parquet");
            commandLine.append(" --dataset test-dataset");
            commandLine.append(" -t 1");

            VariantQueryCLITest.execute(commandLine.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Test
    public void avroAnnotate() {
        try {
            StringBuilder commandLine = new StringBuilder();
            commandLine.append("variant convert");
            commandLine.append(" --log-level ERROR");
            commandLine.append(" -i ").append(vcfPath);
            commandLine.append(" -o ").append(avroPath);
            commandLine.append(" --dataset test-dataset");
            commandLine.append(" --annotate");
            commandLine.append(" -t 1");

            VariantQueryCLITest.execute(commandLine.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Test
    public void avroAnnotateParallel() {
        try {
            StringBuilder commandLine = new StringBuilder();
            commandLine.append("variant convert");
            commandLine.append(" --log-level ERROR");
            commandLine.append(" -i ").append(vcfPath);
            commandLine.append(" -o ").append(avroPath);
            commandLine.append(" --dataset test-dataset");
            commandLine.append(" --annotate");
            commandLine.append(" -t 4");

            VariantQueryCLITest.execute(commandLine.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Test
    public void parquetAnnotate() {
        try {
            StringBuilder commandLine = new StringBuilder();
            commandLine.append("variant convert");
            commandLine.append(" --log-level ERROR");
            commandLine.append(" -i ").append(vcfPath);
            commandLine.append(" -o ").append(parquetPath);
            commandLine.append(" --to parquet");
            commandLine.append(" --dataset test-dataset");
            commandLine.append(" --annotate");

            VariantQueryCLITest.execute(commandLine.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Test
    public void parquetAnnotateParallel() {
        try {
            StringBuilder commandLine = new StringBuilder();
            commandLine.append("variant convert");
            commandLine.append(" --log-level ERROR");
            commandLine.append(" -i ").append(vcfPath);
            commandLine.append(" -o ").append(parquetPath);
            commandLine.append(" --to parquet");
            commandLine.append(" --dataset test-dataset");
            commandLine.append(" --annotate");
            commandLine.append(" -t 4");

            VariantQueryCLITest.execute(commandLine.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}


text:
@interface YTBaseContactViewController ()<UITextFieldDelegate>

@end

@implementation YTBaseContactViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textChanged) name:UITextFieldTextDidChangeNotification object:self.nameField];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textChanged) name:UITextFieldTextDidChangeNotification object:self.phoneField];

    [self addName];
    [self addPhone];
    [self addBtnF];
}

- (void)addName
{
    UIView* view = [[UIView alloc]init];
    view.layer.cornerRadius = 10;
    view.frame = CGRectMake(50, 160, 275, 30);
    //view.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:view];

    // Do any additional setup after loading the view.
    UILabel* nameLabel = [[UILabel alloc]init];
    nameLabel.frame = CGRectMake(0, 0, 51, 30);
    nameLabel.text = @"姓名:";
    [view addSubview:nameLabel];

    self.nameField = [[UITextField alloc]init];

    self.nameField.frame = CGRectMake(51, 0, 224, 30);
    [view addSubview:self.nameField];

    // 设置输入框左边距
    CGRect frame = self.nameField.frame;
    frame.size.width = 8;
    UIView *leftview = [[UIView alloc] initWithFrame:CGRectMake(0, 0, frame.size.width, frame.size.height)];
    self.nameField.leftView = leftview;
    self.nameField.leftViewMode = UITextFieldViewModeAlways;

    self.nameField.layer.borderColor = [[UIColor colorWithRed:51.0 / 255.0 green:215.0 / 255.0 blue:215.0 / 255.0 alpha:1] CGColor];
    self.nameField.layer.borderWidth = 1;
    self.nameField.layer.cornerRadius = 10;
    self.nameField.clearButtonMode = UITextFieldViewModeWhileEditing;
    self.nameField.returnKeyType = UIReturnKeyDone;
    self.nameField.delegate = self;
}

- (void)addPhone
{
    UIView* view = [[UIView alloc]init];
    view.layer.cornerRadius = 10;
    view.frame = CGRectMake(50, 260, 275, 30);
    view.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:view];

    // Do any additional setup after loading the view.
    UILabel* nameLabel = [[UILabel alloc]init];
    nameLabel.frame = CGRectMake(0, 0, 51, 30);
    nameLabel.text = @"号码:";
    [view addSubview:nameLabel];

    self.phoneField = [[UITextField alloc]init];

    self.phoneField.frame = CGRectMake(51, 0, 224, 30);
    [view addSubview:self.phoneField];

    // 设置输入框左边距
    CGRect frame = self.phoneField.frame;
    frame.size.width = 8;
    UIView *leftview = [[UIView alloc] initWithFrame:CGRectMake(0, 0, frame.size.width, frame.size.height)];
    self.phoneField.leftView = leftview;
    self.phoneField.leftViewMode = UITextFieldViewModeAlways;

    self.phoneField.layer.borderColor = [[UIColor colorWithRed:51.0 / 255.0 green:215.0 / 255.0 blue:215.0 / 255.0 alpha:1] CGColor];
    self.phoneField.layer.borderWidth = 1;
    self.phoneField.layer.cornerRadius = 10;
    self.phoneField.clearButtonMode = UITextFieldViewModeWhileEditing;
    self.phoneField.returnKeyType = UIReturnKeyDone;
    self.phoneField.delegate = self;
    self.phoneField.keyboardType = UIKeyboardTypeNumberPad;
}

- (void)addBtnF
{
    self.btn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.btn.frame = CGRectMake(50, 325, 275, 40);
    self.btn.layer.cornerRadius = 10;
    self.btn.enabled = NO;
    [self.btn setBackgroundImage:[UIImage resizableImage:@"navBg"] forState:UIControlStateNormal];
    [self.btn setBackgroundImage:[UIImage resizableImage:@"bg"] forState:UIControlStateHighlighted];
    [self.btn setTitle:@"完成" forState:UIControlStateNormal];
    [self.btn addTarget:self action:@selector(btnClicked) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.btn];

}
- (void)btnClicked
{

}

- (void)textChanged
{
    self.btn.enabled = (self.nameField.text.length && self.phoneField.text.length);
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [self.nameField resignFirstResponder];
    [self.phoneField resignFirstResponder];
    [self.view endEditing:YES];
    return YES;
}

-(void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    if (![self.nameField isExclusiveTouch] && ![self.phoneField isExclusiveTouch]) {
        [self.nameField resignFirstResponder];
        [self.phoneField resignFirstResponder];
        [self.view endEditing:YES];
    }
}

-(void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
@end


text:
// Copyright (c) 2011 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.

using System;
using ICSharpCode.NRefactory.CSharp;
using ICSharpCode.NRefactory.PatternMatching;
using Mono.Cecil;

namespace ICSharpCode.Decompiler.Ast.Transforms
{
	/// <summary>
	/// Transforms decimal constant fields.
	/// </summary>
	public class DecimalConstantTransform : DepthFirstAstVisitor<object, object>, IAstTransform
	{
		static readonly PrimitiveType decimalType = new PrimitiveType("decimal");

		public override object VisitFieldDeclaration(FieldDeclaration fieldDeclaration, object data)
		{
			const Modifiers staticReadOnly = Modifiers.Static | Modifiers.Readonly;
			if ((fieldDeclaration.Modifiers & staticReadOnly) == staticReadOnly && decimalType.IsMatch(fieldDeclaration.ReturnType)) {
				foreach (var attributeSection in fieldDeclaration.Attributes) {
					foreach (var attribute in attributeSection.Attributes) {
						TypeReference tr = attribute.Type.Annotation<TypeReference>();
						if (tr != null && tr.Name == "DecimalConstantAttribute" && tr.Namespace == "System.Runtime.CompilerServices") {
							attribute.Remove();
							if (attributeSection.Attributes.Count == 0)
								attributeSection.Remove();
							fieldDeclaration.Modifiers = (fieldDeclaration.Modifiers & ~staticReadOnly) | Modifiers.Const;
							return null;
						}
					}
				}
			}
			return null;
		}

		public void Run(AstNode compilationUnit)
		{
			compilationUnit.AcceptVisitor(this, null);
		}
	}
}


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
null

#### Original name
Drymophloeus paradoxus Scheff.

### Remarks
null


text:
<template name="adminLayout">
  {{#if Template.subscriptionsReady}}
    {{#if isAdmin}}
      {{>Template.dynamic template=content}}
    {{else}}
      {{>AdminLogin}}
    {{/if}}
  {{else}}
    Loading...
  {{/if}}
</template>


text:
<?php

return [

    'dashboard' => 'Dashboard',

    // Incidents
    'incidents' => [
        'title'                    => 'Incidentes & Agenda',
        'incidents'                => 'Incidentes',
        'logged'                   => '{0} Não existem incidentes, bom trabalho.|Você registrou um incidente.|Você reportou :count incidentes.',
        'incident-create-template' => 'Criar template',
        'incident-templates'       => 'Template de incidentes',
        'add'                      => [
            'title'   => 'Add an Incident',
            'success' => 'Incidente adicionado.',
            'failure' => 'Algo deu errado com o incidente.',
        ],
        'edit' => [
            'title'   => 'Edit an Incident',
            'success' => 'Incidente atualizado.',
            'failure' => 'Algo deu errado com o incidente.',
        ],
        'delete' => [
            'success' => 'The incident has been deleted and will not show on your status page.',
            'failure' => 'The incident could not be deleted. Please try again.',
        ],

        // Incident templates
        'templates' => [
            'title' => 'Template de incidentes',
            'add'   => [
                'title'   => 'Create an Incident Template',
                'message' => 'You should add an Incident Template.',
                'success' => 'Template criado.',
                'failure' => 'Algo deu errado com o template de incidente.',
            ],
            'edit' => [
                'title'   => 'Edit Template',
                'success' => 'Template foi atualizado!',
                'failure' => 'Algo deu errado atualizando o template de incidente',
            ],
            'delete' => [
                'success' => 'The tmplate has been deleted.',
                'failure' => 'The template could not be deleted. Please try again.',
            ],
        ],
    ],

    // Incident Maintenance
    'schedule' => [
        'schedule'     => 'Manutenção Agendada',
        'logged'       => '{0} There are no schedules, good work.|You have logged one schedule.|You have reported :count schedules.',
        'scheduled_at' => 'Agendada em :timestamp',
        'add'          => [
            'title'   => 'Adicionar manutenção programada',
            'success' => 'Agenda adicionada.',
            'failure' => 'Aconteceu algo errado ao adicionar o cronograma.',
        ],
        'edit' => [
            'title'   => 'Editar manutenção programada',
            'success' => 'Agenda foi atualizada!',
            'failure' => 'Aconteceu algo errado ao editar o cronograma.',
        ],
        'delete' => [
            'success' => 'O cronograma foi excluído e não aparecerá na sua página de status.',
            'failure' => 'O cronograma não pôde ser excluído. Por favor, tente novamente.',
        ],
    ],

    // Components
    'components' => [
        'components'         => 'Componentes',
        'component_statuses' => 'Status do componente',
        'listed_group'       => 'Agrupados sob :name',
        'add'                => [
            'title'   => 'Add a Component',
            'message' => 'Você deve adicionar um componente.',
            'success' => 'Componente criado.',
            'failure' => 'Algo deu errado com o componente.',
        ],
        'edit' => [
            'title'   => 'Edit a Component',
            'success' => 'Componente atualizado.',
            'failure' => 'Algo deu errado com o componente.',
        ],
        'delete' => [
            'success' => 'Component deleted.',
            'failure' => 'The Component could not be deleted. Please try again.',
        ],

        // Component groups
        'groups' => [
            'groups'        => 'Grupo de componente|Grupos de componente',
            'no_components' => 'Você deve adicionar um componente à um grupo.',
            'add'           => [
                'title'   => 'Add a Component Group',
                'success' => 'Grupo de componente adicionado.',
                'failure' => 'Algo deu errado com o grupo de componente.',
            ],
            'edit' => [
                'title'   => 'Edit a Component Group',
                'success' => 'Grupo de componentes atualizado.',
                'failure' => 'Algo deu errado com o grupo de componentes.',
            ],
            'delete' => [
                'success' => 'Component Group deleted.',
                'failure' => 'The Component Group could not be deleted. Please try again.',
            ],
        ],
    ],

    // Metrics
    'metrics' => [
        'metrics' => 'Metricas',
        'add'     => [
            'title'   => 'Create a Metric',
            'message' => 'You should add a Metric.',
            'success' => 'Métrica criada.',
            'failure' => 'Algo deu errado com a métrica.',
        ],
        'edit' => [
            'title'   => 'Edit a Metric',
            'success' => 'Métrica atualizada.',
            'failure' => 'Algo deu errado com a métrica.',
        ],
        'delete' => [
            'success' => 'The metric has been deleted and will not show on your status page.',
            'failure' => 'The metric could not be deleted. Please try again.',
        ],
    ],
    // Subscribers
    'subscribers' => [
        'subscribers'  => 'Inscritos',
        'description'  => 'Todos os inscritos receberão atualizações quando novos incidentes forem criados.',
        'verified'     => 'Verificado',
        'not_verified' => 'Não verificado',
        'add'          => [
            'title'   => 'Add a New Subscriber',
            'success' => 'Inscrito adicionado.',
            'failure' => 'Algo deu errado com o componente.',
        ],
        'edit' => [
            'title'   => 'Update Subscriber',
            'success' => 'Inscrito atualizado.',
            'failure' => 'Algo deu errado duante a atualização.',
        ],
    ],

    // Team
    'team' => [
        'team'        => 'Equipe',
        'member'      => 'Membro',
        'profile'     => 'Perfil	',
        'description' => 'Membros da equipe serão capazes de adicionar, modificar & editar componentes e incidentes.',
        'add'         => [
            'title'   => 'Add a New Team Member',
            'success' => 'Membro da equipe adicionado.',
            'failure' => 'Something went wrong with the user.',
        ],
        'edit' => [
            'title'   => 'Update Profile',
            'success' => 'Perfil atualizado.',
            'failure' => 'Algo deu errado duante a atualização.',
        ],
        'delete' => [
            'success' => 'User deleted.',
            'failure' => 'Ocorreu um problema ao excluir esse usuário.',
        ],
        'invite' => [
            'title'   => 'Invite a New Team Member',
            'success' => 'The users invited.',
            'failure' => 'Something went wrong with the invite.',
        ],
    ],

    // Settings
    'settings' => [
        'settings'  => 'Configurações',
        'app-setup' => [
            'app-setup'   => 'Instalação do aplicativo',
            'images-only' => 'Somente imagens podem ser carregadas.',
            'too-big'     => 'O arquivo que você carregou é muito grande. Envie uma imagem inferior à :size',
        ],
        'analytics' => [
            'analytics' => 'Analytics',
        ],
        'localization' => [
            'localization' => 'Localization',
        ],
        'security' => [
            'security'   => 'Segurança',
            'two-factor' => 'Usuários sem autenticação de dois fatores',
        ],
        'stylesheet' => [
            'stylesheet' => 'Folha de estilo',
        ],
        'theme' => [
            'theme' => 'Tema',
        ],
        'edit' => [
            'success' => 'Configurações salvas.',
            'failure' => 'Não foi possível salvar as configurações.',
        ],
    ],

    // Login
    'login' => [
        'login'      => 'Login',
        'logged_in'  => 'Você está logado.',
        'welcome'    => 'Bem-vindo de volta!',
        'two-factor' => 'Por favor insira o seu token.',
    ],

    // Sidebar footer
    'help'        => 'Ajuda',
    'status_page' => 'Página de status',
    'logout'      => 'Sair',

    // Notifications
    'notifications' => [
        'notifications' => 'Notificações',
        'awesome'       => 'Excelente.',
        'whoops'        => 'Opa.',
    ],

    // Welcome modal
    'welcome' => [
        'welcome' => 'Welcome to your status page!',
        'message' => 'Sua página de status está quase pronta! Tavez vocë queira checar essas configurações extras',
        'close'   => 'Basta ir direto para o meu painel de controle',
        'steps'   => [
            'component'  => 'Criar componentes',
            'incident'   => 'Criar incidentes',
            'customize'  => 'Personalizar',
            'team'       => 'Adicionar usuários',
            'api'        => 'Gerar token de API',
            'two-factor' => 'Autenticação em duas etapas',
        ],
    ],

];


text:
using Emc.Documentum.Rest.Net;
using Emc.Documentum.Rest.Http.Utility;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.InteropServices;

namespace Emc.Documentum.Rest.DataModel
{
    /// <summary>
    /// Document resource model
    /// </summary>
    [DataContract(Name = "document", Namespace = "http://identifiers.emc.com/vocab/documentum")]
    [ClassInterface(ClassInterfaceType.AutoDual)]
    public partial class Document : PersistentObject
    {
    }
}


text:
layout: page
title: Syllabus
permalink: /syllabus/
---

## Instructor contact info

Joel Taddei

* Email: joel@theironyard.com
* Phone: (515) 664-2017 -- call after 5 PM for emergencies only

## Schedule

Class is from September 14th to December 11th.

Lecture is from 9 AM to 12:30 PM Monday-Thursday, with breaks during that time. Depending on the topic, we may end
early. We may alter this schedule for particular days and will let you know at least 24 hours ahead of time.

Lab is from 1 PM to 5 PM Monday-Thursday and 9 AM - 5 PM on Friday.

### Office hours and one-on-one instruction

A teacher or TA will be available Monday-Friday from 9 AM to 5 PM at minimum. During lab time, you can schedule
one-on-one time with either of us. After hours, we may be available in the classroom or in Slack, which we use for
group communication.

### Holidays

We will take off `Days to be determined`

## Topics

These topics are listed week-by-week. However, this list is not definitive and we will reorder things based off how
the class is going.

Each list of topics is a list of things students should be comfortable with at the end of that week.

### Week 1

By the end of this week, students should be comfortable with:

* Computational thinking
* Setting up your computer for development
* Data structures
* Control flow
* Organizing Python modules
* Using Git and GitHub to manage source code
* Debugging

### Week 2

* Testing your code
* Higher-order functions
* Recursion
* Exceptions
* Object-oriented programming

### Week 3

* Stochastic programming
* Randomness
* Monte Carlo simulations
* Plotting
* NumPy
* Simple statistics
* Basic statistical inquiry

### Week 4

* Regular expressions
* Loading and manipulating data with pandas
* Common data formats
* Publicly available data sets
* Data set quality
* Cleaning data sets

### Week 5

* Machine learning
* Bayesian statistics and classification
* Clustering

### Week 6

* HTML
* CSS
* Introduction to Django
* Relational databases
* Modeling
* Forms

### Week 7

* Advanced database design
* Deployment
* Building REST APIs

### Week 8

* JavaScript
* Consuming REST APIs
* Data visualization on the Web

### Week 9

This week is a week for review and catch-up. Things will fall through the cracks during the previous 8 weeks, and so
we have this week as a flex week to make sure we cover everything you need.

### Week 10

During this week, you will be pitching your final project ideas, forming groups, and getting feedback. In class,
we will cover some software development principles. You should be comfortable with:

* Breaking up features into distinct tasks to work on
* Estimating the size of programming tasks
* Using Agile development to run a project

### Weeks 11-12

You will be working on your final project and presentation during this time.

## Capstone project

During the last three weeks of the course, you will be working on your capstone project, putting all you've learned
into practice.

You will be working solo or in a group of 2-3 people on your project.

At the end of week 9, you'll present your idea for a final project and get feedback. Not all ideas presented will
become final projects: the projects will be determined by TIY staff after all ideas are presented. During weeks 10, 11
and 12, you'll work primarily on your capstone project.

This project must use Python. It can be a data project, a web project, a systems programming project, or
something else! Because this is a general-purpose programming course, the choices are wide. If you are not working on
a project with a strong visual component, I _highly_ suggest thinking about working with someone from another class to
make your project visual.

## Policies

### Absence policy

You can miss up to 4 lectures; after that, your graduation and enrollment in the job placement program is forfeit.
I don't recommend missing any, as we will be moving very fast.

### Homework policy

Your homework is due by 6 AM on the day it is due. After that, it is late.

I would rather see a solid attempt on time than a complete assignment late. Solid attempts are not considered late.

All homework assigned by your instructor must be completed for graduation.

### Honor code

You are expected to do your own work. You should use all resources available to you, including open-source code, but
copy and pasting open-source code is prohibited: you should use it only for inspiration or as a library in a bigger
project.

Copying homework is taken very seriously and can result in forfeiting job placement or explusion.

## Code of conduct

Like the technical community as a whole, classes at The Iron Yard are made up of a mixture of people from all
different backgrounds.

Diversity is one of our huge strengths, but it can also lead to communication issues. To that end, we have a few
ground rules that we ask people to adhere to when they're taking a class at The Iron Yard. These rules apply equally
to teachers, students, other staff, and guest lecturers.

This isn't an exhaustive list of things that you can't do. Rather, take it in the spirit in which it's intended -
a guide to make it easier to enrich all of us, the technical communities in which we participate.

This code of conduct applies to all communication: this includes in class, Slack, email, and other forums such as
Skype, Google+ Hangouts, etc.

If you believe someone is violating the code of conduct, we ask that you report it by talking to your instructor.
If you do not feel comfortable talking to your instructor, speak with any Iron Yard instructor or staff member.

* **Be welcoming, friendly, and patient.**

* **Be considerate.** Your work will be used by other people, and you in turn will depend on the work of others. Any decision you take will affect your colleagues, and you should take those consequences into account when making decisions.

* **Be respectful.** Not all of us will agree all the time, but disagreement is no excuse for poor behavior and poor manners. We might all experience some frustration now and then, but we cannot allow that frustration to turn into a personal attack. It's important to remember that a community where people feel uncomfortable or threatened is not a productive one. Members of the Iron Yard
community should be respectful when dealing with other members as well as with people outside the Iron Yard community.

* **Be careful in the words that you choose.** Be kind to others. Do not insult or put down other people. Behave professionally. Remember that harassment and sexist, racist, or exclusionary behavior are not appropriate for this class. This includes, but is not limited to:

    * Violent threats or language directed against another person.
    * Sexist, racist, or otherwise discriminatory jokes and language.
    * Posting sexually explicit or violent material.
    * Personal insults, especially those using racist or sexist terms.
    * Unwelcome sexual attention.
    * Advocating for, or encouraging, any of the above behavior.
    *
Repeated harassment of others.
      In general, if someone asks you to stop, then stop.

* **When we disagree, we try to understand why.** Disagreements, both social and technical, happen all the time and The Iron Yard is no exception. It is important that we resolve disagreements and differing views constructively. Remember that we're different. The strength of The Iron Yard comes from its varied members, people from a wide range of backgrounds. Different people have different perspectives on issues. Being unable to understand why someone holds
a viewpoint doesn't mean that they're wrong. Don't forget that it is human to err and blaming each other doesn't get us anywhere, rather offer to help resolving issues and to help learn from mistakes.

*This text is taken from [the Django project](https://www.djangoproject.com/conduct/).*


text:
package com.franktan.popularmovies.data.movie;

import android.database.Cursor;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;

import com.franktan.popularmovies.data.base.AbstractCursor;

/**
 * Cursor wrapper for the {@code movie} table.
 */
@SuppressWarnings("UnnecessaryLocalVariable")
public class MovieCursor extends AbstractCursor implements MovieModel {
    public MovieCursor(Cursor cursor) {
        super(cursor);
    }

    /**
     * Primary key.
     */
    public long getId() {
        Long res = getLongOrNull(MovieColumns._ID);
        if (res == null)
            throw new NullPointerException("The value of '_id' in the database was null, which is not allowed according to the model definition");
        return res;
    }

    /**
     * The id of the movie in MovieDB
     */
    public long getMovieMoviedbId() {
        Long res = getLongOrNull(MovieColumns.MOVIE_MOVIEDB_ID);
        if (res == null)
            throw new NullPointerException("The value of 'movie_moviedb_id' in the database was null, which is not allowed according to the model definition");
        return res;
    }

    /**
     * Get the {@code title} value.
     * Cannot be {@code null}.
     */
    @NonNull
    public String getTitle() {
        String res = getStringOrNull(MovieColumns.TITLE);
        if (res == null)
            throw new NullPointerException("The value of 'title' in the database was null, which is not allowed according to the model definition");
        return res;
    }

    /**
     * Get the {@code backdrop_path} value.
     * Can be {@code null}.
     */
    @Nullable
    public String getBackdropPath() {
        String res = getStringOrNull(MovieColumns.BACKDROP_PATH);
        return res;
    }

    /**
     * Get the {@code original_lan} value.
     * Can be {@code null}.
     */
    @Nullable
    public String getOriginalLan() {
        String res = getStringOrNull(MovieColumns.ORIGINAL_LAN);
        return res;
    }

    /**
     * Get the {@code original_title} value.
     * Can be {@code null}.
     */
    @Nullable
    public String getOriginalTitle() {
        String res = getStringOrNull(MovieColumns.ORIGINAL_TITLE);
        return res;
    }

    /**
     * Get the {@code overview} value.
     * Can be {@code null}.
     */
    @Nullable
    public String getOverview() {
        String res = getStringOrNull(MovieColumns.OVERVIEW);
        return res;
    }

    /**
     * Get the {@code release_date} value.
     * Can be {@code null}.
     */
    @Nullable
    public Long getReleaseDate() {
        Long res = getLongOrNull(MovieColumns.RELEASE_DATE);
        return res;
    }

    /**
     * Get the {@code poster_path} value.
     * Can be {@code null}.
     */
    @Nullable
    public String getPosterPath() {
        String res = getStringOrNull(MovieColumns.POSTER_PATH);
        return res;
    }

    /**
     * Get the {@code popularity} value.
     * Can be {@code null}.
     */
    @Nullable
    public Double getPopularity() {
        Double res = getDoubleOrNull(MovieColumns.POPULARITY);
        return res;
    }

    /**
     * Get the {@code vote_average} value.
     * Can be {@code null}.
     */
    @Nullable
    public Double getVoteAverage() {
        Double res = getDoubleOrNull(MovieColumns.VOTE_AVERAGE);
        return res;
    }

    /**
     * Get the {@code vote_count} value.
     * Can be {@code null}.
     */
    @Nullable
    public Integer getVoteCount() {
        Integer res = getIntegerOrNull(MovieColumns.VOTE_COUNT);
        return res;
    }
}


text:
package de.ayesolutions.gogs.client.service;

import de.ayesolutions.gogs.client.AbstractGogsTest;
import de.ayesolutions.gogs.client.model.CreateRepository;
import de.ayesolutions.gogs.client.model.Repository;
import de.ayesolutions.gogs.client.model.WebHook;
import org.junit.Assert;
import org.junit.Ignore;
import org.junit.Test;

import java.util.List;
import java.util.UUID;

/**
 * @author Christian Aye - c.aye@aye-solutions.de
 */
public class RepositoryServiceTest extends AbstractGogsTest {

    private RepositoryService service = new RepositoryService(API_USER);

    private WebHook dummyWebHook;

    private CreateRepository dummyCreateRepository;

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

    @Override
    public void createDummyObjects() {
        dummyCreateRepository = new CreateRepository();
        dummyCreateRepository.setName(REPOSITORY_NAME);
        dummyCreateRepository.setDescription(REPOSITORY_NAME + " - desc");
        dummyCreateRepository.setAutoInit(true);
        dummyCreateRepository.setGitIgnores("Java");
        dummyCreateRepository.setLicense("Apache License 2.0");
        dummyCreateRepository.setPrivateRepository(false);
        dummyCreateRepository.setReadme("Default");

        dummyWebHook = new WebHook("gogs", "http://localhost/build/1", "json");
        dummyWebHook.setActive(true);
        dummyWebHook.getEvents().add("create");
        dummyWebHook.getEvents().add("push");
    }

    @Test
    public void listRepositories() throws Exception {
        Repository repository = service.createRepository(dummyCreateRepository);
        Assert.assertNotNull(repository);

        List<Repository> repositoryList = service.listRepositories();
        Assert.assertEquals(1, repositoryList.size());

        service.deleteRepository(USERNAME_USER, REPOSITORY_NAME);
    }

    @Test
    public void createRepository() throws Exception {
        Repository repository = service.createRepository(dummyCreateRepository);
        Assert.assertNotNull(repository);

        service.deleteRepository(USERNAME_USER, REPOSITORY_NAME);
    }

    @Test
    @Ignore
    public void createOrganizationRepository() throws Exception {

    }

    @Test
    public void search() throws Exception {
        Repository repository = service.createRepository(dummyCreateRepository);
        Assert.assertNotNull(repository);

        List<Repository> repositoryList = service.search(REPOSITORY_NAME, 0, 1);
        Assert.assertEquals(1, repositoryList.size());

        service.deleteRepository(USERNAME_USER, REPOSITORY_NAME);
    }

    @Test
    @Ignore
    public void migrate() throws Exception {

    }

    @Test
    public void getRepository() throws Exception {
        Repository repository = service.createRepository(dummyCreateRepository);
        Assert.assertNotNull(repository);

        repository = service.getRepository(USERNAME_USER, REPOSITORY_NAME);
        Assert.assertNotNull(repository);

        service.deleteRepository(USERNAME_USER, REPOSITORY_NAME);
    }

    @Test
    public void deleteRepository() throws Exception {
        Repository repository = service.createRepository(dummyCreateRepository);
        Assert.assertNotNull(repository);

        service.deleteRepository(USERNAME_USER, REPOSITORY_NAME);
    }

    @Test
    public void listWebHooks() throws Exception {
        Repository repository = service.createRepository(dummyCreateRepository);
        Assert.assertNotNull(repository);

        WebHook webHook = service.createWebHook(USERNAME_USER, REPOSITORY_NAME, dummyWebHook);
        Assert.assertNotNull(webHook.getId());

        List<WebHook> webHookList = service.listWebHooks(USERNAME_USER, REPOSITORY_NAME);
        Assert.assertEquals(1, webHookList.size());

        service.deleteWebHook(USERNAME_USER, REPOSITORY_NAME, webHook.getId());
        service.deleteRepository(USERNAME_USER, REPOSITORY_NAME);
    }

    @Test
    public void createWebHook() throws Exception {
        Repository repository = service.createRepository(dummyCreateRepository);
        Assert.assertNotNull(repository);

        WebHook webHook = service.createWebHook(USERNAME_USER, REPOSITORY_NAME, dummyWebHook);
        Assert.assertNotNull(webHook.getId());

        Assert.assertNull(service.createWebHook(USERNAME_UNKNOWN, REPOSITORY_NAME, dummyWebHook));

        service.deleteWebHook(USERNAME_USER, REPOSITORY_NAME, webHook.getId());
        service.deleteRepository(USERNAME_USER, REPOSITORY_NAME);
    }

    @Test
    public void updateWebHook() throws Exception {
        Repository repository = service.createRepository(dummyCreateRepository);
        Assert.assertNotNull(repository);

        WebHook webHook = service.createWebHook(USERNAME_USER, REPOSITORY_NAME, dummyWebHook);
        Assert.assertNotNull(webHook);

        Assert.assertNotNull(service.updateWebHook(USERNAME_USER, REPOSITORY_NAME, webHook));

        service.deleteWebHook(USERNAME_USER, REPOSITORY_NAME, webHook.getId());
        service.deleteRepository(USERNAME_USER, REPOSITORY_NAME);
    }

    @Test
    public void deleteWebHook() throws Exception {
        RepositoryService service = new RepositoryService(API_USER);

        Repository repository = service.createRepository(dummyCreateRepository);
        Assert.assertNotNull(repository);

        WebHook webHook = service.createWebHook(USERNAME_USER, REPOSITORY_NAME, dummyWebHook);
        Assert.assertNotNull(webHook.getId());

        service.deleteWebHook(USERNAME_USER, REPOSITORY_NAME, webHook.getId());
        service.deleteRepository(USERNAME_USER, REPOSITORY_NAME);

    }

    @Test
    @Ignore
    public void addCollaborator() throws Exception {

    }

    @Test
    @Ignore
    public void getRawFile() throws Exception {

    }

    @Test
    @Ignore
    public void getArchive() throws Exception {

    }

    @Test
    @Ignore
    public void listBranches() throws Exception {

    }

    @Test
    @Ignore
    public void getBranch() throws Exception {

    }

    @Test
    @Ignore
    public void addPublicKey() throws Exception {

    }

    @Test
    @Ignore
    public void getDeployKeys() throws Exception {

    }

    @Test
    @Ignore
    public void addDeployKey() throws Exception {

    }

    @Test
    @Ignore
    public void getDeployKey() throws Exception {

    }

    @Test
    @Ignore
    public void deleteDeployKey() throws Exception {

    }

    @Test
    @Ignore
    public void getEditorConfig() throws Exception {

    }

    @Test
    @Ignore
    public void addTeamRepository() throws Exception {

    }

    @Test
    @Ignore
    public void deleteTeamRepository() throws Exception {
        Assert.assertTrue(false);
    }
}


text:
namespace Derby.Migrations
{
    using System;
    using System.Data.Entity.Migrations;

    public partial class IdentityFix : DbMigration
    {
        public override void Up()
        {
        }

        public override void Down()
        {
        }
    }
}


text:
ulimit -d unlimited
bta_path=`dirname $0`
cp -r $bta_path/bta_files .
#bad hack as webserver wasnt finding file : I guess www has wrong path
sicstus="/Users/leuschel/bin/bin/sicstus"
if [ -e /usr/bin/sicstus ]
then
sicstus="/usr/bin/sicstus"
fi
if [ -e /usr/local/bin/sicstus ]
then
sicstus="/usr/local/bin/sicstus"
fi
$sicstus -r $bta_path/bta.sav --goal 'bta.'


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
ec.de
</TITLE>

<META NAME="keywords" CONTENT="ec.de package">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../stylesheet.css" TITLE="Style">

ec.de

Classes

Best1BinDEBreeder

DEBreeder

DEStatistics

Rand1EitherOrDEBreeder

Rand1ExpDEBreeder


text:
package com.google.libwebm.mkvmuxer;

public class AudioTrack extends Track {

  public AudioTrack(int seed) {
    nativePointer = newAudioTrack(seed);
  }

  public long bitDepth() {
    return bitDepth(nativePointer);
  }

  public long channels() {
    return channels(nativePointer);
  }

  @Override
  public long payloadSize() {
    return PayloadSize(nativePointer);
  }

  public double sampleRate() {
    return sampleRate(nativePointer);
  }

  public void setBitDepth(long bitDepth) {
    setBitDepth(nativePointer, bitDepth);
  }

  public void setChannels(long channels) {
    setChannels(nativePointer, channels);
  }

  public void setSampleRate(double sampleRate) {
    setSampleRate(nativePointer, sampleRate);
  }

  @Override
  public boolean write(IMkvWriter writer) {
    return Write(nativePointer, writer.getNativePointer());
  }

  protected AudioTrack(long nativePointer) {
    super(nativePointer);
  }

  @Override
  protected void deleteObject() {
    deleteAudioTrack(nativePointer);
  }

  private static native long bitDepth(long jAudioTrack);
  private static native long channels(long jAudioTrack);
  private static native void deleteAudioTrack(long jAudioTrack);
  private static native long newAudioTrack(int jSeed);
  private static native long PayloadSize(long jAudioTrack);
  private static native double sampleRate(long jAudioTrack);
  private static native void setBitDepth(long jAudioTrack, long bit_depth);
  private static native void setChannels(long jAudioTrack, long channels);
  private static native void setSampleRate(long jAudioTrack, double sample_rate);
  private static native boolean Write(long jAudioTrack, long jWriter);
}


text:
Various DCAT tools for harvesting metadata from Belgian open data portals,
converting metadata to DCAT-AP files and updating the Belgian
[data.gov.be](http://data.gov.be) portal.

The portal itself is a Drupal 7 website, based on Fedict's
[Openfed](https://drupal.org/project/openfed) distribution plus two extra modules
[RestWS](https://drupal.org/project/restws) and
[RestWS i18n](https://www.drupal.org/project/restws_i18n).

## Data

Only interested in the result ? The N-Triples and XML files (DCAT-AP)
used to update data.gov.be can be found in the [dcat repository](https://github.com/fedict/dcat)

## Overview of the tools

![Components](components.png)

### Requirements

These tools can be used with a Java runtime 11 or newer, on a headless machine, i.e. there is no fancy GUI.

Internet connection is obviously required, although a proxy can be used.

### Main parts

* Helper classes: for storing scraped pages locally, conversion tools etc.
* Various [scrapers](README-SCRAPER.md): getting metadata from various repositories
and websites, and turning the metadata into DCAT files
* Also part of the scrapers are a series of [SPARQL scripts](README-ENHANCERS.md) to turn DCAT into DCAT-AP:
e.g. map site-specific themes, add missing properties and prepare the files for updating data.gov.be
* Data.gov.be [updater](README-UPLOADER.md): update the data.gov.be (Drupal 7) website
using the enhanced DCAT files
* Some [tools](#tools): link checker, EDP converter tool

There is also separate, stand-alone RDF [validator](https://github.com/fedict/rdfvalidator)
project which can be used to validate DCAT metadata,
regardless if the metadata is to be published on data.gov.be or not.

## Steps for updating data.gov.be and the EU Data Portal

  * The various portals (except `all`) should be harvested using the scrapers.
  * The enhanced files can be uploaded to the data.gov.be portal using the updater
  * Then use `all` enhancer to merge all the files from the various portals into one file `datagovbe.nt`
  * Convert the merged file using the EDP tool to an XML file called `datagovbe_edp.xml`
  * Upload both the `datagovbe.nt` and `datagovbe_edp.xml` to [github](https://github.com/fedict/dcat)
  * This will be used as input for the European Data Portal (scheduled Thursday morning, every week)

### Configuration

All configuration is done using Java (plain text) properties files.
Some examples can be found in [dist/cfg](dist/cfg)

See also the [Notes](README-NOTES.md)


text:
package com.opengamma.strata.product.dsf;

import static com.opengamma.strata.collect.TestHelper.assertSerialization;
import static com.opengamma.strata.collect.TestHelper.coverBeanEquals;
import static com.opengamma.strata.collect.TestHelper.coverImmutableBean;
import static org.testng.Assert.assertEquals;

import java.time.LocalDate;

import org.testng.annotations.Test;

import com.opengamma.strata.basics.ReferenceData;
import com.opengamma.strata.product.TradeInfo;

/**
 * Test {@link DsfTrade}.
 */
@Test
public class DsfTradeTest {

  private static final ReferenceData REF_DATA = ReferenceData.standard();
  static final Dsf PRODUCT = DsfTest.sut();
  static final Dsf PRODUCT2 = DsfTest.sut2();
  private static final TradeInfo TRADE_INFO = TradeInfo.builder()
      .tradeDate(LocalDate.of(2014, 6, 12))
      .settlementDate(LocalDate.of(2014, 6, 14))
      .build();
  private static final double QUANTITY = 100L;
  private static final double QUANTITY2 = 200L;
  private static final double PRICE = 0.99;
  private static final double PRICE2 = 0.98;

  //-------------------------------------------------------------------------
  public void test_builder() {
    DsfTrade test = sut();
    assertEquals(test.getInfo(), TRADE_INFO);
    assertEquals(test.getProduct(), PRODUCT);
    assertEquals(test.getQuantity(), QUANTITY);
    assertEquals(test.getPrice(), PRICE);
    assertEquals(test.getSecurityId(), PRODUCT.getSecurityId());
    assertEquals(test.getCurrency(), PRODUCT.getCurrency());
  }

  //-------------------------------------------------------------------------
  public void test_resolve() {
    DsfTrade test = sut();
    ResolvedDsfTrade expected = ResolvedDsfTrade.builder()
        .info(TRADE_INFO)
        .product(PRODUCT.resolve(REF_DATA))
        .quantity(QUANTITY)
        .price(PRICE)
        .build();
    assertEquals(test.resolve(REF_DATA), expected);
  }

  //-------------------------------------------------------------------------
  public void coverage() {
    coverImmutableBean(sut());
    coverBeanEquals(sut(), sut2());
  }

  public void test_serialization() {
    assertSerialization(sut());
  }

  //-------------------------------------------------------------------------
  static DsfTrade sut() {
    return DsfTrade.builder()
        .info(TRADE_INFO)
        .product(PRODUCT)
        .quantity(QUANTITY)
        .price(PRICE)
        .build();
  }

  static DsfTrade sut2() {
    return DsfTrade.builder()
        .product(PRODUCT2)
        .quantity(QUANTITY2)
        .price(PRICE2)
        .build();
  }

}


text:
use set::Set;
use std::collections::HashMap;
use std::cell::RefCell;

/// Abstraction over set operations. Doesn't contain default implementation.
pub trait SetOps {
    /// Union of fuzzy sets.
    fn union(&self, left: &mut Set, right: &mut Set) -> Set;
    /// Intersection of fuzzy sets.
    fn intersect(&self, left: &mut Set, right: &mut Set) -> Set;
}

/// Implementation of commonly used minimax set operations.
pub struct MinMaxOps;

impl SetOps for MinMaxOps {
    /// Union of fuzzy sets.
    ///
    /// Values with highest memberships are copied to the result set.
    fn union(&self, left: &mut Set, right: &mut Set) -> Set {
        let mut result = HashMap::new();
        for (k, v) in left.cache.borrow().iter() {
            let right_mem = right.check(k.into_inner());
            result.insert(*k, v.max(right_mem));
        }
        for (k, v) in right.cache.borrow().iter() {
            if result.contains_key(k) {
                continue;
            }
            let left_mem = left.check(k.into_inner());
            result.insert(*k, v.max(left_mem));
        }
        Set::new_with_domain(format!("{} UNION {}", left.name, right.name), RefCell::new(result))
    }

    /// Intersection of fuzzy sets.
    ///
    /// Values with lowest memberships are copied to the result set.
    fn intersect(&self, left: &mut Set, right: &mut Set) -> Set {
        let mut result = HashMap::new();
        for (k, v) in left.cache.borrow().iter() {
            let right_mem = right.check(k.into_inner());
            if right_mem > 0.0 {
                result.insert(*k, v.min(right_mem));
            }
        }
        Set::new_with_domain(format!("{} INTERSECT {}", left.name, right.name), RefCell::new(result))
    }
}

/// Abstraction over fuzzy logic operations. Doesn't contain default implementation.
pub trait LogicOps {
    /// Fuzzy logic AND operation.
    fn and(&self, left: f32, right: f32) -> f32;
    /// Fuzzy logic OR operation.
    fn or(&self, left: f32, right: f32) -> f32;
    /// Fuzzy logic NOT operation.
    fn not(&self, value: f32) -> f32;
}

/// Implementation of commonly used Zadeh fuzzy logic operations.
pub struct ZadehOps;

impl LogicOps for ZadehOps {
    /// Fuzzy logic AND operation.
    ///
    /// Returns minimum of arguments.
    ///
    /// # Usage
    /// The classical AND operator's truth table:
    ///
    /// ```rust
    /// use fuzzy_logic::ops::{LogicOps, ZadehOps};
    /// let ops = ZadehOps{};
    /// ops.and(0.0, 0.0); //-> 0.0
    /// ops.and(0.0, 1.0); //-> 0.0
    /// ops.and(1.0, 0.0); //-> 0.0
    /// ops.and(1.0, 1.0); //-> 1.0
    /// ```
    fn and(&self, left: f32, right: f32) -> f32 {
        left.min(right)
    }

    /// Fuzzy logic AND operation.
    ///
    /// Returns maximum of arguments.
    ///
    /// # Usage
    /// The classical OR operator's truth table:
    ///
    /// ```rust
    /// use fuzzy_logic::ops::{LogicOps, ZadehOps};
    /// let ops = ZadehOps{};
    /// ops.or(0.0, 0.0); //-> 0.0
    /// ops.or(0.0, 1.0); //-> 1.0
    /// ops.or(1.0, 0.0); //-> 1.0
    /// ops.or(1.0, 1.0); //-> 1.0
    /// ```
    fn or(&self, left: f32, right: f32) -> f32 {
        left.max(right)
    }

    /// Fuzzy logic AND operation.
    ///
    /// Returns inversed logical value.
    /// # Usage
    /// The classical NOT operator's truth table:
    ///
    /// ```rust
    /// use fuzzy_logic::ops::{LogicOps, ZadehOps};
    /// let ops = ZadehOps{};
    /// ops.not(0.0); //-> 1.0
    /// ops.not(1.0); //-> 0.0
    /// ```
    fn not(&self, value: f32) -> f32 {
        1.0 - value
    }
}


text:
<?php

declare(strict_types=1); // @codeCoverageIgnore

namespace Recoil;

/**
 * A strand trace is a low-level observer of strand events.
 *
 * @see Strand::setTrace()
 *
 * A trace may only be set on a strand when assertions are enabled. When
 * assertions are disabled, all tracing related code is disabled, and setting
 * a trace has no effect.
 *
 * If an exception is thrown from any of the StrandTrace methods the kernel
 * behaviour is undefined.
 *
 * @link http://php.net/manual/en/ini.core.php#ini.zend.assertions
 */
interface StrandTrace
{
    /**
     * Record a push to the call-stack.
     *
     * @param Strand $strand The strand being traced.
     * @param int    $depth  The depth of the call-stack BEFORE the push operation.
     *
     * @return null
     */
    public function push(Strand $strand, int $depth);

    /**
     * Record a pop from the call-stack.
     *
     * @param Strand $strand The strand being traced.
     * @param int    $depth  The depth of the call-stack AFTER the pop operation.
     *
     * @return null
     */
    public function pop(Strand $strand, int $depth);

    /**
     * Record keys and values yielded from the coroutine on the head of the stack.
     *
     * @param Strand $strand The strand being traced.
     * @param int    $depth  The current depth of the call-stack.
     * @param mixed  $key    The key yielded from the coroutine.
     * @param mixed  $value  The value yielded from the coroutine.
     *
     * @return null
     */
    public function yield(Strand $strand, int $depth, $key, $value);

    /**
     * Record the action and value used to resume a yielded coroutine.
     *
     * @param Strand $strand The strand being traced.
     * @param int    $depth  The current depth of the call-stack.
     * @param string $action The resume action ('send' or 'throw').
     * @param mixed  $value  The resume value or exception.
     *
     * @return null
     */
    public function resume(Strand $strand, int $depth, string $action, $value);

    /**
     * Record the suspension of a strand.
     *
     * @param Strand $strand The strand being traced.
     * @param int    $depth  The current depth of the call-stack.
     *
     * @return null
     */
    public function suspend(Strand $strand, int $depth);

    /**
     * Record the action and value when a strand exits.
     *
     * @param Strand $strand The strand being traced.
     * @param int    $depth  The current depth of the call-stack.
     * @param string $action The final action performed on the strand's listener ('send' or 'throw').
     * @param mixed  $value  The strand result or exception.
     *
     * @return null
     */
    public function exit(Strand $strand, int $depth, string $action, $value);
}