text:
File.open('/path/to/file', 'wb') do |file|
  s3.get_object(bucket: 'bucket-name', key: 'object-key') do |chunk, headers|
    # headers['content-length']
    file.write(chunk)
  end
end


text:
package elasta.orm.entity.impl;

import elasta.commons.Utils;
import elasta.orm.entity.DependencyInfo;
import elasta.orm.entity.DependencyTpl;
import elasta.orm.entity.core.*;
import elasta.orm.entity.core.columnmapping.IndirectRelationMapping;
import elasta.orm.entity.ex.EntityValidationException;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;

/**
 * Created by sohan on 4/14/2017.
 */
final class IndirectColumnMappingValidator {
    private final InternalEntityValidator internalEntityValidator;
    private final Map<String, TableDependency> tableToTableDependencyMap;
    private final Map<String, Entity> entityNameToEntityMap;
    final Entity entity;
    final Field field;
    final IndirectRelationMapping mapping;

    public IndirectColumnMappingValidator(InternalEntityValidator internalEntityValidator, Map<String, TableDependency> tableToTableDependencyMap, Map<String, Entity> entityNameToEntityMap, Entity entity, Field field, IndirectRelationMapping mapping) {
        Objects.requireNonNull(internalEntityValidator);
        Objects.requireNonNull(tableToTableDependencyMap);
        Objects.requireNonNull(entityNameToEntityMap);
        Objects.requireNonNull(entity);
        Objects.requireNonNull(field);
        Objects.requireNonNull(mapping);
        this.tableToTableDependencyMap = tableToTableDependencyMap;
        this.entityNameToEntityMap = entityNameToEntityMap;
        this.entity = entity;
        this.field = field;
        this.mapping = mapping;
        this.internalEntityValidator = internalEntityValidator;
    }

    public void validate() {

        checkFieldType();

        Relationship relationship = field.getRelationship().orElseThrow(() -> new EntityValidationException("No relationship present for mapping '" + mapping + "' in table '" + entity.getDbMapping().getTable() + "'"));

        internalEntityValidator.checkFieldTypeAndName(relationship, field);

        if (Utils.not(tableToTableDependencyMap.containsKey(entity.getDbMapping().getTable()))) {

            final Entity referencingEntity = entityNameToEntityMap.get(mapping.getReferencingEntity());

            checkRelationshipToReferencingEntity(referencingEntity);

            checkAllSrcColumnsExistsInCombinedColumns(entity.getName(), mapping.getSrcForeignColumnMappingList());
            checkAllSrcColumnsExistsInCombinedColumns(referencingEntity.getName(), mapping.getDstForeignColumnMappingList());

            return;
        }

        Optional<DependencyTpl> dependencyTplOptional = internalEntityValidator.checkRelationalValidity(mapping);

        Optional<DependencyInfo> info = dependencyTplOptional.flatMap(dependencyTpl -> dependencyTpl.getFieldToDependencyInfoMap().values().stream()
            .filter(this::findDependencyInfoInOppositeSide)
            .findAny());

        if (info.isPresent()) {

            DependencyInfo dependencyInfo = info.get();

            checkMappingValidity(
                mapping,
                (IndirectRelationMapping) dependencyInfo.getRelationMapping(),
                dependencyTplOptional.get(),
                dependencyInfo
            );

        } else {
            checkAllSrcColumnsExistsInCombinedColumns(
                entity.getName(), mapping.getSrcForeignColumnMappingList()
            );
            checkAllSrcColumnsExistsInCombinedColumns(
                entityNameToEntityMap.get(mapping.getReferencingEntity()).getName(), mapping.getDstForeignColumnMappingList()
            );
        }

        info.ifPresent(dependencyInfo -> {
            Relationship relationshipOther = dependencyInfo.getField().getRelationship().orElseThrow(() -> new EntityValidationException("No relationship present for mapping '" + mapping + "' in table '" + entity.getDbMapping().getTable() + "'"));

            if (Utils.not(
                (relationship.getType() == Relationship.Type.ONE_TO_ONE
                    && relationshipOther.getType() == Relationship.Type.ONE_TO_ONE)
                    || (relationship.getType() == Relationship.Type.ONE_TO_MANY
                    && relationshipOther.getType() == Relationship.Type.MANY_TO_ONE)
                    || (relationship.getType() == Relationship.Type.MANY_TO_ONE
                    && relationshipOther.getType() == Relationship.Type.ONE_TO_MANY)
                    || (relationship.getType() == Relationship.Type.MANY_TO_MANY
                    && relationshipOther.getType() == Relationship.Type.MANY_TO_MANY)
            )) {
                throw new EntityValidationException(
                    "Relationship type '" + relationship.getType() + "' is invalid for mapping type '" + mapping.getColumnType() + "'"
                );
            }
        });

    }

    private boolean findDependencyInfoInOppositeSide(DependencyInfo dependencyInfo) {
        if (dependencyInfo.getRelationMapping().getColumnType() == RelationType.INDIRECT) {

            IndirectRelationMapping depMapping = (IndirectRelationMapping) dependencyInfo.getRelationMapping();

            if (mapping.getRelationTable().equals(depMapping.getRelationTable())) {
                return true;
            }
        }
        return false;
    }

    private void checkRelationshipToReferencingEntity(Entity referencingEntity) {

        if (referencingEntity == null) {
            throw new EntityValidationException(
                "No entity found for referenceEntity '" + mapping.getReferencingEntity() + "' in mapping '" + mapping + "' in relationship '" + entity.getName() + "' <-> '" + mapping.getReferencingEntity() + "'"
            );
        }
        if (Utils.not(
            mapping.getReferencingEntity().equals(
                referencingEntity.getName()
            ) && mapping.getReferencingTable().equals(
                referencingEntity.getDbMapping().getTable()
            )
        )) {
            throw new EntityValidationException("Referencing Entity '" + mapping.getReferencingEntity() + "' or Table '" + mapping.getReferencingTable() + "' does not match with actual Referencing Entity '" + referencingEntity.getName() + "' or Table '" + referencingEntity.getDbMapping().getTable() + "'");
        }
    }

    private void checkFieldType() {

        boolean isFieldTypeOk = field.getJavaType() == JavaType.OBJECT || field.getJavaType() == JavaType.ARRAY;
        if (Utils.not(isFieldTypeOk)) {
            throw new EntityValidationException("Field '" + field.getName() + "' has an invalid type '" + field.getJavaType() + "' for dbColumnMappingType '"
                + mapping.getColumnType() + "'");
        }
    }

    private void checkMappingValidity(IndirectRelationMapping mapping, IndirectRelationMapping depMapping, DependencyTpl dependencyTpl, DependencyInfo dependencyInfo) {
        List<ForeignColumnMapping> srcForeignColumnMappingList = mapping.getSrcForeignColumnMappingList();
        List<ForeignColumnMapping> dstForeignColumnMappingList = mapping.getDstForeignColumnMappingList();
        List<ForeignColumnMapping> srcForeignColumnMappingList1 = depMapping.getSrcForeignColumnMappingList();
        List<ForeignColumnMapping> dstForeignColumnMappingList1 = depMapping.getDstForeignColumnMappingList();

        if (srcForeignColumnMappingList.size() > 0
            && dstForeignColumnMappingList1.size() > 0
            && Utils.not(
            internalEntityValidator.isEqualBothSide(srcForeignColumnMappingList, dstForeignColumnMappingList1)
        )) {
            throw new EntityValidationException("mapping.srcForeignColumnMappingList '" +
                srcForeignColumnMappingList
                + "' and depMapping.dstForeignColumnMappingList '" +
                dstForeignColumnMappingList1
                + "' does not match in relationship '" + entity.getName() + "." + field.getName() + "' <-> '" + dependencyTpl.getEntity().getName() + "." + dependencyInfo.getField().getName() + "'");
        }

        if (srcForeignColumnMappingList1.size() > 0
            && dstForeignColumnMappingList.size() > 0
            && Utils.not(
            internalEntityValidator.isEqualBothSide(srcForeignColumnMappingList1, dstForeignColumnMappingList)
        )) {
            throw new EntityValidationException("mapping.srcForeignColumnMappingList '" +
                srcForeignColumnMappingList
                + "' and depMapping.dstForeignColumnMappingList '" +
                dstForeignColumnMappingList1
                + "' does not match in relationship '" + entity.getName() + "." + field.getName() + "' <-> '" + dependencyTpl.getEntity().getName() + "." + dependencyInfo.getField().getName() + "'");
        }

        if (srcForeignColumnMappingList.isEmpty() && dstForeignColumnMappingList1.isEmpty()) {
            throw new EntityValidationException(
                "Both srcForeignColumnMappingList and dstForeignColumnMappingList is empty in relationship '" + entity.getName() + "." + field.getName() + "' <-> '" + dependencyTpl.getEntity().getName() + "." + dependencyInfo.getField().getName() + "'"
            );
        }

        if (dstForeignColumnMappingList.isEmpty() && srcForeignColumnMappingList1.isEmpty()) {
            throw new EntityValidationException(
                "Both srcForeignColumnMappingList and dstForeignColumnMappingList is empty in relationship '" + entity.getName() + "." + field.getName() + "' <-> '" + dependencyTpl.getEntity().getName() + "." + dependencyInfo.getField().getName() + "'"
            );
        }

        checkAllSrcColumnsExistsInCombinedColumns(
            entity.getName(),
            srcForeignColumnMappingList.size() > 0 ? srcForeignColumnMappingList : dstForeignColumnMappingList1
        );

        checkAllSrcColumnsExistsInCombinedColumns(
            dependencyTpl.getEntity().getName(),
            dstForeignColumnMappingList.size() > 0 ? dstForeignColumnMappingList : srcForeignColumnMappingList1
        );
    }

    private void checkAllSrcColumnsExistsInCombinedColumns(String entity, List<ForeignColumnMapping> foreignColumnMappings) {

        foreignColumnMappings.forEach(foreignColumnMapping -> {

            boolean existsInCombinedColumns = internalEntityValidator.columnExistsInCombinedColumns(entity, foreignColumnMapping.getSrcColumn());

            if (Utils.not(existsInCombinedColumns)) {
                throw new EntityValidationException(
                    "Mapping column '" + foreignColumnMapping.getSrcColumn() + "' does not exists in table column list in table '" + entityNameToEntityMap.get(entity).getDbMapping().getTable() + "'"
                );
            }
        });
    }
}

redpajama_set_name: RedPajamaGithub


