text:
package org.jeo.geopkg;

import static java.lang.String.format;

import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;

import javax.sql.DataSource;

import org.jeo.data.Cursor;
import org.jeo.data.Cursors;
import org.jeo.data.DataRef;
import org.jeo.data.Dataset;
import org.jeo.data.FileData;
import org.jeo.data.Query;
import org.jeo.data.QueryPlan;
import org.jeo.data.Tile;
import org.jeo.data.TilePyramid;
import org.jeo.data.TilePyramidBuilder;
import org.jeo.data.Workspace;
import org.jeo.feature.Feature;
import org.jeo.feature.Features;
import org.jeo.feature.Field;
import org.jeo.feature.Schema;
import org.jeo.feature.SchemaBuilder;
import org.jeo.filter.Filter;
import org.jeo.geom.Envelopes;
import org.jeo.geom.Geom;
import org.jeo.geopkg.Entry.DataType;
import org.jeo.geopkg.geom.GeoPkgGeomWriter;
import org.jeo.proj.Proj;
import org.jeo.sql.DbOP;
import org.jeo.sql.SQL;
import org.jeo.util.Key;
import org.jeo.util.Pair;
import org.osgeo.proj4j.CoordinateReferenceSystem;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sqlite.SQLiteDataSource;

import com.vividsolutions.jts.geom.Envelope;
import com.vividsolutions.jts.geom.Geometry;

/**
 * Provides access to a GeoPackage SQLite database.
 *
 * @author Justin Deoliveira, OpenGeo
 */
public class GeoPkgWorkspace implements Workspace, FileData {

    static Logger LOG = LoggerFactory.getLogger(GeoPackage.class);

    /** name of geopackage contents table */
    static final String GEOPACKAGE_CONTENTS = "geopackage_contents";

    /** name of geoemtry columns table */
    static final String GEOMETRY_COLUMNS = "geometry_columns";

    /** name of geoemtry columns table */
    static final String SPATIAL_REF_SYS = "spatial_ref_sys";

    /** name of tile metadata table */
    static final String TILE_TABLE_METADATA = "tile_table_metadata";

    /** name of tile matrix metadata table */
    static final String TILE_MATRIX_METADATA = "tile_matrix_metadata";

    /** date format */
    static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-mm-dd'T'HH:MM:ss.SSS'Z'");
    static {
        DATE_FORMAT.setTimeZone(TimeZone.getTimeZone("GMT"));
    }

    /** creation options */
    GeoPkgOpts opts;

    /** data source */
    DataSource db;

    /** wkb writer */
    GeoPkgGeomWriter geomWriter;

    GeoPkgTypes dbtypes;

    /**
     * Creates a GeoPackage from an existing file.
     *
     * @param dbFile The database file.
     *
     * @throws Exception Any error occurring opening the database file.
     */
    public GeoPkgWorkspace(GeoPkgOpts opts) throws IOException {
        this.opts = opts;
        db = createDataSource(opts);

        dbtypes = new GeoPkgTypes();
        geomWriter = new GeoPkgGeomWriter();
    }

    DataSource createDataSource(GeoPkgOpts opts) {
        SQLiteDataSource dataSource = new SQLiteDataSource();
        dataSource.setUrl("jdbc:sqlite:" + opts.getFile().getPath());
        return dataSource;
    }

    @Override
    public GeoPackage getDriver() {
        return new GeoPackage();
    }

    @Override
    public Map<Key<?>, Object> getDriverOptions() {
        return opts.toMap();
    }

    public File getFile() {
        return opts.getFile();
    }

    DataSource getDataSource() {
        return db;
    }

    @Override
    public Iterable<DataRef<Dataset>> list() throws IOException {
        return run(new DbOP<List<DataRef<Dataset>>>() {
            @Override
            protected List<DataRef<Dataset>> doRun(Connection cx) throws Exception {
                String sql = format("SELECT table_name FROM %s", GEOPACKAGE_CONTENTS);
                log(sql);

                ResultSet rs = open(open(cx.createStatement()).executeQuery(sql));
                List<DataRef<Dataset>> refs = new ArrayList<DataRef<Dataset>>();
                while(rs.next()) {
                    refs.add(new DataRef<Dataset>(Dataset.class, rs.getString(1)));
                }
                return refs;
            }
        });
    }

    @Override
    public Dataset get(String layer) throws IOException {
        FeatureEntry fe = feature(layer);
        if (fe != null) {
            return new GeoPkgVector(fe, this);
        }

        TileEntry te = tile(layer);
        if (te != null) {
            return new GeoPkgTileSet(te, this);
        }

        return null;
    }

//    /**
//     * Lists all entries in the geopackage.
//     */
//    public List<Entry> entries() throws IOException {
//        List<Entry> entries = new ArrayList<Entry>();
//        entries.addAll(features());
//        entries.addAll(tiles());
//        return entries;
//    }

    /**
     * Lists all the feature entries in the geopackage.
     */
    public List<FeatureEntry> features() throws IOException {
        return run(new DbOP<List<FeatureEntry>>() {
            @Override
            protected List<FeatureEntry> doRun(Connection cx) throws Exception {
                String sql = format(
                    "SELECT a.*, b.f_geometry_column, b.geometry_type, b.coord_dimension, " +
                           "c.auth_name, c.auth_srid" +
                     " FROM %s a, %s b, %s c" +
                    " WHERE a.table_name = b.f_table_name" +
                      " AND a.srid = c.srid" +
                      " AND a.data_type = '%s'",
                      GEOPACKAGE_CONTENTS,GEOMETRY_COLUMNS,SPATIAL_REF_SYS, DataType.Feature.value());
                log(sql);

                List<FeatureEntry> entries = new ArrayList<FeatureEntry>();

                ResultSet rs = open(open(cx.createStatement()).executeQuery(sql));
                while(rs.next()) {
                    entries.add(createFeatureEntry(rs));
                }

                return entries;
            }
        });
    }

    public FeatureEntry feature(final String name) throws IOException {
        return run(new DbOP<FeatureEntry>() {
            @Override
            protected FeatureEntry doRun(Connection cx) throws Exception {
                String sql = format(
                    "SELECT a.*, b.f_geometry_column, b.geometry_type, b.coord_dimension" +
                     " FROM %s a, %s b" +
                    " WHERE a.table_name = b.f_table_name" +
                      " AND a.table_name = ?" +
                      " AND a.data_type = ?",
                  GEOPACKAGE_CONTENTS, GEOMETRY_COLUMNS);
                log(sql, name, DataType.Feature);

                PreparedStatement ps = open(cx.prepareStatement(sql));
                ps.setString(1, name);
                ps.setString(2, DataType.Feature.value());

                ResultSet rs = open(ps.executeQuery());
                while(rs.next()) {
                    return createFeatureEntry(rs);
                }

                return null;
            }
        });
    }

    public long count(final FeatureEntry entry, final Query q) throws IOException {
        QueryPlan qp = new QueryPlan(q);

        if (!Envelopes.isNull(q.getBounds())) {
            return Cursors.size(cursor(entry, q));
        }

        final SQL sql = new SQL("SELECT count(*) FROM ").name(entry.getTableName());
        final List<Object> args = encodeQuery(sql, q, qp);

        if (q.isFiltered() && !qp.isFiltered()) {
            return Cursors.size(cursor(entry, q));
        }

        return run(new DbOP<Long>() {
            @Override
            protected Long doRun(Connection cx) throws Exception {
                ResultSet rs =
                    open(open(prepareStatement(log(sql.toString()), args, cx)).executeQuery());
                rs.next();
                return q.adjustCount(rs.getLong(1));
            }
        });
    }

    public Cursor<Feature> cursor(FeatureEntry entry, Query q) throws IOException {
        try {
            Schema schema = schema(entry);

            QueryPlan qp = new QueryPlan(q);

            //TODO: handle selective fields
            SQL sqlb = new SQL("SELECT * FROM ").name(entry.getTableName());
            List<Object> args = encodeQuery(sqlb, q, qp);

            Connection cx = db.getConnection();
            PreparedStatement ps = prepareStatement(log(sqlb.toString()), args, cx);

            ResultSet rs = ps.executeQuery();

            Cursor<Feature> c = new FeatureCursor(rs, cx, schema);

            if (!Envelopes.isNull(q.getBounds())) {
                c = Cursors.intersects(c, q.getBounds());
            }

            return qp.apply(c);
        }
        catch(Exception e) {
            throw new IOException(e);
        }
    }

    List<Object> encodeQuery(SQL sql, Query q, QueryPlan qp) {
        GeoPkgFilterSQLEncoder sqlfe = new GeoPkgFilterSQLEncoder();
        sqlfe.setDbTypes(dbtypes);

        if (!Filter.isTrueOrNull(q.getFilter())) {
            try {
                sql.add(" WHERE ").add(sqlfe.encode(q.getFilter(), null));
                qp.filtered();
            }
            catch(Exception e) {
                LOG.debug("Unable to natively encode filter: " + q.getFilter(), e);
            }
        }

        if (q.getLimit() != null) {
            sql.add(" LIMIT ").add(q.getLimit());
            qp.offsetted();
        }
        if (q.getOffset() != null) {
            sql.add(" OFFSET ").add(q.getOffset());
            qp.limited();
        }

        List<Object> args = new ArrayList<Object>();
        for (Pair<Object, Integer> p : sqlfe.getArgs()) {
            args.add(p.first());
        }
        return args;
    }

    public void add(final FeatureEntry entry, final Feature feature) throws IOException {
        run(new DbOP<Boolean>() {
            @Override
            protected Boolean doRun(Connection cx) throws Exception {
                Feature f = Features.retype(feature, schema(entry));

                SQL sqlb = new SQL("INSERT INTO ").name(entry.getTableName()).add(" (");
                List<Object> objs = new ArrayList<Object>();

                for (Field fld : f.schema()) {
                    Object o = f.get(fld.getName());
                    if (o != null) {
                        sqlb.name(fld.getName()).add(", ");
                        objs.add(o);
                    }
                }

                sqlb.trim(2).add(") VALUES (");
                for(Object obj : objs) {
                    sqlb.add("?,");
                }
                sqlb.trim(1).add(")");

                String sql = sqlb.toString();
                log(sql, objs);

                return open(prepareStatement(sql, objs, cx)).execute();
            }
        });

    }

    public GeoPkgVector create(Schema schema) throws IOException {
        create(new FeatureEntry(), schema);
        return (GeoPkgVector) get(schema.getName());
    }

    public void create(FeatureEntry entry, Schema schema) throws IOException {
        //clone entry so we can work on it
        FeatureEntry e = new FeatureEntry();
        e.init(entry);
        e.setTableName(schema.getName());

        if (e.getGeometryColumn() != null) {
            //check it
            if (schema.field(e.getGeometryColumn()) == null) {
                throw new IllegalArgumentException(
                        format("Geometry column %s does not exist in schema", e.getGeometryColumn()));
            }
        }
        else {
            e.setGeometryColumn(findGeometryName(schema));
        }

        if (e.getIdentifier() == null) {
            e.setIdentifier(schema.getName());
        }
        if (e.getDescription() == null) {
            e.setDescription(e.getIdentifier());
        }

        //check for srid
        if (e.getSrid() == null) {
            e.setSrid(findSRID(schema));
        }
        if (e.getSrid() == null) {
            throw new IllegalArgumentException("Entry must have srid");
        }

        //check for bounds
        if (e.getBounds() == null) {
            //TODO: this is pretty inaccurate
            e.setBounds(Proj.bounds(Proj.crs(e.getSrid())));
        }
        if (e.getBounds() == null) {
            throw new IllegalArgumentException("Entry must have bounds");
        }

        if (e.getCoordDimension() == null) {
            e.setCoordDimension(2);
        }

        if (e.getGeometryType() == null) {
            e.setGeometryType(findGeometryType(schema));
        }
        //mark changed
        e.setLastChange(new Date());

        //create the feature table
        try {
            createFeatureTable(schema, e);
        } catch (Exception ex) {
            throw new IOException("Error creating feature table", ex);
        }

        try {
            addGeopackageContentsEntry(e);
        } catch (Exception ex) {
            throw new IOException("Error updating " + GEOPACKAGE_CONTENTS, ex);
        }

        //update the entry
        entry.init(e);
    }

    void createFeatureTable(final Schema schema, final FeatureEntry entry) throws Exception {
        run(new DbOP<Object>() {
            @Override
            protected Object doRun(Connection cx) throws Exception {
                SQL sql = new SQL("CREATE TABLE ").name(schema.getName()).add("(");

                sql.name(findPrimaryKeyColumnName(schema)).add(" INTEGER PRIMARY KEY, ");
                for (Field f : schema) {
                    sql.name(f.getName()).add(" ");
                    if (f.isGeometry()) {
                        sql.add(Geom.Type.from(f.getType()).getSimpleName());
                    }
                    else {
                        String t = dbtypes.toName(f.getType());
                        sql.add(t != null ? t : "TEXT");
                    }

                    sql.add(", ");
                }
                sql.trim(2).add(")");

                PreparedStatement ps = open(cx.prepareStatement(log(sql.toString())));
                ps.execute();

                //update geometry columns
                addGeometryColumnsEntry(schema, entry, cx);
                return null;
            }
        });
    }

    void addGeopackageContentsEntry(final FeatureEntry entry) throws Exception {
        run(new DbOP<Object>() {
            @Override
            protected Object doRun(Connection cx) throws Exception {
                //addCRS(e.getSrid());

                SQL sqlb = new SQL("INSERT INTO").add(" %s ", GEOPACKAGE_CONTENTS)
                    .add("(table_name, data_type, identifier");

                StringBuilder vals = new StringBuilder("VALUES (?,?,?");

                if (entry.getDescription() != null) {
                    sqlb.add(", description");
                    vals.append(",?");
                }

                if (entry.getLastChange() != null) {
                    sqlb.add(", last_change");
                    vals.append(",?");
                }
                if (entry.getBounds() != null) {
                    sqlb.add(", min_x, min_y, max_x, max_y");
                    vals.append(",?,?,?,?");
                }

                if (entry.getSrid() != null) {
                    sqlb.add(", srid");
                    vals.append(",?");
                }
                sqlb.add(") ").add(vals.append(")").toString());

                PreparedStatement ps = open(cx.prepareStatement(log(sqlb.toString(), entry)));
                ps.setString(1, entry.getTableName());
                ps.setString(2, entry.getDataType().value());
                ps.setString(3, entry.getIdentifier());

                int i = 4;
                if (entry.getDescription() != null) {
                    ps.setString(i++, entry.getDescription());
                }

                if (entry.getLastChange() != null) {
                    ps.setString(i++, DATE_FORMAT.format(entry.getLastChange()));
                }
                if (entry.getBounds() != null) {
                    Envelope b = entry.getBounds();
                    ps.setDouble(i++, b.getMinX());
                    ps.setDouble(i++, b.getMinY());
                    ps.setDouble(i++, b.getMaxX());
                    ps.setDouble(i++, b.getMaxY());
                }

                if(entry.getSrid() != null) {
                    ps.setInt(i++, entry.getSrid());
                }

                ps.executeUpdate();
                return null;
            }
        });
    }

    void addGeometryColumnsEntry(final Schema schema, final FeatureEntry entry, Connection cx)
        throws Exception {
        run(new DbOP<Object>() {
            @Override
            protected Object doRun(Connection cx) throws Exception {
                String sql = format(
                    "INSERT INTO %s VALUES (?, ?, ?, ?, ?);", GEOMETRY_COLUMNS);

                log(sql, entry.getTableName(), entry.getGeometryColumn(),
                    entry.getGeometryType(), entry.getCoordDimension(), entry.getSrid());

                PreparedStatement ps = open(cx.prepareStatement(sql));
                ps.setString(1, entry.getTableName());
                ps.setString(2, entry.getGeometryColumn());
                ps.setString(3, entry.getGeometryType().getSimpleName());
                ps.setInt(4, entry.getCoordDimension());
                ps.setInt(5, entry.getSrid());

                ps.executeUpdate();
                return null;
            }
        }, cx);
    }

    String findPrimaryKeyColumnName(Schema schema) {
        String[] names = new String[]{"fid", "gid", "oid"};
        for (String name : names) {
            if (schema.field(name) == null && schema.field(name.toUpperCase()) == null) {
                return name;
            }
        }
        return null;
    }

    Integer findSRID(Schema schema) {
        CoordinateReferenceSystem crs = schema.crs();
        return crs != null ? Proj.epsgCode(crs) : null;
    }

    Geom.Type findGeometryType(Schema schema) {
        Field geom = schema.geometry();
        return geom != null ? Geom.Type.from(geom.getType()) : null;
    }

    String findGeometryName(Schema schema) {
        Field geom = schema.geometry();
        return geom != null ? geom.getName() : null;
    }

    FeatureEntry createFeatureEntry(ResultSet rs) throws Exception {
        FeatureEntry e = new FeatureEntry();

        initEntry(e, rs);
        e.setGeometryColumn(rs.getString(11));
        e.setGeometryType(Geom.Type.from(rs.getString(12)));
        e.setCoordDimension((rs.getInt(13)));
        return e;
    }

    public Schema schema(FeatureEntry entry) throws IOException {
        if (entry.getSchema() == null) {
            try {
                entry.setSchema(createSchema(entry));
            } catch (Exception e) {
                throw new IOException(e);
            }
        }
        return entry.getSchema();
    }

    Schema createSchema(final FeatureEntry entry) throws Exception {
        return run(new DbOP<Schema>() {
            @Override
            protected Schema doRun(Connection cx) throws Exception {
                String sql = format("SELECT * FROM %s LIMIT 1", entry.getTableName());
                log(sql);

                ResultSet rs = open(open(cx.createStatement()).executeQuery(sql));
                ResultSetMetaData rsmd = rs.getMetaData();

                SchemaBuilder sb = Schema.build(entry.getTableName());
                for (int i = 0; i < rsmd.getColumnCount(); i++) {
                    String col = rsmd.getColumnName(i+1);
                    if (col.equals(entry.getGeometryColumn())) {
                        CoordinateReferenceSystem crs = entry.getSrid() != null ?
                            Proj.crs(entry.getSrid()) : null;
                        sb.field(col, entry.getGeometryType().getType(), crs);
                    }
                    else {
                        sb.field(col, dbtypes.fromSQL(rsmd.getColumnType(i+1)));
                    }
                }
                return sb.schema();
            }
        });
    }

    /**
     * Lists all the tile entries in the geopackage.
     */
    public List<TileEntry> tiles() throws IOException {
        return run(new DbOP<List<TileEntry>>() {
            @Override
            protected List<TileEntry> doRun(Connection cx) throws Exception {
                String sql = format(
                    "SELECT a.*, b.is_times_two_zoom" +
                     " FROM %s a, %s b" +
                    " WHERE a.table_name = b.t_table_name" +
                      " AND a.data_type = ?", GEOPACKAGE_CONTENTS, TILE_TABLE_METADATA);
                log(sql, DataType.Tile);

                PreparedStatement ps = open(cx.prepareStatement(sql));
                ps.setString(1, DataType.Tile.value());

                ResultSet rs = open(ps.executeQuery());

                List<TileEntry> entries = new ArrayList<TileEntry>();
                while(rs.next()) {
                    entries.add(createTileEntry(rs));
                }
                return entries;
            }
        });
    }

    public TileEntry tile(final String name) throws IOException {
        return run(new DbOP<TileEntry>() {
            @Override
            protected TileEntry doRun(Connection cx) throws Exception {
                String sql = format(
                    "SELECT a.*, b.is_times_two_zoom" +
                     " FROM %s a, %s b" +
                    " WHERE a.table_name = ?" +
                      " AND a.data_type = ?", GEOPACKAGE_CONTENTS, TILE_TABLE_METADATA);

                log(sql, name, DataType.Tile);

                PreparedStatement ps = open(cx.prepareStatement(sql));
                ps.setString(1, name);
                ps.setString(2, DataType.Tile.value());

                ResultSet rs = ps.executeQuery();
                if (rs.next()) {
                    return createTileEntry(rs);
                }
                return null;
            }
        });
    }

    public Cursor<Tile> read(TileEntry entry) throws IOException  {
        return read(entry, null, null, null, null, null, null);
    }

    public Cursor<Tile> read(TileEntry entry, Integer lowZoom, Integer highZoom,
        Integer lowCol, Integer highCol, Integer lowRow, Integer highRow) throws IOException  {

        final List<String> q = new ArrayList<String>();
        if (lowZoom != null && lowZoom > -1) {
            q.add("zoom_level >= " + lowZoom);
        }
        if (highZoom != null && highZoom > -1) {
            q.add("zoom_level <= " + lowZoom);
        }
        if (lowCol != null && lowCol > -1) {
            q.add("tile_column >= " + lowCol);
        }
        if (highCol != null && highCol > -1) {
            q.add("tile_column <= " + highCol);
        }
        if (lowRow != null && lowRow > -1) {
            q.add("tile_row >= " + lowRow);
        }
        if (highRow != null && highRow > -1) {
            q.add("tile_row <= " + highRow);
        }

        SQL sql = new SQL("SELECT zoom_level,tile_column,tile_row,tile_data FROM")
            .name(entry.getTableName());

        if (!q.isEmpty()) {
            sql.add(" WHERE ");
            for (String s : q) {
                sql.add(s).add(" AND ");
            }
            sql.trim(5);
        }

        try {
            Connection cx = db.getConnection();
            ResultSet rs = cx.createStatement().executeQuery(log(sql.toString()));
            return new TileCursor(rs, cx);
        }
        catch(Exception e) {
            throw new IOException(e);
        }

    }