text:
package com.tolgaduran.moviedb.data;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import com.tolgaduran.moviedb.data.MovieContract.Cast;
import com.tolgaduran.moviedb.data.MovieContract.Crew;
import com.tolgaduran.moviedb.data.MovieContract.FavouritesMovies;
import com.tolgaduran.moviedb.data.MovieContract.FavouritesTVs;
import com.tolgaduran.moviedb.data.MovieContract.Genres;
import com.tolgaduran.moviedb.data.MovieContract.MovieDetails;
import com.tolgaduran.moviedb.data.MovieContract.Movies;
import com.tolgaduran.moviedb.data.MovieContract.People;
import com.tolgaduran.moviedb.data.MovieContract.Reviews;
import com.tolgaduran.moviedb.data.MovieContract.SimilarMovies;
import com.tolgaduran.moviedb.data.MovieContract.TV;
import com.tolgaduran.moviedb.data.MovieContract.TVCast;
import com.tolgaduran.moviedb.data.MovieContract.TVCreator;
import com.tolgaduran.moviedb.data.MovieContract.TVDetails;
import com.tolgaduran.moviedb.data.MovieContract.TVEpisode;
import com.tolgaduran.moviedb.data.MovieContract.TVEpisodeCrew;
import com.tolgaduran.moviedb.data.MovieContract.TVEpisodeGuestStar;
import com.tolgaduran.moviedb.data.MovieContract.TVEpisodeRuntime;
import com.tolgaduran.moviedb.data.MovieContract.TVGenres;
import com.tolgaduran.moviedb.data.MovieContract.TVNetworks;
import com.tolgaduran.moviedb.data.MovieContract.TVSeasonDetails;
import com.tolgaduran.moviedb.data.MovieContract.TVSeasons;
import com.tolgaduran.moviedb.data.MovieContract.TVSimilar;
import com.tolgaduran.moviedb.data.MovieContract.TVVideos;
import com.tolgaduran.moviedb.data.MovieContract.Videos;

class MovieDBHelper extends SQLiteOpenHelper {

    private static final String DATABASE_NAME = "movie.db";
    private static final int DATABASE_VERSION = 2;