    TileEntry createTileEntry(ResultSet rs) throws Exception {
        final TileEntry e = new TileEntry();
        initEntry(e, rs);

        e.setTimesTwoZoom(1 == rs.getInt(10));

        run(new DbOP<Object>() {
            @Override
            protected Object doRun(Connection cx) throws Exception {
                //load all the tile matrix entries
                String sql = format(
                    "SELECT zoom_level,matrix_width,matrix_height,tile_width,tile_height," +
                           "pixel_x_size, pixel_y_size FROM %s WHERE t_table_name = ? " +
                    " ORDER BY zoom_level", TILE_MATRIX_METADATA);
                log(sql, e.getTableName());

                PreparedStatement ps = open(cx.prepareStatement(sql));
                ps.setString(1, e.getTableName());

                ResultSet rs = open(ps.executeQuery());

                TilePyramidBuilder tpb = TilePyramid.build();
                //TODO: bounds
                if (rs.next()) {
                    tpb.tileSize(rs.getInt(4), rs.getInt(5));
                    do {
                        tpb.grid(rs.getInt(1), rs.getInt(2), rs.getInt(3));
                    }
                    while (rs.next());
                }

                e.setTilePyramid(tpb.pyramid());

                return null;
            }
        }, rs.getStatement().getConnection());

        return e;
    }

    /**
     * Sets common attributes of an entry.
     */
    void initEntry(Entry e, ResultSet rs) throws Exception {
        e.setTableName(rs.getString(1));
        e.setIdentifier(rs.getString(3));
        e.setDescription(rs.getString(4));

        try {
            e.setLastChange(DATE_FORMAT.parse(rs.getString(5)));
        } catch (ParseException ex) {
            throw new RuntimeException(ex);
        }
        e.setBounds(new Envelope(
            rs.getDouble(6), rs.getDouble(8), rs.getDouble(7), rs.getDouble(9)));
        e.setSrid(rs.getInt(10));
    }

    PreparedStatement prepareStatement(String sql, List<Object> args, Connection cx)
        throws SQLException, IOException {

        PreparedStatement ps = cx.prepareStatement(sql);

        for (int i = 0; i < args.size(); i++) {
            Object obj = args.get(i);
            if (obj instanceof Geometry) {
                ps.setBytes(i+1, geomWriter.write((Geometry)obj));
            }
            else {
                if (obj instanceof Byte || obj instanceof Short || obj instanceof Integer) {
                    ps.setInt(i+1, ((Number)obj).intValue());
                }
                if (obj instanceof Long) {
                    ps.setLong(i+1, ((Number)obj).longValue());
                }
                if (obj instanceof Float || obj instanceof Double) {
                    ps.setDouble(i+1, ((Number)obj).doubleValue());
                }
                else {
                    ps.setString(i+1, obj.toString());
                }
            }
        }

        return ps;
    }

    <T> T run(DbOP<T> op) throws IOException {
        return op.run(db);
    }

    <T> T run(DbOP<T> op, Connection cx) throws IOException {
        return op.run(cx);
    }

    String log(String sql, Object... params) {
        if (LOG.isDebugEnabled()) {
            if (params.length == 1 && params[0] instanceof Collection) {
                params = ((Collection)params[0]).toArray();
            }

            StringBuilder log = new StringBuilder(sql);
            if (params.length > 0) {
                log.append("; ");
                for (Object p : params) {
                    log.append(p).append(", ");
                }
                log.setLength(log.length()-2);
            }
            LOG.debug(log.toString());
        }
        return sql;
    }

    @Override
    /**
     * Closes the geopackage and the underlying database connection.
     * <p>
     * The application should always be sure to call this method when the
     * geopackage is no longer needed.
     * </p>
     */
    public void close() {
        try {
            if (db != null) {
                //db.close();
                db = null;
            }
        } catch (Exception e) {
            LOG.warn("Error disposing GeoPackage", e);
        }
    }

    protected void finalize() throws Throwable {
        close();
    }
}


text:
{% extends 'landing_layout.html' %}

{% block content %}

                    <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-main-collapse">

                    </button>

                            Contact

                            Register

                            Login

Changing the way

                                you trade aircraft parts

                                Parts guaranteed in stock.

                                Buy or negotiate online.

                                Immediate and secure online payment.

Locate, negotiate, and purchase all in one place. It's that simple.

Locate

How much time and resources are wasted verifying parts are in stock? On BidTru we guarantee the parts listed are available and ready to ship. Not only that, but all parts have prices, so you can purchase instantly or submit a bid.

Negotiate

BidTru provides transparency through a live bidding process online, keeping you in the loop without the need for emails and phone calls. Watch your screen as bids are placed and react immediately.

Purchase

Forget terms and credit checks. At BidTru we qualify Buyers and Sellers and provide a payment platform to complete transactions so you can broaden your reach. Through BidTru, easily accept payments from anywhere in the world with confidence.

                            Copyright © BidTru, 2014. All rights reserved.

{% endblock %}

redpajama_set_name: RedPajamaGithub


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

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>partes Class Hierarchy</title>
<meta name="date" content="2017-05-11">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Hierarchy For Package partes

Package Hierarchies:

All Packages

Class Hierarchy

java.lang.Object

java.awt.Component (implements java.awt.image.ImageObserver, java.awt.MenuContainer, java.io.Serializable)

java.awt.Container

java.awt.Window (implements javax.accessibility.Accessible)

java.awt.Frame (implements java.awt.MenuContainer)

javax.swing.JFrame (implements javax.accessibility.Accessible, javax.swing.RootPaneContainer, javax.swing.WindowConstants)

partes.VCerrarParte

partes.VParteAdministracion

partes.VVisualizarPartes

partes.Parte

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes


text:
//------------------------------------------------------------------------------------------------
// File:    volucrisguitradedisplay.h
//
// Desc:
//
// Copyright (c) 2007-2008 Unseen Studios.   All rights reserved.
//------------------------------------------------------------------------------------------------
#ifndef __VOLUCRISGUITRADEDISPLAY_H__
#define __VOLUCRISGUITRADEDISPLAY_H__

/**
 * Shows what's happening during a trade between this client and another
 */
class VolucrisGUITradeDisplay
{
    /**
     * One of the item lists in the inventory
     */
    class InventoryItemList : public VolucrisGUIInventoryItemList
    {
        public:

            /**
             * Initializes this class with its owning inventory
             */
            InventoryItemList(VolucrisGUITradeDisplay* trade);

            /**
             * Regenerates the list of items that this list shows.  The indices that are
             * in the trade are automatically selected.
             */
            bool updateDisplay(ClientAvatarInventoryItem inventory[AVATAR_INVENTORY_SIZE],
                                unsigned char* indicesInTrade, unsigned int numberOfIndices);

            /**
             * Gets the list of items that the user has selected
             */
            void getSelectedItems(
                unsigned char* inventoryIndexBuffer,
                size_t bufferSize,
                size_t* numberOfSelectedItems);

        protected:

            /**
             * This method updates the item text
             */
            void onMouseOverListEntryChanged();

            /**
             * When the selection changes, this method is invoked to notify the derived class
             */
            void onSelectionChanged();

        protected:

            /// The owner display structure
            VolucrisGUITradeDisplay* myDisplay;
    };

    /**
     * Displays the items that the players are offering to one another
     */
    class TradeItemList : public GUIList
    {
        /**
         * Handles an entry in this list
         */
        class TradeItemListEntry : public GUIList::ListEntry
        {
            /**
             * Watches for mouse input and changes the state of the list entry depending on it
             */
            class MouseSentinel : public GUIMouseSentinel
            {
                public:

                    /**
                     * Initializes this sentinel with its owner entry
                     */
                    MouseSentinel(TradeItemListEntry* listEntry);

                protected:

                    /**
                     * Called by the mouse input source when the mouse moves.  If the mouse
                     * @return 'true' To indicate the event should stop propogating
                     */
                    bool onMouseMove(GUIPoint position, GUIPoint oldPosition, GUIMouseInputSource* mouse);

                protected:

                    /// The entry that owns this sentinel
                    TradeItemListEntry* myListEntry;
            };

            public:

                /**
                 * Initializes this class
                 */
                TradeItemListEntry();

                /**
                 * Sets the rendering font for the text in this entry
                 */
                void setFont(GUIFont* font);

                /**
                 * Sets the text in this entry
                 */
                void setText(const std::string& text);

                /**
                 * Sets the texture for the elements
                 */
                void setGUITexture(LPDIRECT3DTEXTURE9 texture);

                /**
                 * Frees this element's texture reference if it exists
                 */
                void releaseGUITexture();

                /**
                 * Adds this list item's elements to the rendering process
                 */
                void registerElements(GUILayer* layer);

                /**
                 * Removes this list item's elements from the screen
                 */
                void unregisterElements(GUILayer* layer);

            public:

                /**
                 * Updates the clipping region of the internal elements
                 */
                void refresh();

            public:

                /**
                 * Sets the description for the item stored here.  This automatically
                 * updates the name of the item by calling setText.
                 */
                void setItem(ClientItemDescription* description, unsigned int quantity);

                /**
                 * Gets the item stored in this entry
                 */
                const ClientItemDescription* getItemDescription() const;

            protected:

                /// The mouse-input sentinel for this line
                MouseSentinel myLineMouseSentinel;

                /// The canvas for the background of this line
                GUICanvas myBackgroundCanvas;

                /// The renderer for this line's text
                ListEntryTextElement myTextElement;

                /// The element used to use to fill the background of this line
                GUIBorderedFillElement myBackground;

                /// The canvas to clip rendering to
                GUICanvas* myClipCanvas;

            protected:

                /// The description of the item displayed by this entry
                ClientItemDescription* myItemDescription;

                /// This item's quantity
                unsigned int myItemQuantity;
        };

        /**
         * This slider is used to scroll through the list
         */
        class VolucrisSlider : public GUISlider
        {
            public:

                /**
                 * Initializes this class
                 */
                VolucrisSlider(TradeItemList* list);

            protected:

                /**
                 * Called when the slider's state changes relative to user input.  If
                 * the state change is that the slider's position changed, this method
                 * updates the location of the list.
                 */
                virtual void onStateChange(StateChange stateChange);

            protected:

                /// The list that this slider controls
                TradeItemList* myList;
        };

        /**
         * This sentinel is responsible for resetting the mouse-over entry when the mouse leaves the list
         */
        class MouseLeftListSentinel : public GUIMouseSentinel
        {
            public:

                /**
                 * Initializes this class
                 */
                MouseLeftListSentinel(TradeItemList* list);

            protected:

                /**
                 * Called by the mouse input source when the mouse moves.  The default implementation propogates
                 * the message based on the focus/hierarchy structure established for the sentinels.
                 * @return 'true' To indicate the event should stop propogating
                 */
                bool onMouseMove(GUIPoint position, GUIPoint oldPosition, GUIMouseInputSource* mouse);

            protected:

                /// The list that contains this sentinel
                TradeItemList* myList;
        };

        public:

            /**
             * Initializes this class
             */
            TradeItemList();

            /**
             * Registers the visible elements with the screen
             */
            void registerElements(GUILayer* layer);

            /**
             * Removes elements from the given layer
             */
            void unregisterElements(GUILayer* layer);

            /**
             * Sets the GUI texture for this list
             */
            void setGUITexture(LPDIRECT3DTEXTURE9 guiTexture);

            /**
             * Removes this class's references to the GUI texture
             */
            void releaseGUITexture();

            /**
             * Gets this list's mouse sentinel so that it can be added to something which triggers its events
             */
            GUIMouseSentinel* getMouseSentinel();

            /**
             * Deselects all of the items in this list
             */
            void clearSelection();

            /**
             * Gets the canvas for this list so that it can be positioned
             */
            GUICanvas* getCanvas();

        protected:

            /// The canvas for this list
            GUICanvas myBackgroundCanvas;

            /// The background for the list
            GUIBorderedFillElement myBackgroundElement;

            /// The canvas for this list's slider
            GUICanvas mySliderCanvas;

            /// The slider for this list
            VolucrisSlider mySlider;

            /// The list's root mouse sentinel
            GUIMouseSentinel myRootMouseSentinel;

            /// The entries in this list
            TradeItemListEntry myListEntries[MAX_ITEMS_PER_TRADE];
            unsigned int myNumberOfItems;
    };

    public:

        /**
         * Initializes this class
         */
        VolucrisGUITradeDisplay();

        /**
         * Initializes this display of the trade window
         */
        bool create(ClientItemDescription* itemDescriptions, size_t numberOfItemDescriptions,
                     GUIFont* windowFont, GUIFont* titleFont, LPDIRECT3DTEXTURE9 guiTexture,
                     GUILayer* layer, GUIMouseSentinel* parentSentinel);

        /**
         * Erases all of the members of this display, and removes its components from the
         * display layer.
         */
        void destroy();

        /**
         * Sets up the renderer to display the given trade.  The indices that are traded
         * by this local client (from the inventory) are selected in the inventory display
         * list automatically.
         */
        void displayTrade(ClientAvatarInventoryItem inventory[AVATAR_INVENTORY_SIZE],
                           unsigned char* indicesInTrade, unsigned int numberOfIndices,
                           TradeItem* itemsOfferedByOther, unsigned int numberOfItemsOfferedByOther);

        /**
         * Removes all of this display's items from the screen and mouse input chain
         */
        void hideDisplay();

        /**
         * Gets the list of items that the user has selected in either the inventory.  After the
         * list has been populated, the selected items are cleared.  This is used to send
         * the update offer message to the server.
         */
        void getSelectedItemsAndClearSelection(unsigned char* inventoryIndexBuffer, size_t bufferSize, size_t* numberOfSelectedItems);

        /**
         * If the accept trade button was pushed, this method returns true.  Subsequent calls will return false
         * until the user pushes the equip button again.
         */
        bool pollAcceptTradeButton();

        /**
         * If the cancel trade button was pushed, this method returns true.  Subsequent calls will return false
         * until the user pushes the unequip button again.
         */
        bool pollCancelTradeButton();

        /**
         * If the update offer button was pushed, this method returns true.  Subsequent calls will return false
         * until the user pushes the unequip button again.
         */
        bool pollUpdateOfferButton();

    protected:

        /// The target layer for this display
        GUILayer* myRenderingLayer;

        /// The owner sentinel for this display
        GUIMouseSentinel* myParentSentinel;

        /// The source item description array, obtained from the client game file
        ClientItemDescription* myItemDescriptionsArray;
        unsigned int myItemDescriptionsArraySize;

        // Mouse-over item descriptions shown here
        VolucrisGUITitledPanel myItemDescriptionPanel;  /// The panel where the item descriptions are shown
        GUICanvas myItemDescriptionTextCanvas;          /// Text to display the item description
        GUITextLabelElement myItemDescriptionText;

        // The items being traded by the players
        TradeItemList myItemsToBeTradedAway;
        TradeItemList myItemsToBeReceived;

        // The player's inventory
        VolucrisGUITitledPanel myInventoryItemsPanel;   /// The panel that displays shows carried items
        InventoryItemList myInventoryItemList;          /// Part of the carried items panel; displays the items that the character is carrying

        // Various interaction buttons
        VolucrisGUIButton myAcceptTradeButton;   /// Accept the trade and lock it in
        VolucrisGUIButton myCancelTradeButton;   /// Gets out of the trade window
        VolucrisGUIButton myUpdateOfferButton;   /// Changes what the client is offering
};

#endif


text:
import Canva from './canvaImage';

/**
 * Image Object
 * @param domElement
 * @constructor
 */
const Image = function (domElement) {
    this.domElement = domElement;
};

Image.prototype = {
    getDomElement: function () {
        return this.domElement;
    },
    getHeight: function () {
        return this.domElement.offsetHeight;
    },
    getWidth: function () {
        return this.domElement.offsetWidth;
    }
};

/**
 * Video Object inherits from Image object
 * @param domElement
 * @constructor
 */
const Video = function (domElement) {
    Image.call(this, domElement);
    this.aspectRatio = domElement.getAttribute('data-ratio');
};

Video.prototype = new Image();
Video.prototype.constructor = Video;
Video.prototype.getCurrentTime = function () {
    return Math.floor(this.domElement.currentTime);
};
Video.prototype.getAspectRatio = function () {
    return this.aspectRatio;
};

/**
 * Cache Object
 * @constructor
 */
const Store = function () {
    this.datas = {};
};

Store.prototype = {
    set: function (id, item) {
        this.datas[id] = item;
        return this;
    },
    get: function (id) {
        if (!this.datas[id]) {
            throw 'Unknown ID';
        }
        return this.datas[id];
    },
    remove: function (id) {
        // never reuse same id
        this.datas[id] = null;
    },
    getLength: function () {
        let count = 0;
        for (let k in this.datas) {
            if (this.datas.hasOwnProperty(k)) {
                ++count;
            }
        }
        return count;
    }
};

/**
 * Screenshot Object
 * @param id
 * @param canva
 * @param video
 * @param altCanvas
 * @constructor
 */
const ScreenShot = function (id, canva, video, altCanvas) {

    const date = new Date();
    canva.resize(video);
    canva.copy(video);

    // handle alternative canvas:
    altCanvas = altCanvas === undefined ? [] : altCanvas;
    this.altScreenShots = [];
    if (altCanvas.length > 0) {
        for (let i = 0; i < altCanvas.length; i++) {
            let canvaEl = altCanvas[i].el;
            canvaEl.resize(video);
            canvaEl.copy(video);

            this.altScreenShots.push({
                dataURI: canvaEl.extractImage(),
                name: altCanvas[i].name
            });
        }
    }

    this.id = id;
    this.timestamp = date.getTime();
    this.dataURI = canva.extractImage();
    this.videoTime = video.getCurrentTime();

};

ScreenShot.prototype = {
    getId: function () {
        return this.id;
    },
    getDataURI: function () {
        return this.dataURI;
    },
    getTimeStamp: function () {
        return this.timestamp;
    },
    getVideoTime: function () {
        return this.videoTime;
    },
    getAltScreenShots: function () {
        return this.altScreenShots;
    }
};

/**
 * THUMB EDITOR
 * @param videoId
 * @param canvaId
 * @param outputOptions
 * @returns {{isSupported: isSupported, screenshot: screenshot, store: Store, copy: copy, getCanvaImage: getCanvaImage, resetCanva: resetCanva, getNbScreenshot: getNbScreenshot}}
 * @constructor
 */
const ScreenCapture = function (videoId, canvaId, outputOptions) {
    let editorVideo;
    const domElement = document.getElementById(videoId);

    if (domElement !== null) {
        editorVideo = new Video(domElement);
    }
    const store = new Store();

    function getCanva() {
        return document.getElementById(canvaId);
    }

    outputOptions = outputOptions || {};

    function setAltCanvas() {
        let domElements = [];
        let altCanvas = outputOptions.altCanvas;
        if (altCanvas.length > 0) {
            for (let i = 0; i < altCanvas.length; i++) {
                domElements.push({
                    el: new Canva(altCanvas[i]),
                    width: altCanvas[i].getAttribute('data-width'),
                    name: altCanvas[i].getAttribute('data-name')
                });
            }
        }
        return domElements;
    }

    return {
        isSupported: function () {
            const elem = document.createElement('canvas');

            return !!document.getElementById(videoId) && document.getElementById(canvaId)
                && !!elem.getContext && !!elem.getContext('2d');
        },
        screenshot: function () {
            const screenshot = new ScreenShot(
                store.getLength() + 1,
                new Canva(getCanva()),
                editorVideo,
                setAltCanvas()
            );

            store.set(screenshot.getId(), screenshot);

            return screenshot;
        },
        store: store,
        copy: function (mainSource, altSources) {

            const elementDomNode = document.createElement('img');
            elementDomNode.src = mainSource;

            const element = new Image(elementDomNode);
            const editorCanva = new Canva(getCanva());
            const altEditorCanva = setAltCanvas();
            editorCanva
                .reset()
                .resize(editorVideo)
                .copy(element);

            // handle alternative canvas:
            if (altEditorCanva.length > 0) {
                for (let i = 0; i < altEditorCanva.length; i++) {

                    let tmpEl = document.createElement('img');
                    tmpEl.src = altSources[i].dataURI;

                    const canvaEl = altEditorCanva[i].el;

                    canvaEl
                        .reset()
                        .resize(editorVideo, altEditorCanva[i].width)
                        .copy(new Image(tmpEl)); // @TODO: should copy the right stored image
                }
            }
        },
        getCanvaImage: function () {
            const canva = new Canva(getCanva());

            return canva.extractImage();
        },
        resetCanva: function () {
            const editorCanva = new Canva(getCanva());
            editorCanva.reset();
        },
        getNbScreenshot: function () {
            return store.getLength();
        }
    };
};

export default ScreenCapture;


text:
Flask-Settings
==============

This is an extension that uses a settings file for further customization of the application the reason we dont use the config file is to keep things cleaner and it is more safe this way,


text:
package hu.akarnokd.reactive4javaflow;

import org.junit.Test;

import java.util.concurrent.TimeUnit;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;

public class SchedulerServicesTest {
    @Test
    public void utilityClass() {
        TestHelper.checkUtilityClass(SchedulerServices.class);
    }

    @Test
    public void computationHolderUtility() {
        TestHelper.checkUtilityClass(SchedulerServices.ComputationHolder.class);
    }