    public MovieDBHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {
        final String SQL_CREATE__TABLE = "CREATE TABLE " + Movies.TABLE_NAME + " (" +
                Movies._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
                Movies.PAGE + "  TEXT," +
                Movies.POSTER_PATH + "  TEXT," +
                Movies.ADULT + "  TEXT," +
                Movies.OVERVIEW + "  TEXT," +
                Movies.RELEASE_DATE + "  TEXT," +
                Movies.MOVIE_ID + "  TEXT," +
                Movies.ORIGINAL_TITLE + "  TEXT," +
                Movies.ORIGINAL_LANGUAGE + "  TEXT," +
                Movies.TITLE + "  TEXT," +
                Movies.BACKDROP_PATH + "  TEXT," +
                Movies.POPULARITY + "  TEXT," +
                Movies.VOTE_COUNT + "  TEXT," +
                Movies.VOTE_AVERAGE + "  TEXT," +
                Movies.FAVOURED + " INTEGER NOT NULL DEFAULT 0," +
                Movies.SHOWED + " INTEGER NOT NULL DEFAULT 0," +
                Movies.DOWNLOADED + " INTEGER NOT NULL DEFAULT 0," +
                Movies.MODE + " TEXT," +
                Movies.PREF_LANGUAGE + " TEXT," +
                Movies.PREF_ADULT + " TEXT," +
                Movies.PREF_REGION + " TEXT,"
                + "UNIQUE (" + Movies.MOVIE_ID + ") ON CONFLICT REPLACE)";

        final String SQL_CREATE__TABLE_SIMILAR_MOVIES = "CREATE TABLE " + SimilarMovies.TABLE_NAME + " (" +
                SimilarMovies._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
                SimilarMovies.MOVIE_ID_OLD + "  TEXT," +
                SimilarMovies.PAGE + "  TEXT," +
                SimilarMovies.POSTER_PATH + "  TEXT," +
                SimilarMovies.ADULT + "  TEXT," +
                SimilarMovies.OVERVIEW + "  TEXT," +
                SimilarMovies.RELEASE_DATE + "  TEXT," +
                SimilarMovies.MOVIE_ID + "  TEXT," +
                SimilarMovies.ORIGINAL_TITLE + "  TEXT," +
                SimilarMovies.ORIGINAL_LANGUAGE + "  TEXT," +
                SimilarMovies.TITLE + "  TEXT," +
                SimilarMovies.BACKDROP_PATH + "  TEXT," +
                SimilarMovies.POPULARITY + "  TEXT," +
                SimilarMovies.VOTE_COUNT + "  TEXT," +
                SimilarMovies.VOTE_AVERAGE + "  TEXT," +
                SimilarMovies.FAVOURED + " INTEGER NOT NULL DEFAULT 0," +
                SimilarMovies.SHOWED + " INTEGER NOT NULL DEFAULT 0," +
                SimilarMovies.DOWNLOADED + " INTEGER NOT NULL DEFAULT 0,"
                + "UNIQUE (" + SimilarMovies.MOVIE_ID_OLD + ") ON CONFLICT REPLACE)";

        final String SQL_CREATE__TABLE_TV_SIMILAR = "CREATE TABLE " + TVSimilar.TABLE_NAME + " (" +
                TVSimilar._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
                TVSimilar.TV_ID_OLD + "  TEXT," +
                TVSimilar.PAGE + "  TEXT," +
                TVSimilar.POSTER_PATH + "  TEXT," +
                TVSimilar.OVERVIEW + "  TEXT," +
                TVSimilar.FIRST_AIR_DATE + "  TEXT," +
                TVSimilar.TV_ID + "  TEXT," +
                TVSimilar.ORIGINAL_NAME + "  TEXT," +
                TVSimilar.ORIGINAL_LANGUAGE + "  TEXT," +
                TVSimilar.NAME + "  TEXT," +
                TVSimilar.BACKDROP_PATH + "  TEXT," +
                TVSimilar.POPULARITY + "  TEXT," +
                TVSimilar.VOTE_COUNT + "  TEXT," +
                TVSimilar.VOTE_AVERAGE + "  TEXT," +
                TVSimilar.FAVOURED + " INTEGER NOT NULL DEFAULT 0,"
                + "UNIQUE (" + TVSimilar.TV_ID_OLD + ") ON CONFLICT REPLACE)";

        final String SQL_CREATE__TABLE_MOVIE_DETAILS = "CREATE TABLE " + MovieDetails.TABLE_NAME + " (" +
                MovieDetails._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
                MovieDetails.MOVIE_ID + "  TEXT," +
                MovieDetails.ADULT + "  TEXT," +
                MovieDetails.BACKDROP_PATH + "  TEXT," +
                MovieDetails.BUDGET + "  TEXT," +
                MovieDetails.HOMEPAGE + "  TEXT," +
                MovieDetails.ORIGINAL_LANGUAGE + "  TEXT," +
                MovieDetails.ORIGINAL_TITLE + "  TEXT," +
                MovieDetails.OVERVIEW + "  TEXT," +
                MovieDetails.POPULARITY + "  TEXT," +
                MovieDetails.POSTER_PATH + "  TEXT," +
                MovieDetails.RELEASE_DATE + "  TEXT," +
                MovieDetails.REVENUE + "  TEXT," +
                MovieDetails.RUNTIME + "  TEXT," +
                MovieDetails.STATUS + "  TEXT," +
                MovieDetails.TAGLINE + "  TEXT," +
                MovieDetails.TITLE + "  TEXT," +
                MovieDetails.VOTE_AVERAGE + "  TEXT," +
                MovieDetails.VOTE_COUNT + "  TEXT," +
                MovieDetails.FAVOURED + " INTEGER NOT NULL DEFAULT 0," +
                MovieDetails.SHOWED + " INTEGER NOT NULL DEFAULT 0," +
                MovieDetails.DOWNLOADED + " INTEGER NOT NULL DEFAULT 0,"
                + "UNIQUE (" + MovieDetails.MOVIE_ID + ") ON CONFLICT REPLACE)";

        final String SQL_CREATE__TABLE_TV_DETAILS = "CREATE TABLE " + TVDetails.TABLE_NAME + " (" +
                TVDetails._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
                TVDetails.TV_ID + "  TEXT," +
                TVDetails.BACKDROP_PATH + "  TEXT," +
                TVDetails.FIRST_AIR_DATE + "  TEXT," +
                TVDetails.HOMEPAGE + "  TEXT," +
                TVDetails.IN_PRODUCTION + "  TEXT," +
                TVDetails.LAST_AIR_DATE + "  TEXT," +
                TVDetails.NAME + "  TEXT," +
                TVDetails.NUMBER_OF_EPISODES + "  TEXT," +
                TVDetails.NUMBER_OF_SEASONS + "  TEXT," +
                TVDetails.ORIGINAL_LANG + "  TEXT," +
                TVDetails.ORIGINAL_NAME + "  TEXT," +
                TVDetails.OVERVIEW + "  TEXT," +
                TVDetails.POPULARITY + "  TEXT," +
                TVDetails.POSTER_PATH + "  TEXT," +
                TVDetails.STATUS + "  TEXT," +
                TVDetails.TYPE + "  TEXT," +
                TVDetails.VOTE_AVERAGE + "  TEXT," +
                TVDetails.VOTE_COUNT + "  TEXT," +
                TVDetails.FAVOURED + " INTEGER NOT NULL DEFAULT 0,"
                + "UNIQUE (" + TVDetails.TV_ID + ") ON CONFLICT REPLACE)";

        final String SQL_CREATE__TABLE_CAST = "CREATE TABLE " + Cast.TABLE_NAME + " (" +
                Cast._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
                Cast.CAST_ID + "  TEXT," +
                Cast.CHARACTER + "  TEXT," +
                Cast.CREDIT_ID + "  TEXT," +
                Cast.ID + "  TEXT," +
                Cast.NAME + "  TEXT," +
                Cast.ORDER + "  TEXT," +
                Cast.PROFILE_PATH + "  TEXT," +
                Cast.MOVIE_ID + "  TEXT,"
                + "UNIQUE (" + Cast.MOVIE_ID + " , " + Cast.CAST_ID + ") ON CONFLICT REPLACE)";

        final String SQL_CREATE__TABLE_TVCAST = "CREATE TABLE " + TVCast.TABLE_NAME + " (" +
                TVCast._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
                TVCast.CHARACTER + "  TEXT," +
                TVCast.CREDIT_ID + "  TEXT," +
                TVCast.ID + "  TEXT," +
                TVCast.NAME + "  TEXT," +
                TVCast.ORDER + "  TEXT," +
                TVCast.PROFILE_PATH + "  TEXT," +
                TVCast.TV_ID + "  TEXT,"
                + "UNIQUE (" + TVCast.TV_ID + " , " + TVCast.ID + ") ON CONFLICT REPLACE)";

        final String SQL_CREATE__TABLE_TV_CREATOR = "CREATE TABLE " + TVCreator.TABLE_NAME + " (" +
                TVCreator._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
                TVCreator.TV_ID + "  TEXT," +
                TVCreator.ID + "  TEXT," +
                TVCreator.NAME + "  TEXT," +
                TVCreator.PROFILE_PATH + "  TEXT,"
                + "UNIQUE (" + TVCreator.TV_ID + " , " + TVCreator.ID + ") ON CONFLICT REPLACE)";

        final String SQL_CREATE__TABLE_TV_EPISODE_RUNTIME = "CREATE TABLE " + TVEpisodeRuntime.TABLE_NAME + " (" +
                TVEpisodeRuntime._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
                TVEpisodeRuntime.TV_ID + "  TEXT," +
                TVEpisodeRuntime.TIME + "  TEXT,"
                + "UNIQUE (" + TVEpisodeRuntime.TV_ID + " , " + TVEpisodeRuntime.TIME + ") ON CONFLICT REPLACE)";

        final String SQL_CREATE__TABLE_PEOPLE = "CREATE TABLE " + People.TABLE_NAME + " (" +
                People._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
                People.ADULT + "  TEXT," +
                People.BIOGRAPHY + "  TEXT," +
                People.BIRTHDAY + "  TEXT," +
                People.DEATHDAY + "  TEXT," +
                People.GENDER + "  TEXT," +
                People.HOMEPAGE + "  TEXT," +
                People.ID + "  TEXT," +
                People.NAME + "  TEXT," +
                People.PLACE_OF_BIRTH + "  TEXT," +
                People.POPULARITY + "  TEXT," +
                People.PROFILE_PATH + "  TEXT,"
                + "UNIQUE (" + People.ID + ") ON CONFLICT REPLACE)";

        final String SQL_CREATE__TABLE_CREW = "CREATE TABLE " + Crew.TABLE_NAME + " (" +
                Crew._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
                Crew.CREDIT_ID + "  TEXT," +
                Crew.DEPARTMENT + "  TEXT," +
                Crew.ID + "  TEXT," +
                Crew.JOB + "  TEXT," +
                Crew.NAME + "  TEXT," +
                Crew.PROFILE_PATH + "  TEXT," +
                Crew.MOVIE_ID + "  TEXT,"
                + "UNIQUE (" + Crew.CREDIT_ID + " , " + Crew.MOVIE_ID + ") ON CONFLICT REPLACE)";

        final String SQL_CREATE__TABLE_TV = "CREATE TABLE " + TV.TABLE_NAME + " (" +
                TV._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
                TV.PAGE + "  TEXT," +
                TV.POSTER_PATH + "  TEXT," +
                TV.OVERVIEW + "  TEXT," +
                TV.FIRST_AIR_DATE + "  TEXT," +
                TV.TV_ID + "  TEXT," +
                TV.ORIGINAL_NAME + "  TEXT," +
                TV.ORIGINAL_LANGUAGE + "  TEXT," +
                TV.NAME + "  TEXT," +
                TV.BACKDROP_PATH + "  TEXT," +
                TV.POPULARITY + "  TEXT," +
                TV.VOTE_COUNT + "  TEXT," +
                TV.VOTE_AVERAGE + "  TEXT," +
                TV.FAVOURED + " INTEGER NOT NULL DEFAULT 0," +
                TV.SHOWED + " INTEGER NOT NULL DEFAULT 0," +
                TV.DOWNLOADED + " INTEGER NOT NULL DEFAULT 0," +
                TV.MODE + " TEXT," +
                TV.PREF_LANGUAGE + " TEXT," +
                TV.PREF_ADULT + " TEXT," +
                TV.PREF_REGION + " TEXT,"
                + "UNIQUE (" + TV.TV_ID + ") ON CONFLICT REPLACE)";

        final String SQL_CREATE__TABLE_FAVOURITES_MOVIES = "CREATE TABLE " + FavouritesMovies.TABLE_NAME + " (" +
                FavouritesMovies._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
                FavouritesMovies.MOVIE_ID + "  TEXT,"
                + "UNIQUE (" + FavouritesMovies.MOVIE_ID + ") ON CONFLICT REPLACE)";

        final String SQL_CREATE__TABLE_FAVOURITES_TV = "CREATE TABLE " + FavouritesTVs.TABLE_NAME + " (" +
                FavouritesTVs._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
                FavouritesTVs.TV_ID + "  TEXT,"
                + "UNIQUE (" + FavouritesTVs.TV_ID + ") ON CONFLICT REPLACE)";

        final String SQL_CREATE__TABLE_VIDEOS = "CREATE TABLE " + Videos.TABLE_NAME + " (" +
                Videos._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
                Videos.VIDEO_ID + "  TEXT," +
                Videos.KEY + "  TEXT," +
                Videos.NAME + "  TEXT," +
                Videos.SITE + "  TEXT," +
                Videos.SIZE + "  TEXT," +
                Videos.TYPE + "  TEXT," +
                Videos.MOVIE_ID + "  TEXT ," +
                "UNIQUE (" + Videos.MOVIE_ID + " , " + Videos.VIDEO_ID + ") ON CONFLICT REPLACE)";

        final String SQL_CREATE__TABLE_REVIEWS = "CREATE TABLE " + Reviews.TABLE_NAME + " (" +
                Reviews._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
                Reviews.PAGE + "  TEXT," +
                Reviews.TOTAL_PAGE + "  TEXT," +
                Reviews.TOTAL_RESULTS + "  TEXT," +
                Reviews.ID_REVIEWS + "  TEXT," +
                Reviews.AUTHOR + "  TEXT ," +
                Reviews.CONTENT + "  TEXT," +
                Reviews.URL + "  TEXT," +
                Reviews.MOVIE_ID + "  TEXT )";

        final String SQL_CREATE__TABLE_GENRES = "CREATE TABLE " + Genres.TABLE_NAME + " (" +
                Genres._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
                Genres.NAME + "  TEXT," +
                Genres.ID_GENRES + "  TEXT," +
                Genres.MOVIE_ID + "  TEXT ," +
                "UNIQUE (" + Genres.MOVIE_ID + " , " + Genres.ID_GENRES + ") ON CONFLICT REPLACE)";

        final String SQL_CREATE__TABLE_TV_GENRES = "CREATE TABLE " + TVGenres.TABLE_NAME + " (" +
                TVGenres._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
                TVGenres.NAME + "  TEXT," +
                TVGenres.ID_GENRES + "  TEXT," +
                TVGenres.TV_ID + "  TEXT ," +
                "UNIQUE (" + TVGenres.TV_ID + " , " + TVGenres.ID_GENRES + ") ON CONFLICT REPLACE)";

        final String SQL_CREATE__TABLE_TV_NETWORKS = "CREATE TABLE " + TVNetworks.TABLE_NAME + " (" +
                TVNetworks._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
                TVNetworks.ID + "  TEXT," +
                TVNetworks.NAME + "  TEXT," +
                TVNetworks.TV_ID + "  TEXT ," +
                "UNIQUE (" + TVNetworks.TV_ID + " , " + TVNetworks.NAME + ") ON CONFLICT REPLACE)";

        final String SQL_CREATE__TABLE_TV_SEASONS = "CREATE TABLE " + TVSeasons.TABLE_NAME + " (" +
                TVSeasons._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
                TVSeasons.EPISODE_COUNT + "  TEXT," +
                TVSeasons.ID + "  TEXT," +
                TVSeasons.SEASON_NUMBER + "  TEXT," +
                TVSeasons.POSTER_PATH + "  TEXT," +
                TVSeasons.TV_ID + "  TEXT ," +
                "UNIQUE (" + TVSeasons.TV_ID + " , " + TVSeasons.SEASON_NUMBER + ") ON CONFLICT REPLACE)";

        final String SQL_CREATE__TABLE_TV_VIDEOS = "CREATE TABLE " + TVVideos.TABLE_NAME + " (" +
                TVVideos._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
                TVVideos.VIDEO_ID + "  TEXT," +
                TVVideos.KEY + "  TEXT," +
                TVVideos.NAME + "  TEXT," +
                TVVideos.SITE + "  TEXT," +
                TVVideos.SIZE + "  TEXT," +
                TVVideos.TYPE + "  TEXT," +
                TVVideos.TV_ID + "  TEXT ," +
                "UNIQUE (" + TVVideos.TV_ID + " , " + TVVideos.VIDEO_ID + ") ON CONFLICT REPLACE)";

        final String SQL_CREATE__TABLE_TV_SEASON_DETAILS = "CREATE TABLE " + TVSeasonDetails.TABLE_NAME + " (" +
                TVSeasonDetails._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
                TVSeasonDetails.SEASON_ID + "  TEXT," +
                TVSeasonDetails.AIR_DATE + "  TEXT," +
                TVSeasonDetails.NAME + "  TEXT," +
                TVSeasonDetails.OVERVIEW + "  TEXT," +
                TVSeasonDetails.SEASON__ID + "  TEXT," +
                TVSeasonDetails.POSTER_PATH + "  TEXT," +
                TVSeasonDetails.SEASON_NUMBER + "  TEXT ," +
                "UNIQUE (" + TVSeasonDetails.SEASON_ID + " , " + TVSeasonDetails.SEASON__ID + ") ON CONFLICT REPLACE)";

        final String SQL_CREATE__TABLE_TV_EPISODE = "CREATE TABLE " + TVEpisode.TABLE_NAME + " (" +
                TVEpisode._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
                TVEpisode.SEASON_ID + "  TEXT," +
                TVEpisode.AIR_DATE + "  TEXT," +
                TVEpisode.EPISODE_NUMBER + "  TEXT," +
                TVEpisode.NAME + "  TEXT," +
                TVEpisode.OVERVIEW + "  TEXT," +
                TVEpisode.ID + "  TEXT," +
                TVEpisode.PRODUCTION_CODE + "  TEXT," +
                TVEpisode.SEASON_NUMBER + "  TEXT," +
                TVEpisode.STILL_PATH + "  TEXT," +
                TVEpisode.VOTE_AVERAGE + "  TEXT ," +
                TVEpisode.VOTE_COUNT + "  TEXT ," +
                "UNIQUE (" + TVEpisode.SEASON_ID + " , " + TVEpisode.ID + ") ON CONFLICT REPLACE)";

        final String SQL_CREATE__TABLE_TV_EPISODE_CREW = "CREATE TABLE " + TVEpisodeCrew.TABLE_NAME + " (" +
                TVEpisodeCrew._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
                TVEpisodeCrew.EPISODE_ID + "  TEXT," +
                TVEpisodeCrew.ID + "  TEXT," +
                TVEpisodeCrew.CREDIT_ID + "  TEXT," +
                TVEpisodeCrew.NAME + "  TEXT," +
                TVEpisodeCrew.DEPARTMENT + "  TEXT," +
                TVEpisodeCrew.JOB + "  TEXT," +
                TVEpisodeCrew.PROFILE_PATH + "  TEXT," +
                "UNIQUE (" + TVEpisodeCrew.EPISODE_ID + " , " + TVEpisodeCrew.ID + ") ON CONFLICT REPLACE)";

        final String SQL_CREATE__TABLE_TV_EPISODE_GUEST_STAR = "CREATE TABLE " + TVEpisodeGuestStar.TABLE_NAME + " (" +
                TVEpisodeGuestStar._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
                TVEpisodeGuestStar.EPISODE_ID + "  TEXT," +
                TVEpisodeGuestStar.ID + "  TEXT," +
                TVEpisodeGuestStar.CREDIT_ID + "  TEXT," +
                TVEpisodeGuestStar.NAME + "  TEXT," +
                TVEpisodeGuestStar.CHARACTER + "  TEXT," +
                TVEpisodeGuestStar.ORDER + "  TEXT," +
                TVEpisodeGuestStar.PROFILE_PATH + "  TEXT," +
                "UNIQUE (" + TVEpisodeGuestStar.EPISODE_ID + " , " + TVEpisodeGuestStar.ID + ") ON CONFLICT REPLACE)";

        sqLiteDatabase.execSQL(SQL_CREATE__TABLE);
        sqLiteDatabase.execSQL(SQL_CREATE__TABLE_FAVOURITES_MOVIES);
        sqLiteDatabase.execSQL(SQL_CREATE__TABLE_VIDEOS);
        sqLiteDatabase.execSQL(SQL_CREATE__TABLE_REVIEWS);
        sqLiteDatabase.execSQL(SQL_CREATE__TABLE_GENRES);
        sqLiteDatabase.execSQL(SQL_CREATE__TABLE_MOVIE_DETAILS);
        sqLiteDatabase.execSQL(SQL_CREATE__TABLE_CAST);
        sqLiteDatabase.execSQL(SQL_CREATE__TABLE_CREW);
        sqLiteDatabase.execSQL(SQL_CREATE__TABLE_SIMILAR_MOVIES);

        sqLiteDatabase.execSQL(SQL_CREATE__TABLE_PEOPLE);

        sqLiteDatabase.execSQL(SQL_CREATE__TABLE_TV);
        sqLiteDatabase.execSQL(SQL_CREATE__TABLE_FAVOURITES_TV);
        sqLiteDatabase.execSQL(SQL_CREATE__TABLE_TV_DETAILS);
        sqLiteDatabase.execSQL(SQL_CREATE__TABLE_TV_CREATOR);
        sqLiteDatabase.execSQL(SQL_CREATE__TABLE_TV_EPISODE_RUNTIME);
        sqLiteDatabase.execSQL(SQL_CREATE__TABLE_TV_GENRES);
        sqLiteDatabase.execSQL(SQL_CREATE__TABLE_TV_NETWORKS);
        sqLiteDatabase.execSQL(SQL_CREATE__TABLE_TV_SEASONS);
        sqLiteDatabase.execSQL(SQL_CREATE__TABLE_TV_VIDEOS);
        sqLiteDatabase.execSQL(SQL_CREATE__TABLE_TVCAST);
        sqLiteDatabase.execSQL(SQL_CREATE__TABLE_TV_SIMILAR);
        sqLiteDatabase.execSQL(SQL_CREATE__TABLE_TV_SEASON_DETAILS);
        sqLiteDatabase.execSQL(SQL_CREATE__TABLE_TV_EPISODE);
        sqLiteDatabase.execSQL(SQL_CREATE__TABLE_TV_EPISODE_CREW);
        sqLiteDatabase.execSQL(SQL_CREATE__TABLE_TV_EPISODE_GUEST_STAR);

    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int newVersion) {
        sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + Movies.TABLE_NAME);
        sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + FavouritesMovies.TABLE_NAME);
        sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + Videos.TABLE_NAME);
        sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + Reviews.TABLE_NAME);
        sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + Genres.TABLE_NAME);
        sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + MovieDetails.TABLE_NAME);
        sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + Cast.TABLE_NAME);
        sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + Crew.TABLE_NAME);
        sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + SimilarMovies.TABLE_NAME);

        sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + People.TABLE_NAME);

        sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + TV.TABLE_NAME);
        sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + FavouritesTVs.TABLE_NAME);
        sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + TVDetails.TABLE_NAME);
        sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + TVCreator.TABLE_NAME);
        sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + TVEpisodeRuntime.TABLE_NAME);
        sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + TVGenres.TABLE_NAME);
        sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + TVNetworks.TABLE_NAME);
        sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + TVSeasons.TABLE_NAME);
        sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + TVVideos.TABLE_NAME);
        sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + TVCast.TABLE_NAME);
        sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + TVSimilar.TABLE_NAME);
        sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + TVEpisodeGuestStar.TABLE_NAME);
        sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + TVEpisode.TABLE_NAME);
        sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + TVSeasonDetails.TABLE_NAME);
        sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + TVEpisodeCrew.TABLE_NAME);

        onCreate(sqLiteDatabase);
    }
}