    @Test
    public void singleHolderUtility() {
        TestHelper.checkUtilityClass(SchedulerServices.SingleHolder.class);
    }

    @Test
    public void ioHolderUtility() {
        TestHelper.checkUtilityClass(SchedulerServices.IOHolder.class);
    }

    @Test
    public void newThreadHolderUtility() {
        TestHelper.checkUtilityClass(SchedulerServices.NewThreadHolder.class);
    }

    @Test
    public void rejected() {
        assertEquals("Rejected", SchedulerService.REJECTED.toString());
        SchedulerService.REJECTED.close();
    }

    @Test
    public void restart() throws InterruptedException {
        SchedulerServices.shutdown();
        SchedulerServices.shutdown();
        try {
            Thread.sleep(100);

            for (Thread t : Thread.getAllStackTraces().keySet()) {
                if (t.getName().contains("Reactive4JavaFlow")
                        && !t.getName().contains("Reactive4JavaFlow.Cleaner")) {
                    fail("Thread still running: " + t);
                }
            }
        } finally {
            SchedulerServices.start();
            SchedulerServices.start();
        }

        Folyam.just(1).subscribeOn(SchedulerServices.computation())
                .test()
                .awaitDone(5, TimeUnit.SECONDS)
                .assertResult(1);

        Folyam.just(1).subscribeOn(SchedulerServices.single())
                .test()
                .awaitDone(5, TimeUnit.SECONDS)
                .assertResult(1);

        Folyam.just(1).subscribeOn(SchedulerServices.io())
                .test()
                .awaitDone(5, TimeUnit.SECONDS)
                .assertResult(1);

        Folyam.just(1).subscribeOn(SchedulerServices.newThread())
                .test()
                .awaitDone(5, TimeUnit.SECONDS)
                .assertResult(1);
    }

    @Test
    public void newSingle() throws InterruptedException {
        SchedulerService sch = SchedulerServices.newSingle("SchedulerServicesTest");
        try {
            Folyam.just(1).subscribeOn(sch)
                    .map(v -> Thread.currentThread().getName().contains("SchedulerServicesTest"))
                    .test()
                    .awaitDone(5, TimeUnit.SECONDS)
                    .assertResult(true);
        } finally {
            sch.shutdown();
        }

        Thread.sleep(100);

        for (Thread t : Thread.getAllStackTraces().keySet()) {
            if (t.getName().contains("SchedulerServicesTest")) {
                fail("Thread still running: " + t);
            }
        }

    }

    @Test
    public void newThread() throws InterruptedException {
        SchedulerService sch = SchedulerServices.newThread("SchedulerServicesTest");
        try {
            Folyam.just(1).subscribeOn(sch)
                    .map(v -> Thread.currentThread().getName().contains("SchedulerServicesTest"))
                    .test()
                    .awaitDone(5, TimeUnit.SECONDS)
                    .assertResult(true);
        } finally {
            sch.shutdown();
        }

        Thread.sleep(100);

        for (Thread t : Thread.getAllStackTraces().keySet()) {
            if (t.getName().contains("SchedulerServicesTest")) {
                fail("Thread still running: " + t);
            }
        }
    }

    @Test
    public void newParallel() throws InterruptedException {
        SchedulerService sch = SchedulerServices.newParallel(2, "SchedulerServicesTest");
        try {
            Folyam.range(1, 2).subscribeOn(sch)
                    .parallel(2)
                    .map(v -> Thread.currentThread().getName().contains("SchedulerServicesTest"))
                    .sequential()
                    .test()
                    .awaitDone(5, TimeUnit.SECONDS)
                    .assertResult(true, true);
        } finally {
            sch.shutdown();
        }

        Thread.sleep(100);

        for (Thread t : Thread.getAllStackTraces().keySet()) {
            if (t.getName().contains("SchedulerServicesTest")) {
                fail("Thread still running: " + t);
            }
        }
    }
}


text:
import collections
import random

EllipticCurve = collections.namedtuple('EllipticCurve', 'name p a b g n h')

curve = EllipticCurve(
    'secp256k1',
    # Field characteristic.
    p=0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f,
    # Curve coefficients.
    a=0,
    b=7,
    # Base point.
    g=(0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798,
       0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8),
    # Subgroup order.
    n=0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141,
    # Subgroup cofactor.
    h=1,
)

# Modular arithmetic ##########################################################

def inverse_mod(k, p):
    """Returns the inverse of k modulo p.

    This function returns the only integer x such that (x * k) % p == 1.

    k must be non-zero and p must be a prime.
    """
    if k == 0:
        raise ZeroDivisionError('division by zero')

    if k < 0:
        # k ** -1 = p - (-k) ** -1  (mod p)
        return p - inverse_mod(-k, p)

    # Extended Euclidean algorithm.
    s, old_s = 0, 1
    t, old_t = 1, 0
    r, old_r = p, k

    while r != 0:
        quotient = old_r // r
        old_r, r = r, old_r - quotient * r
        old_s, s = s, old_s - quotient * s
        old_t, t = t, old_s - quotient * t

    gcd, x, y = old_r, old_s, old_t

    assert gcd == 1
    assert (k * x) % p == 1

    return x % p

# Functions that work on curve points #########################################

def is_on_curve(point):
    """Returns True if the given point lies on the elliptic curve."""
    if point is None:
        # None represents the point at infinity.
        return True

    x, y = point

    return (y * y - x * x * x - curve.a * x - curve.b) % curve.p == 0

def point_neg(point):
    """Returns -point."""
    assert is_on_curve(point)

    if point is None:
        # -0 = 0
        return None

    x, y = point
    result = (x, -y % curve.p)

    assert is_on_curve(result)

    return result

def point_add(point1, point2):
    """Returns the result of point1 + point2 according to the group law."""
    assert is_on_curve(point1)
    assert is_on_curve(point2)

    if point1 is None:
        # 0 + point2 = point2
        return point2
    if point2 is None:
        # point1 + 0 = point1
        return point1

    x1, y1 = point1
    x2, y2 = point2

    if x1 == x2 and y1 != y2:
        # point1 + (-point1) = 0
        return None

    if x1 == x2:
        # This is the case point1 == point2.
        m = (3 * x1 * x1 + curve.a) * inverse_mod(2 * y1, curve.p)
    else:
        # This is the case point1 != point2.
        m = (y1 - y2) * inverse_mod(x1 - x2, curve.p)

    x3 = m * m - x1 - x2
    y3 = y1 + m * (x3 - x1)
    result = (x3 % curve.p,
              -y3 % curve.p)

    assert is_on_curve(result)

    return result

def scalar_mult(k, point):
    """Returns k * point computed using the double and point_add algorithm."""
    assert is_on_curve(point)

    if k % curve.n == 0 or point is None:
        return None

    if k < 0:
        # k * point = -k * (-point)
        return scalar_mult(-k, point_neg(point))

    result = None
    addend = point

    while k:
        if k & 1:
            # Add.
            result = point_add(result, addend)

        # Double.
        addend = point_add(addend, addend)

        k >>= 1

    assert is_on_curve(result)

    return result

# Keypair generation and ECDHE ################################################

def make_keypair():
    """Generates a random private-public key pair."""
    private_key = random.randrange(1, curve.n)
    public_key = scalar_mult(private_key, curve.g)

    return private_key, public_key

print('Curve:', curve.name)

# Alice generates her own keypair.
alice_private_key, alice_public_key = make_keypair()
print("Alice's private key:", hex(alice_private_key))
print("Alice's public key: (0x{:x}, 0x{:x})".format(*alice_public_key))

# Bob generates his own key pair.
bob_private_key, bob_public_key = make_keypair()
print("Bob's private key:", hex(bob_private_key))
print("Bob's public key: (0x{:x}, 0x{:x})".format(*bob_public_key))

# Alice and Bob exchange their public keys and calculate the shared secret.
s1 = scalar_mult(alice_private_key, bob_public_key)
s2 = scalar_mult(bob_private_key, alice_public_key)
assert s1 == s2

print('Shared secret: (0x{:x}, 0x{:x})'.format(*s1))


text:
'use strict';

angular.module('fullstackJobApp')
	.controller('ViewResumesCtrl', ['$stateParams', '$state', '$scope', '$location', 'Resume' ,
		function ($stateParams, $state, $scope, $location, Resume) {
			var self = this;

			self.page = $stateParams.page || 1;
			self.itemsPerPage = $stateParams.itemsPerPage || 2;

			self.pagination = {
				page: 1,
				itemsPerPage: 2,
				maxSize: 5,
				numPages: null,
				totalItems: null
			};

			var init = function () {
				loadResumes();
			};

			var loadResumes = function () {
				var page = self.page;
				var itemsPerPage = self.itemsPerPage;

				Resume.index({
					page: page,
					itemsPerPage: itemsPerPage
				}, function (data) {
					var totalItems = data.count;
					self.resumes = data.resumes;
					console.log(self.resumes);

					self.pagination.totalItems = totalItems;
					self.pagination.numPages = totalItems / itemsPerPage;
					self.pagination.page = self.page;
					self.pagination.itemsPerPage = self.itemsPerPage;

				});
			};

			self.pageChanged = function () {
      			var pagination = self.pagination;
     	 		self.page = self.pagination.page;
      			self.itemsPerPage = self.pagination.itemsPerPage;
      			$location
        		.search('page', pagination.page)
        		.search('itemsPerPage', pagination.itemsPerPage);
      			loadResumes();
    		};

			init();

		}]);


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

    <!--

        Licensed to the Apache Software Foundation (ASF) under one or more
        contributor license agreements.  See the NOTICE file distributed with
        this work for additional information regarding copyright ownership.
        The ASF 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.
    -->

    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>org.apache.servicemix.nmr.examples</groupId>
        <artifactId>org.apache.servicemix.nmr.examples.interceptors</artifactId>
        <version>1.1.0-SNAPSHOT</version>
    </parent>

    <groupId>org.apache.servicemix.nmr.examples.interceptors</groupId>
    <artifactId>exchange</artifactId>
    <packaging>bundle</packaging>
    <name>Apache ServiceMix NMR Example:: Exchange Listener</name>

    <dependencies>
        <dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
            <version>${commons.logging.version}</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.servicemix.nmr</groupId>
            <artifactId>org.apache.servicemix.nmr.api</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.felix</groupId>
                <artifactId>maven-bundle-plugin</artifactId>
                <configuration>
                    <instructions>
                        <Bundle-SymbolicName>${pom.artifactId}</Bundle-SymbolicName>
                        <Import-Package>
                            org.apache.commons.logging,
                            org.apache.servicemix.nmr.api,
                            org.apache.servicemix.nmr.api.event,
                            org.apache.servicemix.nmr.api.internal
                        </Import-Package>
                        <Private-Package>org.apache.servicemix.nmr.examples.interceptors.exchange</Private-Package>
                    </instructions>
                </configuration>
             </plugin>
        </plugins>
    </build>

</project>


text:
set -eu -o pipefail

readonly PROJECT_NAME="angular-payload-size"
NODE_MODULES_BIN=$PROJECT_ROOT/node_modules/.bin/

# Get the gzip size of a file with the specified compression level.
#   $1: string - The file path.
#   $2: number - The level of compression.
getGzipSize() {
  local filePath=$1
  local compLevel=$2
  local compPath=$1$2.gz
  local size=-1

  gzip -c -$compLevel "$filePath" >> "$compPath"
  size=$(stat -c%s "$compPath")
  rm "$compPath"

  echo $size
}

# Calculate the size of target file uncompressed size, gzip7 size, gzip9 size
# Write to global variable $payloadData, $filename
calculateSize() {
  label=$(echo "$filename" | sed "s/.*\///" | sed "s/\..*//")

  rawSize=$(stat -c%s "$filename")
  gzip7Size=$(getGzipSize "$filename" 7)
  gzip9Size=$(getGzipSize "$filename" 9)

  # Log the sizes (for information/debugging purposes).
  printf "Size: %6d  (gzip7: %6d, gzip9: %6d)  %s\n" $rawSize $gzip7Size $gzip9Size $label

  payloadData="$payloadData\"uncompressed/$label\": $rawSize, "
  payloadData="$payloadData\"gzip7/$label\": $gzip7Size, "
  payloadData="$payloadData\"gzip9/$label\": $gzip9Size, "
}

# Check whether the file size is under limit.
# Exit with an error if limit is exceeded.
#   $1: string - The name in database.
#   $2: string - The payload size limit file.
checkSize() {
  name="$1"
  limitFile="$2"

  # In non-PR builds, `CI_BRANCH` is the branch being built (e.g. `pull/12345`), not the targeted branch.
  # Thus, PRs will fall back to using the size limits for `master`.
  node ${PROJECT_ROOT}/scripts/ci/payload-size.js $limitFile $name $CI_BRANCH $CI_COMMIT
}

# Write timestamp to global variable `$payloadData`.
addTimestamp() {
  # Add Timestamp
  timestamp=$(date +%s)
  payloadData="$payloadData\"timestamp\": $timestamp, "
}

# Write the current CI build URL to global variable `$payloadData`.
# This allows mapping the data stored in the database to the CI build job that generated it, which
# might contain more info/context.
#   $1: string - The CI build URL.
addBuildUrl() {
  buildUrl="$1"
  payloadData="$payloadData\"buildUrl\": \"$buildUrl\", "
}

# Write the commit message for the current CI commit range to global variable `$payloadData`.
#   $1: string - The commit range for this build (in `<SHA-1>...<SHA-2>` format).
addMessage() {
  commitRange="$1"

  # Grab the set of SHAs for the message. This can fail when you force push or do initial build
  # because $CI_COMMIT_RANGE may contain the previous SHA which will not be in the
  # force push or commit, hence we default to last commit.
  message=$(git log --oneline $commitRange -- || git log --oneline -n1)
  message=$(echo $message | sed 's/\\/\\\\/g' | sed 's/"/\\"/g')
  payloadData="$payloadData\"message\": \"$message\", "
}

# Convert the current `payloadData` value to a JSON string.
# (Basically remove trailing `,` and wrap in `{...}`.)
payloadToJson() {
  echo "{$(sed -r 's|, *$||' <<< $payloadData)}"
}

# Upload data to firebase database if it's commit, print out data for pull requests.
#   $1: string - The name in database.
uploadData() {
  name="$1"

  readonly safeBranchName=$(echo $CI_BRANCH | sed -e 's/\./_/g')
  readonly dbPath=/payload/$name/$safeBranchName/$CI_COMMIT
  readonly jsonPayload=$(payloadToJson)

  # WARNING: CI_SECRET_PAYLOAD_FIREBASE_TOKEN should NOT be printed.
  set +x
  $NODE_MODULES_BIN/firebase database:update --data "$jsonPayload" --project $PROJECT_NAME --confirm --token "$CI_SECRET_PAYLOAD_FIREBASE_TOKEN" $dbPath
}

# Track payload size.
#   $1: string       - The name in database.
#   $2: string       - The file path.
#   $3: true | false - Whether to check the payload size and fail the test if it exceeds limit.
#   $4: [string]     - The payload size limit file. Only necessary if `$3` is `true`.
trackPayloadSize() {
  name="$1"
  path="$2"
  checkSize="$3"
  limitFile="${4:-}"

  payloadData=""

  # Calculate the file sizes.
  echo "Calculating sizes for files in '$path'..."
  for filename in $path; do
    calculateSize
  done

  # Save the file sizes to be retrieved from `payload-size.js`.
  echo "$(payloadToJson)" > /tmp/current.log

  # If this is a non-PR build, upload the data to firebase.
  if [[ "$CI_PULL_REQUEST" == "false" ]]; then
    echo "Uploading data for '$name'..."
    addTimestamp
    addBuildUrl $CI_BUILD_URL
    addMessage $CI_COMMIT_RANGE
    uploadData $name
  else
    echo "Skipped uploading data for '$name', because this is a pull request."
  fi

  # Check the file sizes against the specified limits.
  if [[ $checkSize = true ]]; then
    echo "Verifying sizes against '$limitFile'..."
    checkSize $name $limitFile
  else
    echo "Skipped verifying sizes (checkSize: false)."
  fi
}


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

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Uses of Class org.apache.commons.math3.util.KthSelector (Apache Commons Math 3.6.1 API)</title>
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Class
org.apache.commons.math3.util.KthSelector

Packages that use KthSelector

Package
Description

org.apache.commons.math3.stat.descriptive.rank

Summary statistics based on ranks.

Uses of KthSelector in org.apache.commons.math3.stat.descriptive.rank

Methods in org.apache.commons.math3.stat.descriptive.rank that return KthSelector

Modifier and Type
Method and Description

KthSelector
Percentile.getKthSelector()

Get the kthSelector used for computation.

Methods in org.apache.commons.math3.stat.descriptive.rank with parameters of type KthSelector

Modifier and Type
Method and Description

protected double
Percentile.EstimationType.estimate(double[] work,
        int[] pivotsHeap,
        double pos,
        int length,
        KthSelector selector)

Estimation based on Kth selection.

double
Percentile.EstimationType.evaluate(double[] work,
        double p,
        KthSelector selector)

Evaluate method to compute the percentile for a given bounded array.

protected double
Percentile.EstimationType.evaluate(double[] work,
        int[] pivotsHeap,
        double p,
        KthSelector selector)

Evaluate method to compute the percentile for a given bounded array
 using earlier computed pivots heap.

 This basically calls the index and then
 estimate
 functions to return the estimated percentile value.

Percentile
Percentile.withKthSelector(KthSelector newKthSelector)

Build a new instance similar to the current one except for the
 kthSelector instance specifically set.

Median
Median.withKthSelector(KthSelector newKthSelector)

Build a new instance similar to the current one except for the
 kthSelector instance specifically set.

Constructors in org.apache.commons.math3.stat.descriptive.rank with parameters of type KthSelector

Constructor and Description

Percentile(double quantile,
          Percentile.EstimationType estimationType,
          NaNStrategy nanStrategy,
          KthSelector kthSelector)

Constructs a Percentile with the specific quantile value,
 Percentile.EstimationType, NaNStrategy and KthSelector.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Copyright © 2003–2016 The Apache Software Foundation. All rights reserved.


text:
package jodd.mail;

import org.junit.Test;

import javax.mail.internet.AddressException;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;

public class MailAddressTest {

	@Test
	public void testMailFromString() {
		MailAddress mailAddress = new MailAddress("admin@jodd.com");
		assertNull(mailAddress.getPersonalName());
		assertEquals("admin@jodd.com", mailAddress.getEmail());
		assertEquals("admin@jodd.com", mailAddress.toString());

		mailAddress = new MailAddress("Jenny Doe <admin@jodd.com>");
		assertEquals("Jenny Doe", mailAddress.getPersonalName());
		assertEquals("admin@jodd.com", mailAddress.getEmail());
		assertEquals("Jenny Doe <admin@jodd.com>", mailAddress.toString());

		mailAddress = new MailAddress("Jenny Doe ", "admin@jodd.com");
		assertEquals("Jenny Doe ", mailAddress.getPersonalName());
		assertEquals("admin@jodd.com", mailAddress.getEmail());
		assertEquals("Jenny Doe  <admin@jodd.com>", mailAddress.toString());
	}

	@Test
	public void testMailFromEmailAddress() {
		MailAddress mailAddress = new MailAddress(new EmailAddress("admin@jodd.com"));
		assertNull(mailAddress.getPersonalName());
		assertEquals("admin@jodd.com", mailAddress.getEmail());

		mailAddress = new MailAddress(new EmailAddress("Jenny Doe <admin@jodd.com>"));
		assertEquals("Jenny Doe", mailAddress.getPersonalName());
		assertEquals("admin@jodd.com", mailAddress.getEmail());

		MailAddress mailAddress2 = new MailAddress(mailAddress.toEmailAddress());
		assertEquals("Jenny Doe", mailAddress2.getPersonalName());
		assertEquals("admin@jodd.com", mailAddress2.getEmail());
	}

	@Test
	public void testMailFromInternetAddress() throws AddressException {
		MailAddress mailAddress = new MailAddress(new EmailAddress("Jenny Doe <admin@jodd.com>"));
		MailAddress mailAddress2 = new MailAddress(mailAddress.toInternetAddress());

		assertEquals("Jenny Doe", mailAddress2.getPersonalName());
		assertEquals("admin@jodd.com", mailAddress2.getEmail());
	}

	@Test
	public void testIssue211() {
		String testAddress = "Some One<someone@yahoo.com>";
		MailAddress addr = new MailAddress(testAddress);

		assertEquals("Some One <someone@yahoo.com>", addr.toString());
	}
}


text:
import sys
import wx

import app_info
import resources
from hyper_link_ctrl import HyperLinkCtrl

license = app_info.copyright + u"""

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.
"""