text:
package com.example.elephantfly.coolweather;

import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Build;
import android.preference.PreferenceManager;
import android.provider.ContactsContract;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.example.elephantfly.coolweather.gson.Forecast;
import com.example.elephantfly.coolweather.gson.Weather;
import com.example.elephantfly.coolweather.util.HttpUtil;
import com.example.elephantfly.coolweather.util.Utility;

import org.w3c.dom.Text;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class WeatherActivity extends AppCompatActivity {

    public DrawerLayout drawerLayout;

    private Button navButton;

    public SwipeRefreshLayout swipeRefreshLayout;

    private ScrollView weatherLayout;

    private TextView titleCity;

    private TextView titleUpdateTime;

    private TextView degreeText;

    private TextView weatherInfoText;

    private LinearLayout forecastLayout;

    private TextView aqiText;

    private TextView pm25Text;

    private TextView comfortText;

    private TextView carWashText;

    private  TextView sportText;

    private ImageView bingPicImg;

    public String weatherId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_weather);
        //透明状态栏
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        //透明导航栏
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);

        weatherLayout = (ScrollView)findViewById(R.id.weahter_layout);
        titleCity = (TextView)findViewById(R.id.title_city);
        titleUpdateTime = (TextView)findViewById(R.id.title_update_time);
        degreeText = (TextView)findViewById(R.id.degree_text);
        weatherInfoText = (TextView)findViewById(R.id.weather_info_text);
        forecastLayout = (LinearLayout)findViewById(R.id.forecast_layout);
        aqiText = (TextView)findViewById(R.id.aqi_text);
        pm25Text = (TextView)findViewById(R.id.pm25_text);
        comfortText = (TextView)findViewById(R.id.comfort_text);
        carWashText = (TextView)findViewById(R.id.car_wash_text);
        sportText = (TextView)findViewById(R.id.sport_text);
        bingPicImg = (ImageView)findViewById(R.id.bing_pic_img);
        swipeRefreshLayout = (SwipeRefreshLayout)findViewById(R.id.swipe_refresh);
        swipeRefreshLayout.setColorSchemeResources(R.color.colorPrimary);
        drawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout);
        navButton = (Button)findViewById(R.id.nav_button);

        weatherId = getIntent().getStringExtra("weather_id");
        Log.d("debug", "WeatherActivity:weatherId=" + weatherId);
        weatherLayout.setVisibility(View.INVISIBLE);
        requestWeather(weatherId);

        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                Log.d("debug", "WeatherActivity.swipeRefreshLayout.onRefresh:weatherId=" +
                        weatherId);
                requestWeather(weatherId);
            }
        });
        navButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                drawerLayout.openDrawer(GravityCompat.START);
            }
        });

        loadBingPic();
    }

    public void requestWeather(final String weatherId){
        String weatherUrl = "http://guolin.tech/api/weather?cityid=" +
                weatherId + "&key=ff81c44874664a1592eef0c4c0e109d0";
        HttpUtil.sendOkHttpRequest(weatherUrl, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(WeatherActivity.this, "获取天气信息失败",
                                Toast.LENGTH_SHORT).show();
                        swipeRefreshLayout.setRefreshing(false);
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final  String responseText = response.body().string();
                final Weather weather = Utility.handleWeatherResponse(responseText);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (weather != null && "ok".equals(weather.status)){
                            SharedPreferences.Editor editor = PreferenceManager
                                    .getDefaultSharedPreferences(WeatherActivity.this).edit();
                            editor.putString("weather", responseText);
                            editor.apply();
                            showWeatherInfo(weather);
                        }else {
                            Toast.makeText(WeatherActivity.this, "获取天气信息失败",
                                    Toast.LENGTH_SHORT).show();
                        }
                        swipeRefreshLayout.setRefreshing(false);
                    }
                });
            }
        });
        loadBingPic();
    }

    private void showWeatherInfo(Weather weather){
        String cityName = weather.basic.cityName;
        String updateTime = weather.basic.update.updateTime;
        String degree = weather.now.temperature + "℃";
        String weatherInfo = weather.now.more.info;
        titleCity.setText(cityName);
        titleUpdateTime.setText(updateTime);
        degreeText.setText(degree);
        weatherInfoText.setText(weatherInfo);

        forecastLayout.removeAllViews();
        for (Forecast forecast : weather.forecastList){
            View view = LayoutInflater.from(this).inflate(R.layout.forecast_item,
                    forecastLayout, false);
            TextView dateText = (TextView)view.findViewById(R.id.date_text);
            TextView infoText = (TextView)view.findViewById(R.id.info_text);
            TextView maxText = (TextView)view.findViewById(R.id.max_text);
            TextView minText = (TextView)view.findViewById(R.id.min_text);
            dateText.setText(forecast.date);
            infoText.setText(forecast.more.info);
            maxText.setText(forecast.temperature.max);
            minText.setText(forecast.temperature.min);
            forecastLayout.addView(view);
        }
        if (weather.aqi != null){
            aqiText.setText(weather.aqi.city.aqi);
            pm25Text.setText(weather.aqi.city.pm25);
        }
        String comfort = "舒适度:" + weather.suggestion.comfort.info;
        String carWash = "洗车指数:" + weather.suggestion.carWash.info;
        String sport = "运动建议:" + weather.suggestion.sport.info;
        comfortText.setText(comfort);
        carWashText.setText(carWash);
        sportText.setText(sport);
        weatherLayout.setVisibility(View.VISIBLE);

        Intent intent = new Intent(this, AutoUpdateService.class);
        startService(intent);
    }

    private void loadBingPic(){
        String requestBingPic = "http://guolin.tech/api/bing_pic";
        HttpUtil.sendOkHttpRequest(requestBingPic, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String bingPic = response.body().string();
                SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences
                        (WeatherActivity.this).edit();
                editor.putString("bing_pic", bingPic);
                editor.apply();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Glide.with(WeatherActivity.this).load(bingPic).into(bingPicImg);
                    }
                });
            }
        });
    }
}


text:
using namespace Kore;

Program::Program() {
	vertexShader = nullptr;
	fragmentShader = nullptr;
}

void Program::setVertexShader(Shader* shader) {
	vertexShader = shader;
}

void Program::setFragmentShader(Shader* shader) {
	fragmentShader = shader;
}

void Program::setGeometryShader(Shader* shader) {
	log(Error, "Direct3D 9 does not support geometry shaders.");
}

void Program::setTesselationControlShader(Shader* shader) {
	log(Error, "Direct3D 9 does not support tesselation shaders.");
}

void Program::setTesselationEvaluationShader(Shader* shader) {
	log(Error, "Direct3D 9 does not support tesselation shaders.");
}

void Program::link(VertexStructure** structures, int count) {
	if (count > 1) {
		int a = 3;
		++a;
	}
	int all = 0;
	for (int stream = 0; stream < count; ++stream) {
		for (int index = 0; index < structures[stream]->size; ++index) {
			if (structures[stream]->elements[index].data == Float4x4VertexData) {
				all += 4;
			}
			else {
				all += 1;
			}
		}
	}

	D3DVERTEXELEMENT9* elements = (D3DVERTEXELEMENT9*)alloca(sizeof(D3DVERTEXELEMENT9) * (all + 1));
	int i = 0;
	for (int stream = 0; stream < count; ++stream) {
		int stride = 0;
		for (int index = 0; index < structures[stream]->size; ++index) {
			if (structures[stream]->elements[index].data != Float4x4VertexData) {
				elements[i].Stream = stream;
				elements[i].Offset = stride;
			}
			switch (structures[stream]->elements[index].data) {
			case Float1VertexData:
				elements[i].Type = D3DDECLTYPE_FLOAT1;
				stride += 4 * 1;
				break;
			case Float2VertexData:
				elements[i].Type = D3DDECLTYPE_FLOAT2;
				stride += 4 * 2;
				break;
			case Float3VertexData:
				elements[i].Type = D3DDECLTYPE_FLOAT3;
				stride += 4 * 3;
				break;
			case Float4VertexData:
				elements[i].Type = D3DDECLTYPE_FLOAT4;
				stride += 4 * 4;
				break;
			case ColorVertexData:
				elements[i].Type = D3DDECLTYPE_D3DCOLOR;
				stride += 4;
				break;
			case Float4x4VertexData:
				for (int i2 = 0; i2 < 4; ++i2) {
					elements[i].Stream = stream;
					elements[i].Offset = stride;
					elements[i].Type = D3DDECLTYPE_FLOAT4;
					elements[i].Method = D3DDECLMETHOD_DEFAULT;
					elements[i].Usage = D3DDECLUSAGE_TEXCOORD;
					char name[101];
					strcpy(name, structures[stream]->elements[index].name);
					strcat(name, "_");
					size_t length = strlen(name);
					_itoa(i2, &name[length], 10);
					name[length + 1] = 0;
					elements[i].UsageIndex = vertexShader->attributes[name];
					stride += 4 * 4;
					++i;
				}
				break;
			}
			if (structures[stream]->elements[index].data != Float4x4VertexData) {
				elements[i].Method = D3DDECLMETHOD_DEFAULT;
				elements[i].Usage = D3DDECLUSAGE_TEXCOORD;
				elements[i].UsageIndex = vertexShader->attributes[structures[stream]->elements[index].name];
				++i;
			}
		}
	}
	elements[all].Stream = 0xff;
	elements[all].Offset = 0;
	elements[all].Type = D3DDECLTYPE_UNUSED;
	elements[all].Method = 0;
	elements[all].Usage = 0;
	elements[all].UsageIndex = 0;

	vertexDecleration = nullptr;
	affirm(device->CreateVertexDeclaration(elements, &vertexDecleration));

	if (vertexShader->constants.find("dx_ViewAdjust") != vertexShader->constants.end()) halfPixelLocation = vertexShader->constants["dx_ViewAdjust"].regindex;
	else halfPixelLocation = vertexShader->constants["dx_HalfPixelSize"].regindex;
}

void Program::set() {
	affirm(device->SetVertexShader((IDirect3DVertexShader9*)vertexShader->shader));
	affirm(device->SetPixelShader((IDirect3DPixelShader9*)fragmentShader->shader));
	affirm(device->SetVertexDeclaration(vertexDecleration));

	// TODO (DK) System::screenWidth/Height are only main-window dimensions, what about other windows?
	float floats[4];
	floats[0] = 1.0f / System::windowWidth(0);
	floats[1] = 1.0f / System::windowHeight(0);
	floats[2] = floats[0];
	floats[3] = floats[1];
	affirm(device->SetVertexShaderConstantF(halfPixelLocation, floats, 1));
}

ConstantLocation Program::getConstantLocation(const char* name) {
	ConstantLocation location;
	char d3dname[101];
	strcpy(d3dname, "_");
	strcat(d3dname, name);

	if (fragmentShader->constants.find(d3dname) != fragmentShader->constants.end()) {
		location.reg = fragmentShader->constants[d3dname];
		location.shaderType = 1;
	}
	else if (vertexShader->constants.find(d3dname) != vertexShader->constants.end()) {
		location.reg = vertexShader->constants[d3dname];
		location.shaderType = 0;
	}
	else {
		location.shaderType = -1;
		log(Warning, "Could not find uniform %s.", name);
	}
	return location;
}

TextureUnit Program::getTextureUnit(const char* name) {
	TextureUnit unit;
	char d3dname[101];
	strcpy(d3dname, "_");
	strcat(d3dname, name);

	if (fragmentShader->constants.find(d3dname) != fragmentShader->constants.end()) {
		unit.unit = fragmentShader->constants[d3dname].regindex;
	}
	else if (vertexShader->constants.find(d3dname) != vertexShader->constants.end()) {
		unit.unit = vertexShader->constants[d3dname].regindex;
	}
	else {
		unit.unit = -1;
		log(Warning, "Could not find texture %s.", name);
	}
	return unit;
}


text: <namesapi ng-controller="NamesApiCtrl"></namesapi>


text:
package lk.grp.synergy.model;

/**
 * Created by isuru on 1/12/17.
 */
public class Student {
    private int studentId;
    private String passwordHash;
    private String name;
    private String email;
    private int telephone;
    private int notificationFrequency;
    private int notificationChannel;

    public Student(int studentId, String passwordHash, String name, String email, int telephone, int notificationFrequency, int notificationChannel) {
        this.studentId = studentId;
        this.passwordHash = passwordHash;
        this.name = name;
        this.email = email;
        this.telephone = telephone;
        this.notificationFrequency = notificationFrequency;
        this.notificationChannel = notificationChannel;
    }

    public Student() {
    }

    public int getStudentId() {
        return studentId;
    }

    public void setStudentId(int studentId) {
        this.studentId = studentId;
    }

    public String getName() {
        return name;
    }

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

    public String getEmail() {
        return email;
    }

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

    public int getTelephone() {
        return telephone;
    }

    public void setTelephone(int telephone) {
        this.telephone = telephone;
    }

    public int getNotificationFrequency() {
        return notificationFrequency;
    }

    public void setNotificationFrequency(int notificationFrequency) {
        this.notificationFrequency = notificationFrequency;
    }

    public int getNotificationChannel() {
        return notificationChannel;
    }

    public void setNotificationChannel(int notificationChannel) {
        this.notificationChannel = notificationChannel;
    }

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

        Student student = (Student) o;

        return studentId == student.studentId;

    }

    @Override
    public int hashCode() {
        return studentId;
    }

    public String getPasswordHash() {
        return passwordHash;
    }

    public void setPasswordHash(String passwordHash) {
        this.passwordHash = passwordHash;
    }
}


text:
package org.apache.atlas.web.filters;

import org.apache.atlas.ApplicationProperties;
import org.apache.atlas.RequestContext;
import org.apache.atlas.security.SecurityProperties;
import org.apache.atlas.utils.AuthenticationUtil;
import org.apache.atlas.web.listeners.LoginProcessor;
import org.apache.atlas.web.util.Servlets;
import org.apache.commons.collections.iterators.IteratorEnumeration;
import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.ConfigurationConverter;
import org.apache.commons.lang.StringUtils;
import org.apache.hadoop.security.SecurityUtil;
import org.apache.hadoop.security.UserGroupInformation;
import org.apache.hadoop.security.authentication.client.AuthenticationException;
import org.apache.hadoop.security.authentication.client.KerberosAuthenticator;
import org.apache.hadoop.security.authentication.server.AuthenticationFilter;
import org.apache.hadoop.security.authentication.server.AuthenticationToken;
import org.apache.hadoop.security.authentication.server.KerberosAuthenticationHandler;
import org.apache.hadoop.security.authentication.server.AuthenticationHandler;
import org.apache.hadoop.security.authentication.util.Signer;
import org.apache.hadoop.security.authentication.util.SignerSecretProvider;
import org.apache.log4j.NDC;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetails;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletContext;
import javax.ws.rs.core.Response;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.security.Principal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * This enforces authentication as part of the filter before processing the request.
 * todo: Subclass of {@link org.apache.hadoop.security.authentication.server.AuthenticationFilter}.
 */

public class AtlasAuthenticationFilter extends AuthenticationFilter {
    private static final Logger LOG = LoggerFactory.getLogger(AtlasAuthenticationFilter.class);
    static final String PREFIX = "atlas.authentication.method";
    protected static ServletContext nullContext = new NullServletContext();
    private Signer signer;
    private SignerSecretProvider secretProvider;
    public  final boolean isKerberos = AuthenticationUtil.isKerberosAuthenticationEnabled();

    public AtlasAuthenticationFilter() {
        try {
            LOG.info("AtlasAuthenticationFilter initialization started");
            init(null);
        } catch (ServletException e) {
            LOG.error("Error while initializing AtlasAuthenticationFilter : " + e.getMessage());
        }
    }