class AboutDialog(wx.Dialog):
    def __init__(self, parent, env):
        wx.Dialog.__init__(self, parent, title="About " + app_info.name)
        self.env = env

        logo_font_size = 25 if sys.platform == "__WXMAC__" else 20
        subtitle_font_size = 24 if sys.platform == "__WXMAC__" else 10

        version_text = "Version %s (Released %s)" % (app_info.version_string, app_info.release_date.strftime("%Y-%m-%d"))

        bitmap_devo = wx.StaticBitmap(self)
        bitmap_devo.SetBitmap(resources.load_bitmap("icons/devo-icon-64.png"))

        fontsize = self.GetFont().PointSize
        label_devo = wx.StaticText(self, label=app_info.name)
        label_devo.SetFont(wx.Font(fontsize * 2.5, wx.FONTFAMILY_SWISS, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_BOLD))
        label_devolved = wx.StaticText(self, label="      Text Editing Devolved")
        label_devolved.SetFont(wx.Font(fontsize * 1.25, wx.FONTFAMILY_SWISS, wx.FONTSTYLE_ITALIC, wx.FONTWEIGHT_NORMAL))
        label_version = wx.StaticText(self, label=version_text)

        label_developer = wx.StaticText(self, label=app_info.developer)
        link_website = HyperLinkCtrl(self, wx.ID_ANY, label=app_info.url, url=app_info.url)

        btn_sizer = wx.BoxSizer(wx.HORIZONTAL)
        btn_license = wx.Button(self, label="License")
        btn_ok = wx.Button(self, wx.ID_OK)
        btn_ok.SetDefault()
        btn_sizer.Add(btn_license)
        btn_sizer.AddStretchSpacer()
        btn_sizer.Add(btn_ok)

        logo_text_sizer = wx.BoxSizer(wx.VERTICAL)
        logo_text_sizer.Add(label_devo, 0, wx.LEFT | wx.RIGHT | wx.TOP, 10)
        logo_text_sizer.Add(label_devolved, 0, wx.LEFT | wx.RIGHT, 10)

        logo_sizer = wx.BoxSizer(wx.HORIZONTAL)
        logo_sizer.Add(bitmap_devo, 0, wx.ALIGN_CENTER_VERTICAL)
        logo_sizer.Add(logo_text_sizer, 1, wx.ALIGN_CENTER_VERTICAL)

        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(logo_sizer, 0, wx.LEFT | wx.RIGHT | wx.TOP, 20)
        sizer.AddSpacer(15)
        sizer.Add(label_version, 0, wx.LEFT | wx.RIGHT, 20)
        sizer.AddSpacer(5)
        sizer.Add(label_developer, 0, wx.LEFT | wx.RIGHT, 20)
        sizer.AddSpacer(5)
        sizer.Add(link_website, 0, wx.LEFT | wx.RIGHT, 20)
        sizer.AddSpacer(5)
        sizer.Add(btn_sizer, 0, wx.ALL | wx.EXPAND, 10)

        self.SetSizer(sizer)
        self.Fit()
        self.Centre()

        self.Bind(wx.EVT_BUTTON, self.OnLicense, btn_license)

    def OnLicense(self, evt):
        self.EndModal(wx.ID_OK)
        self.env.open_static_text("Devo License", license)

if __name__ == "__main__":
    app = wx.App()
    dlg = AboutDialog(None, None)
    dlg.ShowModal()


text:
package fsm

import (
	"errors"
	"testing"
)

func TestInvalidEventError(t *testing.T) {
	event := "invalid event"
	state := "state"
	e := InvalidEventError{Event: event, State: state}
	if e.Error() != "event "+e.Event+" inappropriate in current state "+e.State {
		t.Error("InvalidEventError string mismatch")
	}
}

func TestUnknownEventError(t *testing.T) {
	event := "invalid event"
	e := UnknownEventError{Event: event}
	if e.Error() != "event "+e.Event+" does not exist" {
		t.Error("UnknownEventError string mismatch")
	}
}

func TestInTransitionError(t *testing.T) {
	event := "in transition"
	e := InTransitionError{Event: event}
	if e.Error() != "event "+e.Event+" inappropriate because previous transition did not complete" {
		t.Error("InTransitionError string mismatch")
	}
}

func TestNotInTransitionError(t *testing.T) {
	e := NotInTransitionError{}
	if e.Error() != "transition inappropriate because no state change in progress" {
		t.Error("NotInTransitionError string mismatch")
	}
}

func TestNoTransitionError(t *testing.T) {
	e := NoTransitionError{}
	if e.Error() != "no transition" {
		t.Error("NoTransitionError string mismatch")
	}
	e.Err = errors.New("no transition")
	if e.Error() != "no transition with error: "+e.Err.Error() {
		t.Error("NoTransitionError string mismatch")
	}
}

func TestCanceledError(t *testing.T) {
	e := CanceledError{}
	if e.Error() != "transition canceled" {
		t.Error("CanceledError string mismatch")
	}
	e.Err = errors.New("canceled")
	if e.Error() != "transition canceled with error: "+e.Err.Error() {
		t.Error("CanceledError string mismatch")
	}
}

func TestAsyncError(t *testing.T) {
	e := AsyncError{}
	if e.Error() != "async started" {
		t.Error("AsyncError string mismatch")
	}
	e.Err = errors.New("async")
	if e.Error() != "async started with error: "+e.Err.Error() {
		t.Error("AsyncError string mismatch")
	}
}

func TestInternalError(t *testing.T) {
	e := InternalError{}
	if e.Error() != "internal error on state transition" {
		t.Error("InternalError string mismatch")
	}
}


text:
package encoders

import (
	"bytes"
	"errors"
	"fmt"
	"io"
)

const (
	id   = "id: %d\n"
	data = "data: %s\n"
)

type sseEncoder struct {
	io.ReadCloser       // stores the original reader
	offset        int64 // offset for Seek purposes
}

// NewSSEEncoder creates a new server-sent event encoder
func NewSSEEncoder(r io.ReadCloser) Encoder {
	return &sseEncoder{ReadCloser: r}
}

func (r *sseEncoder) Seek(offset int64, whence int) (n int64, err error) {
	if seeker, ok := r.ReadCloser.(io.ReadSeeker); ok {
		r.offset, err = seeker.Seek(offset, whence)
	} else {
		// The underlying reader doesn't support seeking, but
		// we should still update the offset so the IDs will
		// properly reflect the adjusted offset.

		if whence != io.SeekStart {
			return 0, errors.New("Only SeekStart is supported")
		}
		r.offset += offset
	}

	return r.offset, err
}

func (r *sseEncoder) Read(p []byte) (n int, err error) {
	// We assume SSE won't add more than twice the amount of data we get
	q := make([]byte, len(p)/2)
	n, err = r.ReadCloser.Read(q)

	if n > 0 {
		buf := format(r.offset, q[:n])
		if len(buf) > len(p) {
			return 0, errors.New("buffer length cannot be higher than bytes array")
		}

		r.offset += int64(n)
		n = copy(p, buf)
	}

	return n, err
}

func format(pos int64, msg []byte) []byte {
	buf := bytes.NewBufferString(fmt.Sprintf(id, pos+int64(len(msg))))

	for _, line := range bytes.Split(msg, []byte{'\n'}) {
		buf.WriteString(fmt.Sprintf(data, line))
	}
	buf.Write([]byte{'\n'})

	return buf.Bytes()
}


text:
package com.example.android.testing.notes.notes;

import com.example.android.testing.notes.Injection;
import com.example.android.testing.notes.addnote.AddNoteActivity;
import com.example.android.testing.notes.notedetail.NoteDetailActivity;
import com.example.android.testing.notes.R;
import com.example.android.testing.notes.data.Note;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

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

import static com.google.common.base.Preconditions.checkNotNull;

/**
 * Display a grid of {@link Note}s
 */
public class NotesFragment extends Fragment implements NotesContract.View {

    private static final int REQUEST_ADD_NOTE = 1;

    private NotesContract.UserActionsListener mActionsListener;

    private NotesAdapter mListAdapter;

    public NotesFragment() {
        // Requires empty public constructor
    }

    public static NotesFragment newInstance() {
        return new NotesFragment();
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mListAdapter = new NotesAdapter(new ArrayList<Note>(0), mItemListener);
        mActionsListener = new NotesPresenter(Injection.provideNotesRepository(), this);
    }

    @Override
    public void onResume() {
        super.onResume();
        mActionsListener.loadNotes(false);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        setRetainInstance(true);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        // If a note was successfully added, show snackbar
        if (REQUEST_ADD_NOTE == requestCode && Activity.RESULT_OK == resultCode) {
            Snackbar.make(getView(), getString(R.string.successfully_saved_note_message),
                    Snackbar.LENGTH_SHORT).show();
        }
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.fragment_notes, container, false);
        RecyclerView recyclerView = (RecyclerView) root.findViewById(R.id.notes_list);
        recyclerView.setAdapter(mListAdapter);

        int numColumns = getContext().getResources().getInteger(R.integer.num_notes_columns);

        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new GridLayoutManager(getContext(), numColumns));

        // Set up floating action button
        FloatingActionButton fab =
                (FloatingActionButton) getActivity().findViewById(R.id.fab_add_notes);

        fab.setImageResource(R.drawable.ic_add);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mActionsListener.addNewNote();
            }
        });

        // Pull-to-refresh
        SwipeRefreshLayout swipeRefreshLayout =
                (SwipeRefreshLayout) root.findViewById(R.id.refresh_layout);
        swipeRefreshLayout.setColorSchemeColors(
                ContextCompat.getColor(getActivity(), R.color.colorPrimary),
                ContextCompat.getColor(getActivity(), R.color.colorAccent),
                ContextCompat.getColor(getActivity(), R.color.colorPrimaryDark));
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                mActionsListener.loadNotes(true);
            }
        });
        return root;
    }

    /**
     * Listener for clicks on notes in the RecyclerView.
     */
    NoteItemListener mItemListener = new NoteItemListener() {
        @Override
        public void onNoteClick(Note clickedNote) {
            mActionsListener.openNoteDetails(clickedNote);
        }
    };

    @Override
    public void setProgressIndicator(final boolean active) {

        if (getView() == null) {
            return;
        }
        final SwipeRefreshLayout srl =
                (SwipeRefreshLayout) getView().findViewById(R.id.refresh_layout);

        // Make sure setRefreshing() is called after the layout is done with everything else.
        srl.post(new Runnable() {
            @Override
            public void run() {
                srl.setRefreshing(active);
            }
        });
    }

    @Override
    public void showNotes(List<Note> notes) {
        mListAdapter.replaceData(notes);
    }

    @Override
    public void showAddNote() {
        Intent intent = new Intent(getContext(), AddNoteActivity.class);
        startActivityForResult(intent, REQUEST_ADD_NOTE);
    }

    @Override
    public void showNoteDetailUi(String noteId) {
        // in it's own Activity, since it makes more sense that way and it gives us the flexibility
        // to show some Intent stubbing.
        Intent intent = new Intent(getContext(), NoteDetailActivity.class);
        intent.putExtra(NoteDetailActivity.EXTRA_NOTE_ID, noteId);
        startActivity(intent);
    }

    private static class NotesAdapter extends RecyclerView.Adapter<NotesAdapter.ViewHolder> {

        private List<Note> mNotes;
        private NoteItemListener mItemListener;

        public NotesAdapter(List<Note> notes, NoteItemListener itemListener) {
            setList(notes);
            mItemListener = itemListener;
        }

        @Override
        public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            Context context = parent.getContext();
            LayoutInflater inflater = LayoutInflater.from(context);
            View noteView = inflater.inflate(R.layout.item_note, parent, false);

            return new ViewHolder(noteView, mItemListener);
        }

        @Override
        public void onBindViewHolder(ViewHolder viewHolder, int position) {
            Note note = mNotes.get(position);

            viewHolder.title.setText(note.getTitle());
            viewHolder.description.setText(note.getDescription());
        }

        public void replaceData(List<Note> notes) {
            setList(notes);
            notifyDataSetChanged();
        }

        private void setList(List<Note> notes) {
            mNotes = checkNotNull(notes);
        }

        @Override
        public int getItemCount() {
            return mNotes.size();
        }

        public Note getItem(int position) {
            return mNotes.get(position);
        }

        public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

            public TextView title;

            public TextView description;
            private NoteItemListener mItemListener;

            public ViewHolder(View itemView, NoteItemListener listener) {
                super(itemView);
                mItemListener = listener;
                title = (TextView) itemView.findViewById(R.id.note_detail_title);
                description = (TextView) itemView.findViewById(R.id.note_detail_description);
                itemView.setOnClickListener(this);
            }

            @Override
            public void onClick(View v) {
                int position = getAdapterPosition();
                Note note = getItem(position);
                mItemListener.onNoteClick(note);

            }
        }
    }

    public interface NoteItemListener {

        void onNoteClick(Note clickedNote);
    }

}