    private HttpServlet optionsServlet;

    /**
     * Initialize the filter.
     *
     * @param filterConfig filter configuration.
     * @throws ServletException thrown if the filter could not be initialized.
     */
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        LOG.info("AtlasAuthenticationFilter initialization started");
        final FilterConfig globalConf = filterConfig;

        final Map<String, String> params = new HashMap<String, String>();

        FilterConfig filterConfig1 = new FilterConfig() {
            @Override
            public ServletContext getServletContext() {
                if (globalConf != null) {
                    return globalConf.getServletContext();
                } else {
                    return nullContext;
                }
            }

            @SuppressWarnings("unchecked")
            @Override
            public Enumeration<String> getInitParameterNames() {
                return new IteratorEnumeration(params.keySet().iterator());
            }

            @Override
            public String getInitParameter(String param) {
                return params.get(param);
            }

            @Override
            public String getFilterName() {
                return "AtlasAuthenticationFilter";
            }
        };

        super.init(filterConfig1);

        optionsServlet = new HttpServlet() {
        };
        optionsServlet.init();

    }

    @Override
    public void initializeSecretProvider(FilterConfig filterConfig)
            throws ServletException {
        LOG.debug("AtlasAuthenticationFilter :: initializeSecretProvider "+filterConfig);
        secretProvider = (SignerSecretProvider) filterConfig.getServletContext().
                getAttribute(AuthenticationFilter.SIGNER_SECRET_PROVIDER_ATTRIBUTE);
        if (secretProvider == null) {
            // As tomcat cannot specify the provider object in the configuration.
            // It'll go into this path
            String configPrefix = filterConfig.getInitParameter(CONFIG_PREFIX);
            configPrefix = (configPrefix != null) ? configPrefix + "." : "";
            try {
                secretProvider = AuthenticationFilter.constructSecretProvider(
                        filterConfig.getServletContext(),
                        super.getConfiguration(configPrefix, filterConfig), false);
            } catch (Exception ex) {
                throw new ServletException(ex);
            }
        }
        signer = new Signer(secretProvider);
    }

    @Override
    protected Properties getConfiguration(String configPrefix, FilterConfig filterConfig) throws ServletException {
        Configuration configuration;
        try {
            configuration = ApplicationProperties.get();
        } catch (Exception e) {
            throw new ServletException(e);
        }

        Properties config = new Properties();

        String kerberosAuthEnabled = configuration != null ? configuration.getString("atlas.authentication.method.kerberos") : null;
        // getString may return null, and would like to log the nature of the default setting
        String authMethod = "";
        if (kerberosAuthEnabled == null || kerberosAuthEnabled.equalsIgnoreCase("false")) {
            LOG.info("No authentication method configured.  Defaulting to simple authentication");
            authMethod = "simple";
        } else if (kerberosAuthEnabled.equalsIgnoreCase("true")) {
            authMethod = "kerberos";
        }

        if(configuration.getString("atlas.authentication.method.kerberos.name.rules")!=null) {
            config.put("kerberos.name.rules", configuration.getString("atlas.authentication.method.kerberos.name.rules"));
        }
        if(configuration.getString("atlas.authentication.method.kerberos.keytab")!=null) {
            config.put("kerberos.keytab", configuration.getString("atlas.authentication.method.kerberos.keytab"));
        }
        if(configuration.getString("atlas.authentication.method.kerberos.principal")!=null) {
            config.put("kerberos.principal", configuration.getString("atlas.authentication.method.kerberos.principal"));
        }
        config.put(AuthenticationFilter.AUTH_TYPE, authMethod );
        config.put(AuthenticationFilter.COOKIE_PATH, "/");

        // add any config passed in as init parameters
        Enumeration<String> enumeration = filterConfig.getInitParameterNames();
        while (enumeration.hasMoreElements()) {
            String name = enumeration.nextElement();
            config.put(name, filterConfig.getInitParameter(name));
        }

        //Resolve _HOST into bind address
        String bindAddress = configuration.getString(SecurityProperties.BIND_ADDRESS);
        if (bindAddress == null) {
            LOG.info("No host name configured.  Defaulting to local host name.");
            try {
                bindAddress = InetAddress.getLocalHost().getHostName();
            } catch (UnknownHostException e) {
                throw new ServletException("Unable to obtain host name", e);
            }
        }
        String principal = config.getProperty(KerberosAuthenticationHandler.PRINCIPAL);
        if (principal != null) {
            try {
                principal = SecurityUtil.getServerPrincipal(principal, bindAddress);
            } catch (IOException ex) {
                throw new RuntimeException("Could not resolve Kerberos principal name: " + ex.toString(), ex);
            }
            config.put(KerberosAuthenticationHandler.PRINCIPAL, principal);
        }

        LOG.debug(" AuthenticationFilterConfig: {}", config);

        return config;
    }

    @Override
    public void doFilter(final ServletRequest request, final ServletResponse response,
                         final FilterChain filterChain) throws IOException, ServletException {

        final HttpServletRequest httpRequest = (HttpServletRequest) request;
        FilterChain filterChainWrapper = new FilterChain() {
            @Override
            public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse)
                    throws IOException, ServletException {
                final HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;
                final HttpServletResponse httpResponse = (HttpServletResponse) servletResponse;

                if (isKerberos) {
                    Authentication existingAuth = SecurityContextHolder.getContext().getAuthentication();
                    String userName = readUserFromCookie(httpResponse);

                    if (StringUtils.isEmpty(userName) && !StringUtils.isEmpty(httpRequest.getRemoteUser())) {
                        userName = httpRequest.getRemoteUser();
                    }

                    if ((existingAuth == null || !existingAuth.isAuthenticated()) && (!StringUtils.isEmpty(userName))) {
                        UserGroupInformation ugi = UserGroupInformation.getLoginUser();
                        String[] groupsName = ugi.getGroupNames();

                        final List<GrantedAuthority> grantedAuths = new ArrayList<>();
                        for (String group : groupsName) {
                            grantedAuths.add(new SimpleGrantedAuthority(group));
                        }

                        final UserDetails principal = new User(userName, "", grantedAuths);
                        final Authentication finalAuthentication = new UsernamePasswordAuthenticationToken(principal, "", grantedAuths);
                        WebAuthenticationDetails webDetails = new WebAuthenticationDetails(httpRequest);
                        ((AbstractAuthenticationToken) finalAuthentication).setDetails(webDetails);
                        SecurityContextHolder.getContext().setAuthentication(finalAuthentication);

                        request.setAttribute("atlas.http.authentication.type", true);
                        LOG.info("Logged into Atlas as = " + userName);
                    }
                }
                // OPTIONS method is sent from quick start jersey atlas client
                if (httpRequest.getMethod().equals("OPTIONS")) {
                    optionsServlet.service(request, response);
                } else {
                    try {
                        String requestUser = httpRequest.getRemoteUser();
                        NDC.push(requestUser + ":" + httpRequest.getMethod() + httpRequest.getRequestURI());
                        RequestContext requestContext = RequestContext.get();
                        if(requestContext!=null) {
                            requestContext.setUser(requestUser);
                        }
                        LOG.info("Request from authenticated user: {}, URL={}", requestUser,
                                Servlets.getRequestURI(httpRequest));

                        filterChain.doFilter(servletRequest, servletResponse);
                    } finally {
                        NDC.pop();
                    }
                }
            }
        };

        try {
            String authHeader = httpRequest.getHeader("Authorization");
            if (authHeader != null && authHeader.startsWith("Basic")) {
                filterChain.doFilter(request, response);
            } else if (isKerberos) {
                doKerberosAuth(request, response, filterChainWrapper);
            } else {
                filterChain.doFilter(request, response);
            }
        } catch (NullPointerException e) {
            LOG.error("Exception in AtlasAuthenticationFilter ", e);
            //PseudoAuthenticationHandler.getUserName() from hadoop-auth throws NPE if user name is not specified
            ((HttpServletResponse) response).sendError(Response.Status.BAD_REQUEST.getStatusCode(),
                    "Authentication is enabled and user is not specified. Specify user.name parameter");
        }
    }

    /**
     * This method is copied from hadoop auth lib, code added for error handling and fallback to other auth methods
     *
     * If the request has a valid authentication token it allows the request to continue to the target resource,
     * otherwise it triggers an authentication sequence using the configured {@link org.apache.hadoop.security.authentication.server.AuthenticationHandler}.
     *
     * @param request the request object.
     * @param response the response object.
     * @param filterChain the filter chain object.
     *
     * @throws IOException thrown if an IO error occurred.
     * @throws ServletException thrown if a processing error occurred.
     */
    public void doKerberosAuth(ServletRequest request, ServletResponse response, FilterChain filterChain)
            throws IOException, ServletException {
        boolean unauthorizedResponse = true;
        int errCode = HttpServletResponse.SC_UNAUTHORIZED;
        AuthenticationException authenticationEx = null;
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        boolean isHttps = "https".equals(httpRequest.getScheme());
        AuthenticationHandler   authHandler = getAuthenticationHandler();
        try {
            boolean newToken = false;
            AuthenticationToken token;
            try {
                token = getToken(httpRequest);
            }
            catch (AuthenticationException ex) {
                LOG.warn("AuthenticationToken ignored: " + ex.getMessage());
                // will be sent back in a 401 unless filter authenticates
                authenticationEx = ex;
                token = null;
            }
            if (authHandler.managementOperation(token, httpRequest, httpResponse)) {
                if (token == null) {
                    if (LOG.isDebugEnabled()) {
                        LOG.debug("Request [{}] triggering authentication", getRequestURL(httpRequest));
                    }
                    token = authHandler.authenticate(httpRequest, httpResponse);
                    if (token != null && token.getExpires() != 0 &&
                            token != AuthenticationToken.ANONYMOUS) {
                        token.setExpires(System.currentTimeMillis() + getValidity() * 1000);
                    }
                    newToken = true;
                }
                if (token != null) {
                    unauthorizedResponse = false;
                    if (LOG.isDebugEnabled()) {
                        LOG.debug("Request [{}] user [{}] authenticated", getRequestURL(httpRequest), token.getUserName());
                    }
                    final AuthenticationToken authToken = token;
                    httpRequest = new HttpServletRequestWrapper(httpRequest) {

                        @Override
                        public String getAuthType() {
                            return authToken.getType();
                        }

                        @Override
                        public String getRemoteUser() {
                            return authToken.getUserName();
                        }

                        @Override
                        public Principal getUserPrincipal() {
                            return (authToken != AuthenticationToken.ANONYMOUS) ? authToken : null;
                        }
                    };
                    if (newToken && !token.isExpired() && token != AuthenticationToken.ANONYMOUS) {
                        String signedToken = signer.sign(token.toString());
                        createAuthCookie(httpResponse, signedToken, getCookieDomain(),
                                getCookiePath(), token.getExpires(), isHttps);
                    }

                   filterChain.doFilter(httpRequest, httpResponse);
                }
            } else {
                unauthorizedResponse = false;
            }
        } catch (AuthenticationException ex) {
            // exception from the filter itself is fatal
            errCode = HttpServletResponse.SC_FORBIDDEN;
            authenticationEx = ex;
            LOG.warn("Authentication exception: " + ex.getMessage(), ex);
        }
        if (unauthorizedResponse) {
            if (!httpResponse.isCommitted()) {
                createAuthCookie(httpResponse, "", getCookieDomain(),
                        getCookiePath(), 0, isHttps);
                // If response code is 401. Then WWW-Authenticate Header should be
                // present.. reset to 403 if not found..
                if ((errCode == HttpServletResponse.SC_UNAUTHORIZED)
                        && (!httpResponse.containsHeader(
                        KerberosAuthenticator.WWW_AUTHENTICATE))) {
                    errCode = HttpServletResponse.SC_FORBIDDEN;
                }
                if (authenticationEx == null) { // added this code for atlas error handling and fallback
                    boolean chk = true;
                    Collection<String> headerNames = httpResponse.getHeaderNames();
                    for (String headerName : headerNames) {
                        String value = httpResponse.getHeader(headerName);
                        if (headerName.equalsIgnoreCase("Set-Cookie") && value.startsWith("JSESSIONID")) {
                            chk = false;
                            break;
                        }
                    }
                    String authHeader = httpRequest.getHeader("Authorization");
                    if (authHeader == null && chk) {
                        filterChain.doFilter(request, response);
                    } else if (authHeader != null && authHeader.startsWith("Basic")) {
                        filterChain.doFilter(request, response);
                    }

                } else {
                    httpResponse.sendError(errCode, authenticationEx.getMessage());
                }
            }
        }
    }

    @Override
    public void destroy() {
        optionsServlet.destroy();
        super.destroy();
    }

    private static String readUserFromCookie(HttpServletResponse response1) {
        String userName = null;
        boolean isCookieSet = response1.containsHeader("Set-Cookie");
        if (isCookieSet) {
            Collection<String> authUserName = response1.getHeaders("Set-Cookie");
            if (authUserName != null) {
                Iterator<String> i = authUserName.iterator();
                while (i.hasNext()) {
                    String cookie = i.next();
                    if (!StringUtils.isEmpty(cookie)) {
                        if (cookie.toLowerCase().startsWith("hadoop.auth".toLowerCase()) && cookie.contains("u=")) {
                            String[] split = cookie.split(";");
                            if (split != null) {
                                for (String s : split) {
                                    if (!StringUtils.isEmpty(s) && s.toLowerCase().startsWith("hadoop.auth".toLowerCase())) {
                                        int ustr = s.indexOf("u=");
                                        if (ustr != -1) {
                                            int andStr = s.indexOf("&", ustr);
                                            if (andStr != -1) {
                                                try {
                                                    userName = s.substring(ustr + 2, andStr);
                                                    break;
                                                } catch (Exception e) {
                                                    userName = null;
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        return userName;
    }

    public static void createAuthCookie(HttpServletResponse resp, String token, String domain, String path, long expires, boolean isSecure) {
        StringBuilder sb = (new StringBuilder("hadoop.auth")).append("=");
        if(token != null && token.length() > 0) {
            sb.append("\"").append(token).append("\"");
        }

        sb.append("; Version=1");
        if(path != null) {
            sb.append("; Path=").append(path);
        }

        if(domain != null) {
            sb.append("; Domain=").append(domain);
        }

        if(expires >= 0L) {
            Date date = new Date(expires);
            SimpleDateFormat df = new SimpleDateFormat("EEE, dd-MMM-yyyy HH:mm:ss zzz");
            df.setTimeZone(TimeZone.getTimeZone("GMT"));
            sb.append("; Expires=").append(df.format(date));
        }

        if(isSecure) {
            sb.append("; Secure");
        }

        sb.append("; HttpOnly");
        resp.addHeader("Set-Cookie", sb.toString());
    }

}


text:
import os

from spec import Spec, trap, eq_

from invoke import run

def _output_eq(cmd, expected):
    return eq_(run(cmd).stdout, expected)

class Main(Spec):
    def setup(self):
        # Enter integration/ so Invoke loads its local tasks.py
        os.chdir(os.path.dirname(__file__))

    @trap
    def basic_invocation(self):
        _output_eq("invoke print_foo", "foo\n")

    @trap
    def shorthand_binary_name(self):
        _output_eq("inv print_foo", "foo\n")

    @trap
    def explicit_task_module(self):
        _output_eq("inv --collection _explicit foo", "Yup\n")

    @trap
    def invocation_with_args(self):
        _output_eq(
            "inv print_name --name whatevs",
            "whatevs\n"
        )

    @trap
    def bad_collection_exits_nonzero(self):
        result = run("inv -c nope -l", warn=True)
        eq_(result.exited, 1)
        assert not result.stdout
        assert result.stderr


text:
using System.Xml.Serialization;

namespace MAL.NetLogic.Interfaces
{
    public interface IMyInfoXml
    {
        [XmlElement(ElementName = "user_id")]
        string UserId { get; set; }

        [XmlElement(ElementName = "user_name")]
        string Username { get; set; }

        [XmlElement(ElementName = "user_watching")]
        int Watching { get; set; }

        [XmlElement(ElementName = "user_completed")]
        int Completed { get; set; }

        [XmlElement(ElementName = "user_onhold")]
        int OnHold { get; set; }

        [XmlElement(ElementName = "user_dropped")]
        int Dropped { get; set; }

        [XmlElement(ElementName = "user_plantowatch")]
        int PlanToWatch { get; set; }

        [XmlElement(ElementName = "user_days_spent_watching")]
        double DaysWatching { get; set; }
    }
}


text:
const express = require("express");
const path = require('path');

// app is a instance of express
// to run express on top of nodejs need to run app instance
const app = express();

// to use middleware app.use
// express built-in middleware for static dir files to server
// from assets we serve app.css
app.use(express.static('assets'));

// for mutiple static dir
// from file we serve index.html
app.use(express.static('files'));

// to create path prefix virtual dir
// from virtual we serve images
app.use('/virtual', express.static(path.join(__dirname, 'images')));

// basic http get request on '/'
app.get('/', function(req, res) {
    res.send("Hello World!");
});

// server port listen on 3000
app.listen(3000, function() {
    console.log('Server is running on port 3000');
});


text:
{-# LANGUAGE RankNTypes #-}

module Text.Greek.Script.Place where

import qualified Data.Set as Set

data Initial = IsInitial | NotInitial deriving (Eq, Ord, Show)
data Medial = IsMedial | NotMedial deriving (Eq, Ord, Show)
data Final = IsFinal | NotFinal deriving (Eq, Ord, Show)

type Place3 = (Initial, Medial, Final)

initialFinal :: Place3
initialFinal = (IsInitial, NotMedial, IsFinal)

initial :: Place3
initial = (IsInitial, NotMedial, NotFinal)

final :: Place3
final = (NotInitial, NotMedial, IsFinal)

medial :: Place3
medial = (NotInitial, IsMedial, NotFinal)

getInitialSet :: Ord c => [(c, Place3)] -> Set.Set c
getInitialSet = Set.fromList . concatMap go
  where
    go (c, p) | (IsInitial,_,_) <- p = [c]
    go _ = []

data AttestedInitial = AttestedInitial | UnattestedInitial deriving (Eq, Ord, Show)

type Place4 = (Initial, Medial, Final, AttestedInitial)

applyAttestation :: Ord c => Set.Set c -> (c, Place3) -> (c, Place4)
applyAttestation ss (c, p)
  | (_,IsMedial,_) <- p
  , Set.member c ss
  = (c, addAttestedInitial p AttestedInitial)
applyAttestation _ (c, p) = (c, addAttestedInitial p UnattestedInitial)

addAttestedInitial :: Place3 -> AttestedInitial -> Place4
addAttestedInitial (a, b, c) d = (a, b, c, d)

markInitial :: [a] -> [(Initial, a)]
markInitial [] = []
markInitial (x : xs) = (IsInitial, x) : fmap (\y -> (NotInitial, y)) xs


text:
import os
RELEASE = False

from wsgidav.version import __version__

from ez_setup import use_setuptools
use_setuptools()

from setuptools import setup, find_packages

# 'setup.py upload' fails on Vista, because .pypirc is searched on 'HOME' path
if not "HOME" in os.environ and  "HOMEPATH" in os.environ:
    os.environ.setdefault("HOME", os.environ.get("HOMEPATH", ""))
    print "Initializing HOME environment variable to '%s'" % os.environ["HOME"]

setup(name="WsgiDAV",
      version = __version__,
      author = "Martin Wendt, Ho Chun Wei",
      author_email = "wsgidav@wwwendt.de",
      maintainer = "Martin Wendt",
      maintainer_email = "wsgidav@wwwendt.de",
      url = "https://github.com/mar10/wsgidav/",
      description = "Generic WebDAV server based on WSGI",
      long_description="""\
WsgiDAV is a WebDAV server for sharing files and other resources over the web.
It is based on the WSGI interface <http://www.python.org/peps/pep-0333.html>.

It comes bundled with a simple WSGI web server.

*This package is based on PyFileServer by Ho Chun Wei.*

Project home: https://github.com/mar10/wsgidav/
""",

        #Development Status :: 2 - Pre-Alpha
        #Development Status :: 3 - Alpha
        #Development Status :: 4 - Beta
        #Development Status :: 5 - Production/Stable

      classifiers = ["Development Status :: 5 - Production/Stable",
                     "Intended Audience :: Information Technology",
                     "Intended Audience :: Developers",
                     "Intended Audience :: System Administrators",
                     "License :: OSI Approved :: MIT License",
                     "Operating System :: OS Independent",
                     "Programming Language :: Python",
                     "Topic :: Internet :: WWW/HTTP",
                     "Topic :: Internet :: WWW/HTTP :: HTTP Servers",
                     "Topic :: Internet :: WWW/HTTP :: Dynamic Content",
                     "Topic :: Internet :: WWW/HTTP :: WSGI",
                     "Topic :: Internet :: WWW/HTTP :: WSGI :: Application",
                     "Topic :: Internet :: WWW/HTTP :: WSGI :: Server",
                     "Topic :: Software Development :: Libraries :: Python Modules",
                     ],
      keywords = "web wsgi webdav application server",
#      platforms=["Unix", "Windows"],
      license = "The MIT License",
#      install_requires = ["lxml"],
      packages = find_packages(exclude=[]),
      py_modules = ["ez_setup", ],

#      package_data={"": ["*.txt", "*.html", "*.conf"]},
#      include_package_data = True, # TODO: PP
      zip_safe = False,
      extras_require = {},
      tests_require = ["nose",   # run nosetests
                       "Paste",  # paste.fixture.TestApp
                       ],
#      test_suite = "tests.test_all.run",
      test_suite = "nose.collector",
      entry_points = {
          "console_scripts" : ["wsgidav = wsgidav.server.run_server:run"],
          },
      # TODO: PP:
#      entry_points = """
#      [paste.app_factory]
#      main = wsgidav.wsgiapp:make_app
#      """,
      )


text:
<?php

namespace common\extensions\parser;

use common\extensions\parser\Word;
use common\extensions\parser\Line;
use common\extensions\parser\WordTester;

/**
 * Incapsulates counting logic intended for intelligence imitation. It is need
 * to find brands and subsections.
 */
class Counter
{
    const TYPE_BRAND = 0;
    const TYPE_CATEGORY = 1;

    protected $_list;
    protected $_type;
    protected $_tester;

    /**
     * Creates new Counter instance with `brand` type.
     *
     * @return \common\extensions\parser\Counter
     */
    public static function brand()
    {
        $counter = new Counter();
        $counter->_type = self::TYPE_BRAND;
        return $counter;
    }

    /**
     * Creates new Counter instance with `category` type.
     *
     * @return \common\extensions\parser\Counter
     */
    public static function category()
    {
        $counter = new Counter();
        $counter->_type = self::TYPE_CATEGORY;
        return $counter;
    }

    /**
     * Sets the WordTester that counter will use.
     *
     * @param WordTester $tester
     * @return \common\extensions\parser\Counter
     */
    public function useTester(WordTester $tester)
    {
        $this->_tester = $tester;
        return $this;
    }

    /**
     * Answers if the counter has `brand` type.
     *
     * @return boolean
     */
    public function isBrand()
    {
        return $this->_type === self::TYPE_BRAND;
    }

    /**
     * Answers if the counter has `category` type.
     *
     * @return boolean
     */
    public function isCategory()
    {
        return $this->_type === self::TYPE_CATEGORY;
    }

    /**
     * Counts word in single line.
     *
     * @param Line $line
     */
    public function count(Line $line)
    {
        $line->each(function(Word $word, $data) {
            if (!$this->validate($word)) {
                return;
            }

            if ($this->isCategory()) {
                $this->nounCount($data);
            } else {
                $this->simpleCount($data);
            }
        });
    }

    /**
     * Defines word type if it is not determined as brand or category.
     *
     * @param Word $word
     */
    public function throwOut(Word $word)
    {
        if ($this->isBrand()) {
            $word->asModelPart();
        }
    }

    /**
     * Defines word type if it is determined as brand or category.
     *
     * @param Word $word
     */
    public function accept(Word $word)
    {
        if ($this->isBrand()) {
            $word->asBrand();
        } else {
            $word->asSubsection();
        }
    }

    /**
     * Returns if the first word has bigger count than second.
     *
     * @param string $first first word to compare
     * @param string $second second word to compare
     * @return boolean
     */
    public function greater($first, $second)
    {
        if (!isset($this->_list[$first])) {
            return false;
        }

        if (!isset($this->_list[$second])) {
            return true;
        }

        return $this->_list[$first] > $this->_list[$second];
    }

    /**
     * Removes word from counter list if it was throwed out.
     *
     * @param string $word
     */
    public function remove($word)
    {
        if (!isset($this->_list[$word])) {
            return;
        }

        unset($this->_list[$word]);
    }

    /**
     * Validates word to have right type depending on counter type.
     *
     * @param Word $word
     * @return boolean
     */
    public function validate(Word $word)
    {
        return ($this->isBrand() && $word->isUnknownPart()) ||
            ($this->isCategory() && $word->isNamePart());
    }

    protected function __construct() {}

    /**
     * Simply counts word.
     *
     * @param string $data
     */
    protected function simpleCount($data)
    {
        if (!isset($this->_list[$data])) {
            $this->_list[$data] = 0;
        }

        $this->_list[$data] += 1;
    }

    /**
     * Counts word only if it is a noun.
     *
     * @param string $data
     */
    protected function nounCount($data)
    {
        if (!$this->_tester->testNoun($data)) {
            return;
        }

        $this->simpleCount($data);
    }
}


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

/** @interface */
function InjectedScriptHostClass()
{
}

/**
 */
InjectedScriptHostClass.prototype.clearConsoleMessages = function() {}

/**
 * @param {*} objectId
 * @param {!Object} hints
 */
InjectedScriptHostClass.prototype.inspect = function(objectId, hints) {}

/**
 * @param {number} num
 * @return {*}
 */
InjectedScriptHostClass.prototype.inspectedObject = function(num) {}

/**
 * @param {*} obj
 * @return {string}
 */
InjectedScriptHostClass.prototype.internalConstructorName = function(obj) {}

/**
 * @param {*} obj
 * @return {boolean}
 */
InjectedScriptHostClass.prototype.formatAccessorsAsProperties = function(obj) {}

/**
 * @param {*} obj
 * @return {boolean}
 */
InjectedScriptHostClass.prototype.isTypedArray = function(obj) {}

/**
 * @param {*} obj
 * @return {string}
 */
InjectedScriptHostClass.prototype.subtype = function(obj) {}

/**
 * @param {!Function} obj
 * @return {*}
 */
InjectedScriptHostClass.prototype.functionDetails = function(obj) {}

/**
 * @param {!Object} obj
 * @return {?Object}
 */
InjectedScriptHostClass.prototype.generatorObjectDetails = function(obj) {}

/**
 * @param {!Object} obj
 * @return {?Array.<*>}
 */
InjectedScriptHostClass.prototype.collectionEntries = function(obj) {}

/**
 * @param {*} obj
 * @return {!Array.<*>}
 */
InjectedScriptHostClass.prototype.getInternalProperties = function(obj) {}

/**
 * @param {!EventTarget} target
 * @return {!Object|undefined}
 */
InjectedScriptHostClass.prototype.getEventListeners = function(target) {}

/**
 * @param {string} text
 * @return {*}
 */
InjectedScriptHostClass.prototype.eval = function(text) {}

/**
 * @param {string} text
 * @param {!Object=} commandLineAPI
 * @return {*}
 */
InjectedScriptHostClass.prototype.evaluateWithExceptionDetails = function(text, commandLineAPI) {}

/**
 * @param {*} fn
 */
InjectedScriptHostClass.prototype.debugFunction = function(fn) {}

/**
 * @param {*} fn
 */
InjectedScriptHostClass.prototype.undebugFunction = function(fn) {}

/**
 * @param {*} fn
 */
InjectedScriptHostClass.prototype.monitorFunction = function(fn) {}

/**
 * @param {*} fn
 */
InjectedScriptHostClass.prototype.unmonitorFunction = function(fn) {}

/**
 * @param {!Function} fn
 * @param {*} receiver
 * @param {!Array.<*>=} argv
 * @return {*}
 */
InjectedScriptHostClass.prototype.callFunction = function(fn, receiver, argv) {}

/**
 * @param {!Function} fn
 * @param {*} receiver
 * @param {!Array.<*>=} argv
 * @return {*}
 */
InjectedScriptHostClass.prototype.suppressWarningsAndCallFunction = function(fn, receiver, argv) {}

/**
 * @param {!Object} obj
 * @param {string} key
 * @param {*} value
 */
InjectedScriptHostClass.prototype.setNonEnumProperty = function(obj, key, value) {}

/**
 * @param {!Function} functionObject
 * @param {number} scopeIndex
 * @param {string} variableName
 * @param {*} newValue
 * @return {*}
 */
InjectedScriptHostClass.prototype.setFunctionVariableValue = function(functionObject, scopeIndex, variableName, newValue) {}

/**
 * @param {*} value
 * @param {string} groupName
 * @return {number}
 */
InjectedScriptHostClass.prototype.bind = function(value, groupName) {}

/**
 * @param {number} id
 * @return {*}
 */
InjectedScriptHostClass.prototype.objectForId = function(id) {}

/**
 * @param {number} id
 * @return {string}
 */
InjectedScriptHostClass.prototype.idToObjectGroupName = function(id) {}

/** @type {!InjectedScriptHostClass} */
var InjectedScriptHost;

/** @interface */
function JavaScriptCallFrame()
{
    /** @type {!JavaScriptCallFrame} */
    this.caller;
    /** @type {number} */
    this.sourceID;
    /** @type {number} */
    this.line;
    /** @type {number} */
    this.column;
    /** @type {!Array.<!Object>} */
    this.scopeChain;
    /** @type {!Object} */
    this.thisObject;
    /** @type {string} */
    this.stepInPositions;
    /** @type {string} */
    this.functionName;
    /** @type {number} */
    this.functionLine;
    /** @type {number} */
    this.functionColumn;
    /** @type {boolean} */
    this.isAtReturn;
    /** @type {*} */
    this.returnValue;
}

/**
 * @param {string} script
 * @param {!Object=} scopeExtension
 * @return {*}
 */
JavaScriptCallFrame.prototype.evaluateWithExceptionDetails = function(script, scopeExtension) {}

/**
 * @return {*}
 */
JavaScriptCallFrame.prototype.restart = function() {}

/**
 * @param {number=} scopeIndex
 * @param {?string=} variableName
 * @param {*=} newValue
 * @return {*}
 */
JavaScriptCallFrame.prototype.setVariableValue = function(scopeIndex, variableName, newValue) {}

/**
 * @param {number} scopeIndex
 * @return {number}
 */
JavaScriptCallFrame.prototype.scopeType = function(scopeIndex) {}

/**
 * @param {number} scopeIndex
 * @return {string}
 */
JavaScriptCallFrame.prototype.scopeName = function(scopeIndex) {}

/**
 * @param {number} scopeIndex
 * @return {?DebuggerAgent.Location}
 */
JavaScriptCallFrame.prototype.scopeStartLocation = function(scopeIndex) {}

/**
 * @param {number} scopeIndex
 * @return {?DebuggerAgent.Location}
 */
JavaScriptCallFrame.prototype.scopeEndLocation = function(scopeIndex) {}

/** @type {!Window} */
var inspectedGlobalObject;
/** @type {number} */
var injectedScriptId;