text:
module ActiveAdmin

  # All Pages controllers inherit from this controller.
  class PageController < BaseController

    # Active admin actions don't require layout.  All custom actions do.
    ACTIVE_ADMIN_ACTIONS = [:index]

    actions :index

    if ActiveAdmin::Dependency.rails >= 4
      before_action :authorize_access!
    else
      before_filter :authorize_access!
    end

    def index(options={}, &block)
      render "active_admin/page/index"
    end

    def clear_page_actions!
      active_admin_config.clear_page_actions!
    end

    private

    def authorize_access!
      permission = action_to_permission(params[:action])
      authorize! permission, active_admin_config
    end

  end
end


text:
create temporary tablespace jison_temp tempfile 'C:\APP\ADMINISTRATOR\ORADATA\ORCL\jison_temp.dbf' size 64m autoextend
on next 64m maxsize 2048m extent management local;

create tablespace jison_blog logging datafile 'C:\APP\ADMINISTRATOR\ORADATA\ORCL\jison_blog.dbf' size 64m autoextend
 on next 64m maxsize 2048m extent management local;

 create user jison identified by jison default tablespace jison_blog temporary tablespace jison_temp;

grant connect, resource, unlimited tablespace to jison;


text:
namespace mscorlib
{
	namespace System
	{
		namespace Runtime
		{
			namespace InteropServices
			{

				//Public Methods Tests

				// Method GetTypeAttr
				//		Signature: mscorlib::System::IntPtr ppTypeAttr
				TEST(mscorlib_System_Runtime_InteropServices_UCOMITypeInfo_Fixture,GetTypeAttr_Test)
				{

				}

				// Method GetTypeComp
				//		Signature: mscorlib::System::Runtime::InteropServices::UCOMITypeComp ppTComp
				TEST(mscorlib_System_Runtime_InteropServices_UCOMITypeInfo_Fixture,GetTypeComp_Test)
				{

				}

				// Method GetFuncDesc
				//		Signature: mscorlib::System::Int32 index, mscorlib::System::IntPtr ppFuncDesc
				TEST(mscorlib_System_Runtime_InteropServices_UCOMITypeInfo_Fixture,GetFuncDesc_Test)
				{

				}

				// Method GetVarDesc
				//		Signature: mscorlib::System::Int32 index, mscorlib::System::IntPtr ppVarDesc
				TEST(mscorlib_System_Runtime_InteropServices_UCOMITypeInfo_Fixture,GetVarDesc_Test)
				{

				}

				// Method GetNames
				//		Signature: mscorlib::System::Int32 memid, std::vector<mscorlib::System::String*> rgBstrNames, mscorlib::System::Int32 cMaxNames, mscorlib::System::Int32 pcNames
				TEST(mscorlib_System_Runtime_InteropServices_UCOMITypeInfo_Fixture,GetNames_Test)
				{

				}

				// Method GetRefTypeOfImplType
				//		Signature: mscorlib::System::Int32 index, mscorlib::System::Int32 href
				TEST(mscorlib_System_Runtime_InteropServices_UCOMITypeInfo_Fixture,GetRefTypeOfImplType_Test)
				{

				}

				// Method GetImplTypeFlags
				//		Signature: mscorlib::System::Int32 index, mscorlib::System::Int32 pImplTypeFlags
				TEST(mscorlib_System_Runtime_InteropServices_UCOMITypeInfo_Fixture,GetImplTypeFlags_Test)
				{

				}

				// Method GetIDsOfNames
				//		Signature: std::vector<mscorlib::System::String*> rgszNames, mscorlib::System::Int32 cNames, std::vector<mscorlib::System::Int32*> pMemId
				TEST(mscorlib_System_Runtime_InteropServices_UCOMITypeInfo_Fixture,GetIDsOfNames_Test)
				{

				}

				// Method Invoke
				//		Signature: mscorlib::System::Object pvInstance, mscorlib::System::Int32 memid, mscorlib::System::Int16 wFlags, mscorlib::System::Runtime::InteropServices::DISPPARAMS pDispParams, mscorlib::System::Object pVarResult, mscorlib::System::Runtime::InteropServices::EXCEPINFO pExcepInfo, mscorlib::System::Int32 puArgErr
				TEST(mscorlib_System_Runtime_InteropServices_UCOMITypeInfo_Fixture,Invoke_Test)
				{

				}

				// Method GetDocumentation
				//		Signature: mscorlib::System::Int32 index, mscorlib::System::String strName, mscorlib::System::String strDocString, mscorlib::System::Int32 dwHelpContext, mscorlib::System::String strHelpFile
				TEST(mscorlib_System_Runtime_InteropServices_UCOMITypeInfo_Fixture,GetDocumentation_Test)
				{

				}

				// Method GetDllEntry
				//		Signature: mscorlib::System::Int32 memid, mscorlib::System::Runtime::InteropServices::INVOKEKIND::__ENUM__ invKind, mscorlib::System::String pBstrDllName, mscorlib::System::String pBstrName, mscorlib::System::Int16 pwOrdinal
				TEST(mscorlib_System_Runtime_InteropServices_UCOMITypeInfo_Fixture,GetDllEntry_Test)
				{

				}

				// Method GetRefTypeInfo
				//		Signature: mscorlib::System::Int32 hRef, mscorlib::System::Runtime::InteropServices::UCOMITypeInfo ppTI
				TEST(mscorlib_System_Runtime_InteropServices_UCOMITypeInfo_Fixture,GetRefTypeInfo_Test)
				{

				}

				// Method AddressOfMember
				//		Signature: mscorlib::System::Int32 memid, mscorlib::System::Runtime::InteropServices::INVOKEKIND::__ENUM__ invKind, mscorlib::System::IntPtr ppv
				TEST(mscorlib_System_Runtime_InteropServices_UCOMITypeInfo_Fixture,AddressOfMember_Test)
				{

				}

				// Method CreateInstance
				//		Signature: mscorlib::System::Object pUnkOuter, mscorlib::System::Guid riid, mscorlib::System::Object ppvObj
				TEST(mscorlib_System_Runtime_InteropServices_UCOMITypeInfo_Fixture,CreateInstance_Test)
				{

				}

				// Method GetMops
				//		Signature: mscorlib::System::Int32 memid, mscorlib::System::String pBstrMops
				TEST(mscorlib_System_Runtime_InteropServices_UCOMITypeInfo_Fixture,GetMops_Test)
				{

				}

				// Method GetContainingTypeLib
				//		Signature: mscorlib::System::Runtime::InteropServices::UCOMITypeLib ppTLB, mscorlib::System::Int32 pIndex
				TEST(mscorlib_System_Runtime_InteropServices_UCOMITypeInfo_Fixture,GetContainingTypeLib_Test)
				{

				}

				// Method ReleaseTypeAttr
				//		Signature: mscorlib::System::IntPtr pTypeAttr
				TEST(mscorlib_System_Runtime_InteropServices_UCOMITypeInfo_Fixture,ReleaseTypeAttr_Test)
				{

				}

				// Method ReleaseFuncDesc
				//		Signature: mscorlib::System::IntPtr pFuncDesc
				TEST(mscorlib_System_Runtime_InteropServices_UCOMITypeInfo_Fixture,ReleaseFuncDesc_Test)
				{

				}

				// Method ReleaseVarDesc
				//		Signature: mscorlib::System::IntPtr pVarDesc
				TEST(mscorlib_System_Runtime_InteropServices_UCOMITypeInfo_Fixture,ReleaseVarDesc_Test)
				{

				}

			}
		}
	}
}


text:
Meteor.startup(function () {

  Meteor.Mandrill.config({
    username: Meteor.settings['notifications']['mandrill'].username,
    key: Meteor.settings['notifications']['mandrill'].key
  });

  updateRunners();
  updateScripts();
  ensureTests();
});

function ensureTests () {

  var tests = Tests.find({ nextRunAt: { $lt: new Date }});
  tests.forEach(function (test) {
    runTest(test._id);
  });

  Meteor.setTimeout(ensureTests, 10000);
}

function updateRunners () {

  var runners = [
    { title: "CasperJS", slug: "casperjs", command: "casperjs --ssl-protocol=any test" },
    { title: "Mocha", slug: "mocha", command: "mocha" }
  ];

  runners.forEach(function (runner) {
    Runners.upsert({ slug: runner.slug }, { $set: runner });
  });

  // TODO Sync back and remove runners from DB that are not in array
  var runnerCount = Runners.find().count();
  console.log("%s Runners updated", runnerCount);
}

function updateScripts () {

  var hashFiles = Meteor.npmRequire('hash-files');
  var readdir = Meteor.npmRequire('recursive-readdir');
  var runners = Runners.find();

  runners.forEach(function (runner) {

    try {
      var dir = './assets/app/tests/' + runner.slug;

      var files = Async.runSync(function (done) {
        readdir(dir, done);
      });

      if (files.error) {
        console.log(files.error);
      }
      else if (files.result && files.result.length) {
        files.result.forEach(function (file) {

          //noinspection Eslint
          var hash = hashFiles.sync({ files: [file] });

          Scripts.upsert({ path: file }, {
            $set: {
              runnerId: runner._id,
              file: file,
              path: file,
              hash: hash
            }
          });
        });
      }
    }
    catch (err) {
      console.log(err);
      console.log("Cannot update %s tests", runner.title);
    }
  });

  // TODO Sync back and remove runners from DB that are not in array
  var scriptCount = Scripts.find().count();
  console.log("%s Scripts updated", scriptCount);
}