text:
require File.expand_path('../../../spec_helper', __FILE__)
require File.expand_path('../fixtures/classes', __FILE__)

describe "Struct#[]=" do
  it "assigns the passed value" do
    car = Struct::Car.new('Ford', 'Ranger')

    car[:model] = 'Escape'
    car[:model].should == 'Escape'

    car['model'] = 'Fusion'
    car[:model].should == 'Fusion'

    car[1] = 'Excursion'
    car[:model].should == 'Excursion'

    car[-1] = '2000-2005'
    car[:year].should == '2000-2005'
  end

  it "fails when trying to assign attributes which don't exist" do
    car = Struct::Car.new('Ford', 'Ranger')

    lambda { car[:something] = true }.should raise_error(NameError)
    lambda { car[3] = true          }.should raise_error(IndexError)
    lambda { car[-4] = true         }.should raise_error(IndexError)
    lambda { car[Object.new] = true }.should raise_error(TypeError)
  end
end


text:
'use strict';
module.exports = require('./')('fixture');

redpajama_set_name: RedPajamaGithub


text:
header! { (ESCurrentVersion, "ES-CurrentVersion") => [String] }
header! { (ESExpectedVersion, "ES-ExpectedVersion") => [String] }
header! { (ESResolveLinkTos, "ES-ResolveLinkTos") => [bool] }
header! { (ESHardDelete, "ES-HardDelete") => [bool] }

pub mod append_to_stream;
pub mod read_stream_events_forward;
pub mod delete_stream;
mod to_error;


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _03.Demo
{
    class Program
    {
        //static void printConcatanneted(string leftString, string rightString)
        //{
        //    Console.WriteLine(leftString + rightString);
        //}
        //static void Main(string[] args)
        //{
        //    printConcatanneted(" asda", "     asdaaaaa");
        //}

        static int Parse(string number)
        {
            int result = 0;
            foreach (var digit in number)
            {
                result = (digit - '0' + result * 10);
            }
            return result;
        }
        static int Parse(char [] digits)
        {
            return 0;
        }
        static void Main()
        {
            Console.WriteLine(Parse("251"));
            var parsedValue = Parse("251");
            Console.WriteLine(parsedValue);
        }

    }
}


text:
module CourseUser::LevelProgressConcern
  extend ActiveSupport::Concern

  delegate :level_number, :next_level_threshold, to: :current_level

  # Returns the level object of the CourseUser with respect to a course's Course::Levels.
  #
  # @return [Course::Level] Level of CourseUser.
  def current_level
    @current_level ||= course.level_for(experience_points)
  end

  # Computes the percentage (a fixnum ranging from 0-100) of the CourseUser's EXP progress
  # between the current level and the next.  If the CourseUser is at the highest level,
  # the percentage will be set at 100.
  #
  # eg. Current EXP: 500, Level 1 Threshold: 200, Level 2 Threshold: 600
  # Then CourseUser.level_progress_percentage = 75 # [(500 - 200) / (600 - 200)]
  #
  # @return [Fixnum] The CourseUser's EXP progress percentage.
  def level_progress_percentage
    if current_level.next
      current_experience_progress = experience_points - current_level.experience_points_threshold
      experience_between_levels = current_level.next.experience_points_threshold -
                                  current_level.experience_points_threshold
      100 * current_experience_progress / experience_between_levels
    else
      100
    end
  end
end


text:
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import net.schmizz.sshj.SSHClient;
import net.schmizz.sshj.sftp.SFTPClient;
import net.schmizz.sshj.transport.verification.PromiscuousVerifier;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.spongepowered.include.com.google.common.io.ByteStreams;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class UpdateSolder {

	private final String sftpPath;
	private final String apiToken;
	private final SFTPClient sftpClient;

	private static final Path OUTPUT_PATH = Paths.get("temp");
	private static final String[] MINECRAFT_VERSIONS = {"1.16.5", "1.17.1", "1.18.2", "1.19.2"};
	private static final Map<String, String> MOD_ID_MAP = new HashMap<>();
	private static final Map<String, String> MODPACK_ID_MAP = new HashMap<>();
	private static final Map<String, String> DUMMY_BUILD_ID_MAP = new HashMap<>();
	private static final Map<String, String> DUMMY_MOD_MAP = new HashMap<>();
	private static final Map<String, String> NEW_MOD_MAP = new HashMap<>();

	static {
		MOD_ID_MAP.put("mtr", "1");
		MOD_ID_MAP.put("mtr-london-underground-addon", "4");
		MOD_ID_MAP.put("fabric-loader", "2");
		MOD_ID_MAP.put("fabric-api", "3");
		MOD_ID_MAP.put("forge-loader", "5");
		MOD_ID_MAP.put("forge-architectury", "6");
		MOD_ID_MAP.put("modmenu", "7");

		MODPACK_ID_MAP.put("fabric-1.16.5", "2");
		MODPACK_ID_MAP.put("forge-1.16.5", "4");
		MODPACK_ID_MAP.put("fabric-1.17.1", "3");
		MODPACK_ID_MAP.put("forge-1.17.1", "8");
		MODPACK_ID_MAP.put("fabric-1.18.2", "5");
		MODPACK_ID_MAP.put("forge-1.18.2", "9");
		MODPACK_ID_MAP.put("fabric-1.19.2", "7");
		MODPACK_ID_MAP.put("forge-1.19.2", "10");
		MODPACK_ID_MAP.put("centown-classic", "6");

		DUMMY_BUILD_ID_MAP.put("fabric-1.16.5", "143");
		DUMMY_BUILD_ID_MAP.put("forge-1.16.5", "144");
		DUMMY_BUILD_ID_MAP.put("fabric-1.17.1", "145");
		DUMMY_BUILD_ID_MAP.put("forge-1.17.1", "146");
		DUMMY_BUILD_ID_MAP.put("fabric-1.18.2", "147");
		DUMMY_BUILD_ID_MAP.put("forge-1.18.2", "148");
		DUMMY_BUILD_ID_MAP.put("fabric-1.19.2", "149");
		DUMMY_BUILD_ID_MAP.put("forge-1.19.2", "150");
		DUMMY_BUILD_ID_MAP.put("centown-classic", "142");

		DUMMY_MOD_MAP.put("mtr-fabric-1.16.5", "fabric-1.16.5-3.0.1");
		DUMMY_MOD_MAP.put("mtr-fabric-1.17.1", "fabric-1.17.1-3.0.1");
		DUMMY_MOD_MAP.put("mtr-fabric-1.18.2", "fabric-1.18.2-3.0.1");
		DUMMY_MOD_MAP.put("mtr-fabric-1.19.2", "fabric-1.19-3.0.1");
		DUMMY_MOD_MAP.put("mtr-forge-1.16.5", "forge-1.16.5-3.0.1");
		DUMMY_MOD_MAP.put("mtr-forge-1.17.1", "forge-1.17.1-3.0.1");
		DUMMY_MOD_MAP.put("mtr-forge-1.18.2", "forge-1.18.2-3.0.1");
		DUMMY_MOD_MAP.put("mtr-forge-1.19.2", "forge-1.19-3.0.1");
		DUMMY_MOD_MAP.put("mtr-london-underground-addon-fabric-1.16.5", "fabric-1.16.5-3.0.1-1.2");
		DUMMY_MOD_MAP.put("mtr-london-underground-addon-fabric-1.17.1", "fabric-1.17.1-3.0.1-1.2");
		DUMMY_MOD_MAP.put("mtr-london-underground-addon-fabric-1.18.2", "fabric-1.18.2-3.0.1-1.2");
		DUMMY_MOD_MAP.put("mtr-london-underground-addon-fabric-1.19.2", "fabric-1.19.2-3.0.1-1.2");
		DUMMY_MOD_MAP.put("mtr-london-underground-addon-forge-1.16.5", "forge-1.16.5-3.0.1-1.2");
		DUMMY_MOD_MAP.put("mtr-london-underground-addon-forge-1.17.1", "forge-1.17.1-3.0.1-1.2");
		DUMMY_MOD_MAP.put("mtr-london-underground-addon-forge-1.18.2", "forge-1.18.2-3.0.1-1.2");
		DUMMY_MOD_MAP.put("mtr-london-underground-addon-forge-1.19.2", "forge-1.19.2-3.0.1-1.2");
		DUMMY_MOD_MAP.put("fabric-loader-1.16.5", "1.16.5-0.14.8");
		DUMMY_MOD_MAP.put("fabric-loader-1.17.1", "1.17.1-0.14.8");
		DUMMY_MOD_MAP.put("fabric-loader-1.18.2", "1.18.2-0.14.8");
		DUMMY_MOD_MAP.put("fabric-loader-1.19.2", "1.19-0.14.8");
		DUMMY_MOD_MAP.put("fabric-api-1.16.5", "0.42.0+1.16");
		DUMMY_MOD_MAP.put("fabric-api-1.17.1", "0.46.1+1.17");
		DUMMY_MOD_MAP.put("fabric-api-1.18.2", "0.57.0+1.18.2");
		DUMMY_MOD_MAP.put("fabric-api-1.19.2", "0.57.0+1.19");
		DUMMY_MOD_MAP.put("forge-loader-1.16.5", "1.16.5-36.2.34");
		DUMMY_MOD_MAP.put("forge-loader-1.17.1", "1.17.1-37.1.1");
		DUMMY_MOD_MAP.put("forge-loader-1.18.2", "1.18.2-40.1.0");
		DUMMY_MOD_MAP.put("forge-loader-1.19.2", "1.19-41.0.63");
		DUMMY_MOD_MAP.put("forge-architectury-1.16.5", "1.32.66+forge-1.16.5");
		DUMMY_MOD_MAP.put("forge-architectury-1.17.1", "2.10.12+forge-1.17.1");
		DUMMY_MOD_MAP.put("forge-architectury-1.18.2", "4.4.71+forge-1.18.2");
		DUMMY_MOD_MAP.put("forge-architectury-1.19.2", "5.7.28+forge-1.19");
		DUMMY_MOD_MAP.put("modmenu-1.16.5", "1.16.5-1.16.22");
		DUMMY_MOD_MAP.put("modmenu-1.17.1", "2.0.15-1.17.1");
		DUMMY_MOD_MAP.put("modmenu-1.18.2", "3.2.3-1.18.2");
		DUMMY_MOD_MAP.put("modmenu-1.19.2", "4.0.0-1.19");
	}

	public static void main(String[] args) throws IOException {
		if (args.length == 5) {
			new UpdateSolder(args[0], args[1], args[2], args[3], args[4]);
		}
	}

	private UpdateSolder(String sftpHost, String sftpUsername, String sftpPassword, String sftpPath, String apiToken) throws IOException {
		this.sftpPath = sftpPath;
		this.apiToken = apiToken;

		final SSHClient sshClient = new SSHClient();
		sshClient.addHostKeyVerifier(new PromiscuousVerifier());
		sshClient.connect(sftpHost);
		sshClient.authPassword(sftpUsername, sftpPassword);
		sftpClient = sshClient.newSFTPClient();

		FileUtils.deleteQuietly(OUTPUT_PATH.toFile());

		final String mtrVersion = readUrl("https://www.minecrafttransitrailway.com/libs/latest/latest.json", new JsonObject()).getAsJsonObject().get("version").getAsString();
		final String luVersion = readUrl("https://www.minecrafttransitrailway.com/libs/latest/latest-lu-addon.json", new JsonObject()).getAsJsonObject().get("version").getAsString();
		for (final String minecraftVersion : MINECRAFT_VERSIONS) {
			for (final Loader loader : Loader.values()) {
				final String modVersionMtr = loader.loader + "-" + minecraftVersion + "-" + mtrVersion;
				final String modVersionLu = loader.loader + "-" + minecraftVersion + "-" + luVersion;
				uploadZip("https://www.minecrafttransitrailway.com/libs/latest/MTR-" + loader.loader + "-" + minecraftVersion + "-latest.jar", minecraftVersion, "mtr", "mods/MTR-" + modVersionMtr + ".jar", modVersionMtr);
				uploadZip("https://www.minecrafttransitrailway.com/libs/latest/MTR-LU-Addon-" + loader.loader + "-" + minecraftVersion + "-latest.jar", minecraftVersion, "mtr-london-underground-addon", "mods/MTR-LU-Addon-" + modVersionLu + ".jar", modVersionLu);
			}

			try {
				final String fabricLoaderVersion = readUrl("https://meta.fabricmc.net/v2/versions/loader/" + minecraftVersion, new JsonArray()).getAsJsonArray().get(0).getAsJsonObject().getAsJsonObject("loader").get("version").getAsString();
				uploadZip("https://meta.fabricmc.net/v2/versions/loader/" + minecraftVersion + "/" + fabricLoaderVersion + "/profile/json", minecraftVersion, "fabric-loader", "bin/version.json", minecraftVersion + "-" + fabricLoaderVersion);
			} catch (Exception e) {
				e.printStackTrace();
			}

			try {
				final JsonObject forgeVersionsObject = readUrl("https://files.minecraftforge.net/net/minecraftforge/forge/promotions_slim.json", new JsonObject()).getAsJsonObject().getAsJsonObject("promos");
				final String forgeVersion = minecraftVersion + "-" + forgeVersionsObject.get(minecraftVersion + "-latest").getAsString();
				uploadZip("https://maven.minecraftforge.net/net/minecraftforge/forge/" + forgeVersion + "/forge-" + forgeVersion + "-installer.jar", minecraftVersion, "forge-loader", "bin/modpack.jar", forgeVersion);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		uploadModrinthMod(Loader.FABRIC, "P7dR8mSH", "fabric-api");
		uploadModrinthMod(Loader.FABRIC, "mOgUt4GM", "modmenu");
		uploadModrinthMod(Loader.FORGE, "lhGA9TYQ", "forge-architectury");

		FileUtils.deleteQuietly(OUTPUT_PATH.toFile());
		sftpClient.close();
		sshClient.disconnect();

		final String buildVersion = mtrVersion + "-" + new SimpleDateFormat("yyyyMMdd-HHmmss").format(new Date());
		for (final String minecraftVersion : MINECRAFT_VERSIONS) {
			for (final Loader loader : Loader.values()) {
				final String combinedVersion = loader.loader + "-" + minecraftVersion;
				final String buildId = sendRequest("create-build?modpack_id=%s&version=%s&minecraft=%s&clone=%s&memory-enabled=on&memory=2048", MODPACK_ID_MAP.get(combinedVersion), buildVersion, minecraftVersion, DUMMY_BUILD_ID_MAP.get(combinedVersion)).get("build_id").getAsString();
				updateModInBuild(buildId, DUMMY_MOD_MAP.get("mtr-" + combinedVersion), combinedVersion + "-" + mtrVersion, loader.loader, minecraftVersion);
				updateModInBuild(buildId, DUMMY_MOD_MAP.get("mtr-london-underground-addon-" + combinedVersion), combinedVersion + "-" + luVersion, loader.loader, minecraftVersion);

				if (loader == Loader.FABRIC) {
					updateModInBuild(buildId, DUMMY_MOD_MAP.get("fabric-loader-" + minecraftVersion), NEW_MOD_MAP.get("fabric-loader-" + minecraftVersion), loader.loader, minecraftVersion);
					updateModInBuild(buildId, DUMMY_MOD_MAP.get("fabric-api-" + minecraftVersion), NEW_MOD_MAP.get("fabric-api-" + minecraftVersion), loader.loader, minecraftVersion);
					updateModInBuild(buildId, DUMMY_MOD_MAP.get("modmenu-" + minecraftVersion), NEW_MOD_MAP.get("modmenu-" + minecraftVersion), loader.loader, minecraftVersion);
				} else {
					updateModInBuild(buildId, DUMMY_MOD_MAP.get("forge-loader-" + minecraftVersion), NEW_MOD_MAP.get("forge-loader-" + minecraftVersion), loader.loader, minecraftVersion);
					updateModInBuild(buildId, DUMMY_MOD_MAP.get("forge-architectury-" + minecraftVersion), NEW_MOD_MAP.get("forge-architectury-" + minecraftVersion), loader.loader, minecraftVersion);
				}
			}
		}
	}

	private void uploadZip(String url, String minecraftVersion, String modId, String zipPath, String modVersion) {
		if (!MOD_ID_MAP.containsKey(modId)) {
			return;
		}

		NEW_MOD_MAP.put(modId + "-" + minecraftVersion, modVersion);

		try {
			Files.createDirectories(OUTPUT_PATH.resolve(modId));
			final InputStream inputStream = new URL(url).openStream();
			final Path outputZipPath = OUTPUT_PATH.resolve(modId).resolve(modId + "-" + modVersion + ".zip");
			final OutputStream outputStream = Files.newOutputStream(outputZipPath);
			final ZipOutputStream zipOutputStream = new ZipOutputStream(outputStream);
			zipOutputStream.putNextEntry(new ZipEntry(zipPath));
			ByteStreams.copy(inputStream, zipOutputStream);
			zipOutputStream.closeEntry();
			zipOutputStream.close();
			outputStream.close();
			inputStream.close();

			final String serverMd5 = rehash(modId, modVersion);
			final InputStream zipInputStream = Files.newInputStream(outputZipPath);
			final String newMd5 = DigestUtils.md5Hex(zipInputStream);
			zipInputStream.close();

			if (serverMd5 == null || !serverMd5.equalsIgnoreCase(newMd5)) {
				printStatus("Uploading to SFTP:", modId, modVersion, newMd5);
				sftpClient.put(outputZipPath.toString(), sftpPath + "/mods/" + modId);

				final JsonObject response = sendRequest("add-version?mod-id=%s&add-version=%s", MOD_ID_MAP.get(modId), modVersion);
				if (response.has("status")) {
					final String status = response.get("status").getAsString();
					if (status.equals("success")) {
						printStatus(String.format("Updating Solder %s:", status), modId, modVersion, "");
					}
				}

				rehash(modId, modVersion);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private String rehash(String modId, String modVersion) {
		final JsonObject response = sendRequest("update-hash?mod-id=%s&update-hash=%s", MOD_ID_MAP.get(modId), modVersion);
		if (response.has("status")) {
			final String md5 = response.has("md5") ? response.get("md5").getAsString() : null;
			printStatus(String.format("Rehashing %s:", response.get("status").getAsString()), modId, modVersion, md5 == null ? "" : md5);
			return md5;
		} else {
			return null;
		}
	}

	private void updateModInBuild(String buildId, String oldModVersion, String newModVersion, String loaderVersion, String minecraftVersion) {
		try {
			Thread.sleep(2000);
		} catch (Exception e) {
			e.printStackTrace();
		}
		final JsonObject response = sendRequest("update-build?build_id=%s&modversion_id=%s&version=%s", buildId, oldModVersion, newModVersion);
		if (response.has("status")) {
			printStatus(String.format("Updated mod %s:", response.get("status").getAsString()), loaderVersion, minecraftVersion, newModVersion);
		}
	}

	private JsonObject sendRequest(String url, String... arguments) {
		try {
			final Object[] parameters = new Object[arguments.length];
			for (int i = 0; i < arguments.length; i++) {
				parameters[i] = URLEncoder.encode(arguments[i], "UTF-8");
			}
			final HttpURLConnection http = (HttpURLConnection) new URL(String.format("https://minecrafttransitrailway.com/api/mtr/" + url, parameters)).openConnection();
			http.setRequestMethod("POST");
			http.setDoOutput(true);
			http.setRequestProperty("Authorization", "Bearer " + apiToken);
			return new JsonParser().parse(IOUtils.toString(http.getInputStream(), StandardCharsets.UTF_8)).getAsJsonObject();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return new JsonObject();
	}

	private void uploadModrinthMod(Loader loader, String projectId, String modId) {
		try {
			final Set<String> minecraftVersions = new HashSet<>();
			Collections.addAll(minecraftVersions, MINECRAFT_VERSIONS);
			final JsonArray versionsArray = readUrl("https://api.modrinth.com/v2/project/" + projectId + "/version", new JsonArray()).getAsJsonArray();
			for (final JsonElement jsonElement : versionsArray) {
				final JsonObject versionObject = jsonElement.getAsJsonObject();
				if (stringJsonArrayContains(versionObject.getAsJsonArray("loaders"), loader.loader)) {
					final Set<String> minecraftVersionsToRemove = new HashSet<>();
					for (final String minecraftVersion : minecraftVersions) {
						if (stringJsonArrayContains(versionObject.getAsJsonArray("game_versions"), minecraftVersion)) {
							final JsonObject fileObject = versionObject.getAsJsonArray("files").get(0).getAsJsonObject();
							uploadZip(fileObject.get("url").getAsString(), minecraftVersion, modId, "mods/" + fileObject.get("filename").getAsString(), appendMinecraftVersion(versionObject.get("version_number").getAsString(), minecraftVersion));
							minecraftVersionsToRemove.add(minecraftVersion);
						}
					}
					minecraftVersionsToRemove.forEach(minecraftVersions::remove);
					if (minecraftVersions.isEmpty()) {
						return;
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private static <T extends JsonElement> JsonElement readUrl(String url, T defaultValue) {
		try (InputStream inputStream = new URL(url).openStream()) {
			return new JsonParser().parse(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return defaultValue;
	}

	private static boolean stringJsonArrayContains(JsonArray jsonArray, String text) {
		for (final JsonElement jsonElement : jsonArray) {
			if (jsonElement.getAsString().equals(text)) {
				return true;
			}
		}
		return false;
	}

	private static String appendMinecraftVersion(String text, String minecraftVersion) {
		final String[] minecraftVersionSplit = minecraftVersion.split("\\.");
		final int size = Math.min(minecraftVersionSplit.length, 2);
		final StringBuilder stringBuilder = new StringBuilder();
		for (int i = 0; i < size; i++) {
			stringBuilder.append(minecraftVersionSplit[i]);
			if (i < size - 1) {
				stringBuilder.append(".");
			}
		}
		if (text.contains(stringBuilder)) {
			return text;
		} else {
			return text + "-" + minecraftVersion;
		}
	}

	private static void printStatus(String message, String modId, String modVersion, String md5) {
		System.out.printf("%-30s %-60s%s\n", message, String.format("%s-%s", modId, modVersion), md5);
	}

	private enum Loader {
		FABRIC("fabric"), FORGE("forge");

		private final String loader;

		Loader(String loader) {
			this.loader = loader;
		}
	}
}


text:
package mdb.com.view.moviedetails.reviews;

import android.database.Cursor;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import butterknife.Bind;
import butterknife.ButterKnife;
import mdb.com.R;
import mdb.com.data.api.entity.MovieReviewEntity;
import mdb.com.view.moviesgrid.util.CursorRecyclerViewAdapter;

/**
 * @author james on 8/21/17.
 */

public class MovieReviewsAdapter extends CursorRecyclerViewAdapter<MovieReviewsAdapter.ReviewViewHolder> {

    private UpdateReviewsView updateReviewsView;

    public MovieReviewsAdapter(Cursor cursor, UpdateReviewsView updateReviewsView) {
        super(cursor);
        this.updateReviewsView = updateReviewsView;
    }

    @Override
    public ReviewViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_movie_review, parent, false);
        return new ReviewViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(ReviewViewHolder viewHolder, Cursor cursor) {
        MovieReviewEntity reviewEntity = MovieReviewEntity.fromCursor(cursor);
        viewHolder.reviewTitle.setText(reviewEntity.getAuthor());
        viewHolder.description.setText(reviewEntity.getContent());

    }

    @Override
    public void onEmptyCursor() {
        updateReviewsView.updateReviewsViewForEmptyData();
    }

    class ReviewViewHolder extends RecyclerView.ViewHolder {

        @Bind(R.id.review_title)
        TextView reviewTitle;
        @Bind(R.id.review_description)
        TextView description;

        public ReviewViewHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }
    }

    public interface UpdateReviewsView {
        void updateReviewsViewForEmptyData();
    }
}


text:
package com.trsvax.facebook.components;

import java.io.StringWriter;

import org.apache.tapestry5.ComponentResources;
import org.apache.tapestry5.MarkupWriter;
import org.apache.tapestry5.annotations.AfterRender;
import org.apache.tapestry5.annotations.BeginRender;
import org.apache.tapestry5.annotations.Environmental;
import org.apache.tapestry5.annotations.Parameter;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.services.javascript.JavaScriptSupport;

import com.trsvax.facebook.services.FBAsyncSupport;

public class NewsFeed {

	@Parameter
	private String name;
	@Parameter
	private String link;
	@Parameter
	private String picture;
	@Parameter
	private String caption;
	@Parameter
	private String description;
	@Parameter
	private String message;

	@Environmental
	private FBAsyncSupport fbAsyncSupport;

	@Environmental
	private JavaScriptSupport javaScriptSupport;

	@Inject
	private ComponentResources resources;

	@BeginRender
	void beginRender(MarkupWriter writer) {
		String id = javaScriptSupport.allocateClientId(resources);
		writer.element("a","id",id,"href","#");
		javaScriptSupport.addScript("", "");
		fbAsyncSupport.init(init(id));
	}

	@AfterRender
	void afterRender(MarkupWriter writer) {
		writer.end();
	}

	String init(String id) {

		StringWriter init = new StringWriter();

		init.append(String.format(
				"Event.observe( document.getElementById('%s'), 'click',", id));
		init.append("function(event){");
		init.append("FB.ui(");
		init.append("{");
		init.append("method: 'feed',");
		if ( name != null ) {
		init.append(String.format("name: '%s',",name));
		}
		if ( link != null ) {
			init.append(String.format("link: '%s',",link));
		}
		if ( picture != null ) {
			init.append(String.format("picture: '%s',",picture));
		}
		if ( caption != null ) {
			init.append(String.format("caption: '%s',",caption));
		}
		if ( description != null ) {
			init.append(String.format("description: '%s',",description));
		}
		if ( message != null ) {
			init.append(String.format("message: '%s'",message));
		}
		init.append("},");
		init.append("function(response) {");

		init.append(" }");

		init.append(");");
		init.append("}");
		init.append(");\n");
		return init.toString();
	}
}


text:
import {Component, OnInit} from '@angular/core';
import {UserService} from "../user/user.service";
import {LanguageService} from "../language/language.service";
import {TranslationsService} from "../translations/translations.service";

@Component({
  selector: 'user-language-and-translation',
  templateUrl: './user-language-and-translation.component.html',
  styleUrls: ['./user-language-and-translation.component.css']
})
export class UserLanguageAndTranslationComponent {

  constructor(public userService: UserService,
              public languageService: LanguageService,
              public translationService: TranslationsService) {
  }

}


text:
#ifndef NEK_ALLOCATOR_HPP
#define NEK_ALLOCATOR_HPP

#include <nek/allocator/allocator.hpp>
#include <nek/allocator/allocator_traits.hpp>

#endif


text:
/** @file
 *	@brief iDibCache class implementation
 */
/** @addtogroup iolib_xe
 *  @{
 */
#ifndef _IOLIB_XENON_DIB_CHACHE_H_
#define _IOLIB_XENON_DIB_CHACHE_H_

#include "xe.dib.h"
#include "../he/he.tables.h"
#include "../he/he.container.cache.h"

/// Key-Value pair class template for iDibCache
template <class iKEY>
struct iDibCacheKV {
	/// Constructs iDibCacheKV with given key and dib
	iDibCacheKV(const iKEY& _key, const iDib& _dib)
	: key(_key)
	, dib(_dib)
	{}

	iKEY	key;
	iDib	dib;

	struct Hasher {
		typedef iKEY KeyType;
		const iKEY& operator()( iDibCacheKV* p ) const
		{ return p->key; }
		const uint32 operator()( const iKEY& k ) const
		{ return iTables::HashFn( k ); }
	};
};

/// Dib cache class template
template <class iKEY>
class iDibCache : private iCache<iDibCacheKV<iKEY>, typename iDibCacheKV<iKEY>::Hasher >
{
public:
	/// Default constructor
	iDibCache(uint32 sizLimit = 0)
	: iCache<iDibCacheKV<iKEY>,iDibCacheKV<iKEY>::Hasher>(sizLimit)
	{ }

	/// Destructor
	~iDibCache()
	{ }

	/// Adds dib to the cache and returns its key
	void AddDib(const iDib& dib, const iKEY& key)
	{
		iDibCacheKV<iKEY> *pkv = new iDibCacheKV<iKEY>(key,dib);
		AddElement(pkv);
	}

	/// Returns constant pointer to the specified element
	const iDib* GetDibPtr(const iKEY& key) const
	{
		iDibCacheKV<iKEY>* pEl = GetElement(key);
		if (pEl) return &pEl->dib;
		return NULL;
	}

	/// Returns pointer to the specified element
	iDib* GetDibPtr(const iKEY& key)
	{
		iDibCacheKV<iKEY>* pEl = GetElement(key);
		if (pEl) return &pEl->dib;
		return NULL;
	}

	/// Returns ammount of elements in cache
	uint32 GetDibsCount() const
	{
		return GetElementsCount();
	}

};

/// Define iDibCache with integer-based keys
typedef iDibCache<uint32>	iDibCacheU32;

/// Define iDibCache with string-based keys
typedef iDibCache<iStringT>	iDibCacheStr;

#endif //_IOLIB_XENON_DIB_CHACHE_H_
/** @} */ // iolib_xe


text:
"""Compare two HTML documents."""

import re
from html.parser import HTMLParser

# ASCII whitespace is U+0009 TAB, U+000A LF, U+000C FF, U+000D CR, or U+0020
# SPACE.
# https://infra.spec.whatwg.org/#ascii-whitespace
ASCII_WHITESPACE = re.compile(r'[\t\n\f\r ]+')

def normalize_whitespace(string):
    return ASCII_WHITESPACE.sub(' ', string)

class Element:
    def __init__(self, name, attributes):
        self.name = name
        self.attributes = sorted(attributes)
        self.children = []

    def append(self, element):
        if isinstance(element, str):
            element = normalize_whitespace(element)
            if self.children:
                if isinstance(self.children[-1], str):
                    self.children[-1] += element
                    self.children[-1] = normalize_whitespace(self.children[-1])
                    return
        elif self.children:
            # removing last children if it is only whitespace
            # this can result in incorrect dom representations since
            # whitespace between inline tags like <span> is significant
            if isinstance(self.children[-1], str):
                if self.children[-1].isspace():
                    self.children.pop()
        if element:
            self.children.append(element)

    def finalize(self):
        def rstrip_last_element(children):
            if children:
                if isinstance(children[-1], str):
                    children[-1] = children[-1].rstrip()
                    if not children[-1]:
                        children.pop()
                        children = rstrip_last_element(children)
            return children

        rstrip_last_element(self.children)
        for i, child in enumerate(self.children):
            if isinstance(child, str):
                self.children[i] = child.strip()
            elif hasattr(child, 'finalize'):
                child.finalize()

    def __eq__(self, element):
        if not hasattr(element, 'name') or self.name != element.name:
            return False
        if len(self.attributes) != len(element.attributes):
            return False
        if self.attributes != element.attributes:
            # attributes without a value is same as attribute with value that
            # equals the attributes name:
            # <input checked> == <input checked="checked">
            for i in range(len(self.attributes)):
                attr, value = self.attributes[i]
                other_attr, other_value = element.attributes[i]
                if value is None:
                    value = attr
                if other_value is None:
                    other_value = other_attr
                if attr != other_attr or value != other_value:
                    return False
        return self.children == element.children

    def __hash__(self):
        return hash((self.name, *self.attributes))

    def _count(self, element, count=True):
        if not isinstance(element, str):
            if self == element:
                return 1
        if isinstance(element, RootElement):
            if self.children == element.children:
                return 1
        i = 0
        for child in self.children:
            # child is text content and element is also text content, then
            # make a simple "text" in "text"
            if isinstance(child, str):
                if isinstance(element, str):
                    if count:
                        i += child.count(element)
                    elif element in child:
                        return 1
            else:
                i += child._count(element, count=count)
                if not count and i:
                    return i
        return i

    def __contains__(self, element):
        return self._count(element, count=False) > 0

    def count(self, element):
        return self._count(element, count=True)

    def __getitem__(self, key):
        return self.children[key]

    def __str__(self):
        output = '<%s' % self.name
        for key, value in self.attributes:
            if value:
                output += ' %s="%s"' % (key, value)
            else:
                output += ' %s' % key
        if self.children:
            output += '>\n'
            output += ''.join(str(c) for c in self.children)
            output += '\n</%s>' % self.name
        else:
            output += '>'
        return output

    def __repr__(self):
        return str(self)

class RootElement(Element):
    def __init__(self):
        super().__init__(None, ())

    def __str__(self):
        return ''.join(str(c) for c in self.children)

class HTMLParseError(Exception):
    pass

class Parser(HTMLParser):
    # https://html.spec.whatwg.org/#void-elements
    SELF_CLOSING_TAGS = {
        'area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input', 'link', 'meta',
        'param', 'source', 'track', 'wbr',
        # Deprecated tags
        'frame', 'spacer',
    }

    def __init__(self):
        super().__init__()
        self.root = RootElement()
        self.open_tags = []
        self.element_positions = {}

    def error(self, msg):
        raise HTMLParseError(msg, self.getpos())

    def format_position(self, position=None, element=None):
        if not position and element:
            position = self.element_positions[element]
        if position is None:
            position = self.getpos()
        if hasattr(position, 'lineno'):
            position = position.lineno, position.offset
        return 'Line %d, Column %d' % position

    @property
    def current(self):
        if self.open_tags:
            return self.open_tags[-1]
        else:
            return self.root

    def handle_startendtag(self, tag, attrs):
        self.handle_starttag(tag, attrs)
        if tag not in self.SELF_CLOSING_TAGS:
            self.handle_endtag(tag)

    def handle_starttag(self, tag, attrs):
        # Special case handling of 'class' attribute, so that comparisons of DOM
        # instances are not sensitive to ordering of classes.
        attrs = [
            (name, ' '.join(sorted(value for value in ASCII_WHITESPACE.split(value) if value)))
            if name == "class"
            else (name, value)
            for name, value in attrs
        ]
        element = Element(tag, attrs)
        self.current.append(element)
        if tag not in self.SELF_CLOSING_TAGS:
            self.open_tags.append(element)
        self.element_positions[element] = self.getpos()

    def handle_endtag(self, tag):
        if not self.open_tags:
            self.error("Unexpected end tag `%s` (%s)" % (
                tag, self.format_position()))
        element = self.open_tags.pop()
        while element.name != tag:
            if not self.open_tags:
                self.error("Unexpected end tag `%s` (%s)" % (
                    tag, self.format_position()))
            element = self.open_tags.pop()

    def handle_data(self, data):
        self.current.append(data)

def parse_html(html):
    """
    Take a string that contains *valid* HTML and turn it into a Python object
    structure that can be easily compared against other HTML on semantic
    equivalence. Syntactical differences like which quotation is used on
    arguments will be ignored.
    """
    parser = Parser()
    parser.feed(html)
    parser.close()
    document = parser.root
    document.finalize()
    # Removing ROOT element if it's not necessary
    if len(document.children) == 1:
        if not isinstance(document.children[0], str):
            document = document.children[0]
    return document


text:
"use strict";

(function (root, factory) {
  if (typeof define === 'function' && define.amd) {
    // AMD. Register as an anonymous module.
    define([], factory);
  } else {
    // Browser globals
    var lib = factory.call(root);
    Object.keys(lib).forEach(function(key) {
      root[key] = lib[key];
    });
  }
}(this, function () {

  var topWindow = this;

  /** @module webgl-utils */

  /**
   * Wrapped logging function.
   * @param {string} msg The message to log.
   */
  function error(msg) {
    if (topWindow.console) {
      if (topWindow.console.error) {
        topWindow.console.error(msg);
      } else if (topWindow.console.log) {
        topWindow.console.log(msg);
      }
    }
  }

  /**
   * Check if the page is embedded.
   * @param {Window?) w window to check
   * @return {boolean} True of we are in an iframe
   */
  function isInIFrame(w) {
    w = w || topWindow;
    return w !== w.top;
  }

  /**
   * Creates the HTLM for a failure message
   * @param {string} canvasContainerId id of container of th
   *        canvas.
   * @return {string} The html.
   */
  function makeFailHTML(msg) {
    return '' +
      '

' +
      '' +
      '
' +
      '
' + msg + '
' +
      '
' +
      '

';
  }

  /**
   * Mesasge for getting a webgl browser
   * @type {string}
   */
  var GET_A_WEBGL_BROWSER = '' +
    'This page requires a browser that supports WebGL.
' +
    'Click here to upgrade your browser.';

  /**
   * Mesasge for need better hardware
   * @type {string}
   */
  var OTHER_PROBLEM = '' +
    "It doesn't appear your computer can support WebGL.
" +
    'Click here for more information.';

  /**
   * Creates a webgl context.
   * @param {HTMLCanvasElement} canvas The canvas tag to get
   *     context from. If one is not passed in one will be
   *     created.
   * @return {WebGLRenderingContext} The created context.
   */
  function create3DContext(canvas, opt_attribs) {
    var names = ["webgl", "experimental-webgl"];
    var context = null;
    for (var ii = 0; ii < names.length; ++ii) {
      try {
        context = canvas.getContext(names[ii], opt_attribs);
      } catch(e) {}  // eslint-disable-line
      if (context) {
        break;
      }
    }
    return context;
  }

  /**
   * Creates a webgl context. If creation fails it will
   * change the contents of the container of the <canvas>
   * tag to an error message with the correct links for WebGL.
   * @param {HTMLCanvasElement} canvas. The canvas element to
   *     create a context from.
   * @param {WebGLContextCreationAttirbutes} opt_attribs Any
   *     creation attributes you want to pass in.
   * @return {WebGLRenderingContext} The created context.
   * @memberOf module:webgl-utils
   */
  function setupWebGL(canvas, opt_attribs) {
    function showLink(str) {
      var container = canvas.parentNode;
      if (container) {
        container.innerHTML = makeFailHTML(str);
      }
    }

    if (!topWindow.WebGLRenderingContext) {
      showLink(GET_A_WEBGL_BROWSER);
      return null;
    }

    var context = create3DContext(canvas, opt_attribs);
    if (!context) {
      showLink(OTHER_PROBLEM);
    }
    return context;
  }

  function updateCSSIfInIFrame() {
    if (isInIFrame()) {
      document.body.className = "iframe";
    }
  }

  /**
   * @typedef {Object} GetWebGLContextOptions
   * @property {boolean} [dontResize] by default `getWebGLContext` will resize the canvas to match the size it's displayed.
   * @property {boolean} [noTitle] by default inserts a copy of the `<title>` content into the page
   * @memberOf module:webgl-utils
   */

  /**
   * Gets a WebGL context.
   * makes its backing store the size it is displayed.
   * @param {HTMLCanvasElement} canvas a canvas element.
   * @param {WebGLContextCreationAttirbutes} [opt_attribs] optional webgl context creation attributes
   * @param {module:webgl-utils.GetWebGLContextOptions} [opt_options] options
   * @memberOf module:webgl-utils
   */
  function getWebGLContext(canvas, opt_attribs, opt_options) {
    var options = opt_options || {};

    if (isInIFrame()) {
      updateCSSIfInIFrame();

      // make the canvas backing store the size it's displayed.
      if (!options.dontResize && options.resize !== false) {
        var width = canvas.clientWidth;
        var height = canvas.clientHeight;
        canvas.width = width;
        canvas.height = height;
      }
    } else if (!options.noTitle && options.title !== false) {
      var title = document.title;
      var h1 = document.createElement("h1");
      h1.innerText = title;
      document.body.insertBefore(h1, document.body.children[0]);
    }

    var gl = setupWebGL(canvas, opt_attribs);
    return gl;
  }

  /**
   * Error Callback
   * @callback ErrorCallback
   * @param {string} msg error message.
   * @memberOf module:webgl-utils
   */

  /**
   * Loads a shader.
   * @param {WebGLRenderingContext} gl The WebGLRenderingContext to use.
   * @param {string} shaderSource The shader source.
   * @param {number} shaderType The type of shader.
   * @param {module:webgl-utils.ErrorCallback} opt_errorCallback callback for errors.
   * @return {WebGLShader} The created shader.
   */
  function loadShader(gl, shaderSource, shaderType, opt_errorCallback) {
    var errFn = opt_errorCallback || error;
    // Create the shader object
    var shader = gl.createShader(shaderType);

    // Load the shader source
    gl.shaderSource(shader, shaderSource);

    // Compile the shader
    gl.compileShader(shader);

    // Check the compile status
    var compiled = gl.getShaderParameter(shader, gl.COMPILE_STATUS);
    if (!compiled) {
      // Something went wrong during compilation; get the error
      var lastError = gl.getShaderInfoLog(shader);
      errFn("*** Error compiling shader '" + shader + "':" + lastError);
      gl.deleteShader(shader);
      return null;
    }

    return shader;
  }

  /**
   * Creates a program, attaches shaders, binds attrib locations, links the
   * program and calls useProgram.
   * @param {WebGLShader[]} shaders The shaders to attach
   * @param {string[]} [opt_attribs] An array of attribs names. Locations will be assigned by index if not passed in
   * @param {number[]} [opt_locations] The locations for the. A parallel array to opt_attribs letting you assign locations.
   * @param {module:webgl-utils.ErrorCallback} opt_errorCallback callback for errors. By default it just prints an error to the console
   *        on error. If you want something else pass an callback. It's passed an error message.
   * @memberOf module:webgl-utils
   */
  function createProgram(
      gl, shaders, opt_attribs, opt_locations, opt_errorCallback) {
    var errFn = opt_errorCallback || error;
    var program = gl.createProgram();
    shaders.forEach(function(shader) {
      gl.attachShader(program, shader);
    });
    if (opt_attribs) {
      obj_attrib.forEach(function(attrib, ndx) {
        gl.bindAttribLocation(
            program,
            opt_locations ? opt_locations[ndx] : ndx,
            attrib);
      });
    }
    gl.linkProgram(program);

    // Check the link status
    var linked = gl.getProgramParameter(program, gl.LINK_STATUS);
    if (!linked) {
        // something went wrong with the link
        var lastError = gl.getProgramInfoLog(program);
        errFn("Error in program linking:" + lastError);

        gl.deleteProgram(program);
        return null;
    }
    return program;
  }

  /**
   * Loads a shader from a script tag.
   * @param {WebGLRenderingContext} gl The WebGLRenderingContext to use.
   * @param {string} scriptId The id of the script tag.
   * @param {number} opt_shaderType The type of shader. If not passed in it will
   *     be derived from the type of the script tag.
   * @param {module:webgl-utils.ErrorCallback} opt_errorCallback callback for errors.
   * @return {WebGLShader} The created shader.
   */
  function createShaderFromScript(
      gl, scriptId, opt_shaderType, opt_errorCallback) {
    var shaderSource = "";
    var shaderType;
    var shaderScript = document.getElementById(scriptId);
    if (!shaderScript) {
      throw ("*** Error: unknown script element" + scriptId);
    }
    shaderSource = shaderScript.text;

    if (!opt_shaderType) {
      if (shaderScript.type === "x-shader/x-vertex") {
        shaderType = gl.VERTEX_SHADER;
      } else if (shaderScript.type === "x-shader/x-fragment") {
        shaderType = gl.FRAGMENT_SHADER;
      } else if (shaderType !== gl.VERTEX_SHADER && shaderType !== gl.FRAGMENT_SHADER) {
        throw ("*** Error: unknown shader type");
      }
    }

    return loadShader(
        gl, shaderSource, opt_shaderType ? opt_shaderType : shaderType,
        opt_errorCallback);
  }

  var defaultShaderType = [
    "VERTEX_SHADER",
    "FRAGMENT_SHADER",
  ];

  /**
   * Creates a program from 2 script tags.
   *
   * @param {WebGLRenderingContext} gl The WebGLRenderingContext
   *        to use.
   * @param {string[]} shaderScriptIds Array of ids of the script
   *        tags for the shaders. The first is assumed to be the
   *        vertex shader, the second the fragment shader.
   * @param {string[]} [opt_attribs] An array of attribs names. Locations will be assigned by index if not passed in
   * @param {number[]} [opt_locations] The locations for the. A parallel array to opt_attribs letting you assign locations.
   * @param {module:webgl-utils.ErrorCallback} opt_errorCallback callback for errors. By default it just prints an error to the console
   *        on error. If you want something else pass an callback. It's passed an error message.
   * @return {WebGLProgram} The created program.
   * @memberOf module:webgl-utils
   */
  function createProgramFromScripts(
      gl, shaderScriptIds, opt_attribs, opt_locations, opt_errorCallback) {
    var shaders = [];
    for (var ii = 0; ii < shaderScriptIds.length; ++ii) {
      shaders.push(createShaderFromScript(
          gl, shaderScriptIds[ii], gl[defaultShaderType[ii]], opt_errorCallback));
    }
    return createProgram(gl, shaders, opt_attribs, opt_locations, opt_errorCallback);
  }

  /**
   * Creates a program from 2 sources.
   *
   * @param {WebGLRenderingContext} gl The WebGLRenderingContext
   *        to use.
   * @param {string[]} shaderSourcess Array of sources for the
   *        shaders. The first is assumed to be the vertex shader,
   *        the second the fragment shader.
   * @param {string[]} [opt_attribs] An array of attribs names. Locations will be assigned by index if not passed in
   * @param {number[]} [opt_locations] The locations for the. A parallel array to opt_attribs letting you assign locations.
   * @param {module:webgl-utils.ErrorCallback} opt_errorCallback callback for errors. By default it just prints an error to the console
   *        on error. If you want something else pass an callback. It's passed an error message.
   * @return {WebGLProgram} The created program.
   * @memberOf module:webgl-utils
   */
  function createProgramFromSources(
      gl, shaderSources, opt_attribs, opt_locations, opt_errorCallback) {
    var shaders = [];
    for (var ii = 0; ii < shaderSources.length; ++ii) {
      shaders.push(loadShader(
          gl, shaderSources[ii], gl[defaultShaderType[ii]], opt_errorCallback));
    }
    return createProgram(gl, shaders, opt_attribs, opt_locations, opt_errorCallback);
  }

  /**
   * Returns the corresponding bind point for a given sampler type
   */
  function getBindPointForSamplerType(gl, type) {
    if (type === gl.SAMPLER_2D)   return gl.TEXTURE_2D;        // eslint-disable-line
    if (type === gl.SAMPLER_CUBE) return gl.TEXTURE_CUBE_MAP;  // eslint-disable-line
  }

  /**
   * @typedef {Object.<string, function>} Setters
   */

  /**
   * Creates setter functions for all uniforms of a shader
   * program.
   *
   * @see {@link module:webgl-utils.setUniforms}
   *
   * @param {WebGLProgram} program the program to create setters for.
   * @returns {Object.<string, function>} an object with a setter by name for each uniform
   * @memberOf module:webgl-utils
   */
  function createUniformSetters(gl, program) {
    var textureUnit = 0;

    /**
     * Creates a setter for a uniform of the given program with it's
     * location embedded in the setter.
     * @param {WebGLProgram} program
     * @param {WebGLUniformInfo} uniformInfo
     * @returns {function} the created setter.
     */
    function createUniformSetter(program, uniformInfo) {
      var location = gl.getUniformLocation(program, uniformInfo.name);
      var type = uniformInfo.type;
      // Check if this uniform is an array
      var isArray = (uniformInfo.size > 1 && uniformInfo.name.substr(-3) === "[0]");
      if (type === gl.FLOAT && isArray) {
        return function(v) {
          gl.uniform1fv(location, v);
        };
      }
      if (type === gl.FLOAT) {
        return function(v) {
          gl.uniform1f(location, v);
        };
      }
      if (type === gl.FLOAT_VEC2) {
        return function(v) {
          gl.uniform2fv(location, v);
        };
      }
      if (type === gl.FLOAT_VEC3) {
        return function(v) {
          gl.uniform3fv(location, v);
        };
      }
      if (type === gl.FLOAT_VEC4) {
        return function(v) {
          gl.uniform4fv(location, v);
        };
      }
      if (type === gl.INT && isArray) {
        return function(v) {
          gl.uniform1iv(location, v);
        };
      }
      if (type === gl.INT) {
        return function(v) {
          gl.uniform1i(location, v);
        };
      }
      if (type === gl.INT_VEC2) {
        return function(v) {
          gl.uniform2iv(location, v);
        };
      }
      if (type === gl.INT_VEC3) {
        return function(v) {
          gl.uniform3iv(location, v);
        };
      }
      if (type === gl.INT_VEC4) {
        return function(v) {
          gl.uniform4iv(location, v);
        };
      }
      if (type === gl.BOOL) {
        return function(v) {
          gl.uniform1iv(location, v);
        };
      }
      if (type === gl.BOOL_VEC2) {
        return function(v) {
          gl.uniform2iv(location, v);
        };
      }
      if (type === gl.BOOL_VEC3) {
        return function(v) {
          gl.uniform3iv(location, v);
        };
      }
      if (type === gl.BOOL_VEC4) {
        return function(v) {
          gl.uniform4iv(location, v); }
        ;
      }
      if (type === gl.FLOAT_MAT2) {
        return function(v) {
          gl.uniformMatrix2fv(location, false, v);
        };
      }
      if (type === gl.FLOAT_MAT3) {
        return function(v) {
          gl.uniformMatrix3fv(location, false, v);
        };
      }
      if (type === gl.FLOAT_MAT4) {
        return function(v) {
          gl.uniformMatrix4fv(location, false, v);
        };
      }
      if ((type === gl.SAMPLER_2D || type === gl.SAMPLER_CUBE) && isArray) {
        var units = [];
        for (var ii = 0; ii < info.size; ++ii) {
          units.push(textureUnit++);
        }
        return function(bindPoint, units) {
          return function(textures) {
            gl.uniform1iv(location, units);
            textures.forEach(function(texture, index) {
              gl.activeTexture(gl.TEXTURE0 + units[index]);
              gl.bindTexture(bindPoint, tetxure);
            });
          };
        }(getBindPointForSamplerType(gl, type), units);
      }
      if (type === gl.SAMPLER_2D || type === gl.SAMPLER_CUBE) {
        return function(bindPoint, unit) {
          return function(texture) {
            gl.uniform1i(location, unit);
            gl.activeTexture(gl.TEXTURE0 + unit);
            gl.bindTexture(bindPoint, texture);
          };
        }(getBindPointForSamplerType(gl, type), textureUnit++);
      }
      throw ("unknown type: 0x" + type.toString(16)); // we should never get here.
    }

    var uniformSetters = { };
    var numUniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS);

    for (var ii = 0; ii < numUniforms; ++ii) {
      var uniformInfo = gl.getActiveUniform(program, ii);
      if (!uniformInfo) {
        break;
      }
      var name = uniformInfo.name;
      // remove the array suffix.
      if (name.substr(-3) === "[0]") {
        name = name.substr(0, name.length - 3);
      }
      var setter = createUniformSetter(program, uniformInfo);
      uniformSetters[name] = setter;
    }
    return uniformSetters;
  }

  /**
   * Set uniforms and binds related textures.
   *
   * example:
   *
   *     var programInfo = createProgramInfo(
   *         gl, ["some-vs", "some-fs");
   *
   *     var tex1 = gl.createTexture();
   *     var tex2 = gl.createTexture();
   *
   *     ... assume we setup the textures with data ...
   *
   *     var uniforms = {
   *       u_someSampler: tex1,
   *       u_someOtherSampler: tex2,
   *       u_someColor: [1,0,0,1],
   *       u_somePosition: [0,1,1],
   *       u_someMatrix: [
   *         1,0,0,0,
   *         0,1,0,0,
   *         0,0,1,0,
   *         0,0,0,0,
   *       ],
   *     };
   *
   *     gl.useProgram(program);
   *
   * This will automatically bind the textures AND set the
   * uniforms.
   *
   *     setUniforms(programInfo.uniformSetters, uniforms);
   *
   * For the example above it is equivalent to
   *
   *     var texUnit = 0;
   *     gl.activeTexture(gl.TEXTURE0 + texUnit);
   *     gl.bindTexture(gl.TEXTURE_2D, tex1);
   *     gl.uniform1i(u_someSamplerLocation, texUnit++);
   *     gl.activeTexture(gl.TEXTURE0 + texUnit);
   *     gl.bindTexture(gl.TEXTURE_2D, tex2);
   *     gl.uniform1i(u_someSamplerLocation, texUnit++);
   *     gl.uniform4fv(u_someColorLocation, [1, 0, 0, 1]);
   *     gl.uniform3fv(u_somePositionLocation, [0, 1, 1]);
   *     gl.uniformMatrix4fv(u_someMatrix, false, [
   *         1,0,0,0,
   *         0,1,0,0,
   *         0,0,1,0,
   *         0,0,0,0,
   *       ]);
   *
   * Note it is perfectly reasonable to call `setUniforms` multiple times. For example
   *
   *     var uniforms = {
   *       u_someSampler: tex1,
   *       u_someOtherSampler: tex2,
   *     };
   *
   *     var moreUniforms {
   *       u_someColor: [1,0,0,1],
   *       u_somePosition: [0,1,1],
   *       u_someMatrix: [
   *         1,0,0,0,
   *         0,1,0,0,
   *         0,0,1,0,
   *         0,0,0,0,
   *       ],
   *     };
   *
   *     setUniforms(programInfo.uniformSetters, uniforms);
   *     setUniforms(programInfo.uniformSetters, moreUniforms);
   *
   * @param {Object.<string, function>} setters the setters returned from
   *        `createUniformSetters`.
   * @param {Object.<string, value>} an object with values for the
   *        uniforms.
   * @memberOf module:webgl-utils
   */
  function setUniforms(setters, values) {
    Object.keys(values).forEach(function(name) {
      var setter = setters[name];
      if (setter) {
        setter(values[name]);
      }
    });
  }

  /**
   * Creates setter functions for all attributes of a shader
   * program. You can pass this to {@link module:webgl-utils.setBuffersAndAttributes} to set all your buffers and attributes.
   *
   * @see {@link module:webgl-utils.setAttributes} for example
   * @param {WebGLProgram} program the program to create setters for.
   * @return {Object.<string, function>} an object with a setter for each attribute by name.
   * @memberOf module:webgl-utils
   */
  function createAttributeSetters(gl, program) {
    var attribSetters = {
    };

    function createAttribSetter(index) {
      return function(b) {
          gl.bindBuffer(gl.ARRAY_BUFFER, b.buffer);
          gl.enableVertexAttribArray(index);
          gl.vertexAttribPointer(
              index, b.numComponents || b.size, b.type || gl.FLOAT, b.normalize || false, b.stride || 0, b.offset || 0);
        };
    }

    var numAttribs = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES);
    for (var ii = 0; ii < numAttribs; ++ii) {
      var attribInfo = gl.getActiveAttrib(program, ii);
      if (!attribInfo) {
        break;
      }
      var index = gl.getAttribLocation(program, attribInfo.name);
      attribSetters[attribInfo.name] = createAttribSetter(index);
    }

    return attribSetters;
  }

  /**
   * Sets attributes and binds buffers (deprecated... use {@link module:webgl-utils.setBuffersAndAttributes})
   *
   * Example:
   *
   *     var program = createProgramFromScripts(
   *         gl, ["some-vs", "some-fs");
   *
   *     var attribSetters = createAttributeSetters(program);
   *
   *     var positionBuffer = gl.createBuffer();
   *     var texcoordBuffer = gl.createBuffer();
   *
   *     var attribs = {
   *       a_position: {buffer: positionBuffer, numComponents: 3},
   *       a_texcoord: {buffer: texcoordBuffer, numComponents: 2},
   *     };
   *
   *     gl.useProgram(program);
   *
   * This will automatically bind the buffers AND set the
   * attributes.
   *
   *     setAttributes(attribSetters, attribs);
   *
   * Properties of attribs. For each attrib you can add
   * properties:
   *
   * *   type: the type of data in the buffer. Default = gl.FLOAT
   * *   normalize: whether or not to normalize the data. Default = false
   * *   stride: the stride. Default = 0
   * *   offset: offset into the buffer. Default = 0
   *
   * For example if you had 3 value float positions, 2 value
   * float texcoord and 4 value uint8 colors you'd setup your
   * attribs like this
   *
   *     var attribs = {
   *       a_position: {buffer: positionBuffer, numComponents: 3},
   *       a_texcoord: {buffer: texcoordBuffer, numComponents: 2},
   *       a_color: {
   *         buffer: colorBuffer,
   *         numComponents: 4,
   *         type: gl.UNSIGNED_BYTE,
   *         normalize: true,
   *       },
   *     };
   *
   * @param {Object.<string, function>} setters Attribute setters as returned from createAttributeSetters
   * @param {Object.<string, module:webgl-utils.AttribInfo>} buffers AttribInfos mapped by attribute name.
   * @memberOf module:webgl-utils
   * @deprecated use {@link module:webgl-utils.setBuffersAndAttributes}
   */
  function setAttributes(setters, buffers) {
    Object.keys(buffers).forEach(function(name) {
      var setter = setters[name];
      if (setter) {
        setter(buffers[name]);
      }
    });
  }

  /**
   * @typedef {Object} ProgramInfo
   * @property {WebGLProgram} program A shader program
   * @property {Object<string, function>} uniformSetters: object of setters as returned from createUniformSetters,
   * @property {Object<string, function>} attribSetters: object of setters as returned from createAttribSetters,
   * @memberOf module:webgl-utils
   */

  /**
   * Creates a ProgramInfo from 2 sources.
   *
   * A ProgramInfo contains
   *
   *     programInfo = {
   *        program: WebGLProgram,
   *        uniformSetters: object of setters as returned from createUniformSetters,
   *        attribSetters: object of setters as returned from createAttribSetters,
   *     }
   *
   * @param {WebGLRenderingContext} gl The WebGLRenderingContext
   *        to use.
   * @param {string[]} shaderSourcess Array of sources for the
   *        shaders or ids. The first is assumed to be the vertex shader,
   *        the second the fragment shader.
   * @param {string[]} [opt_attribs] An array of attribs names. Locations will be assigned by index if not passed in
   * @param {number[]} [opt_locations] The locations for the. A parallel array to opt_attribs letting you assign locations.
   * @param {module:webgl-utils.ErrorCallback} opt_errorCallback callback for errors. By default it just prints an error to the console
   *        on error. If you want something else pass an callback. It's passed an error message.
   * @return {module:webgl-utils.ProgramInfo} The created program.
   * @memberOf module:webgl-utils
   */
  function createProgramInfo(
      gl, shaderSources, opt_attribs, opt_locations, opt_errorCallback) {
    shaderSources = shaderSources.map(function(source) {
      var script = document.getElementById(source);
      return script ? script.text : source;
    });
    var program = createProgramFromSources(gl, shaderSources, opt_attribs, opt_locations, opt_errorCallback);
    if (!program) {
      return null;
    }
    var uniformSetters = createUniformSetters(gl, program);
    var attribSetters = createAttributeSetters(gl, program);
    return {
      program: program,
      uniformSetters: uniformSetters,
      attribSetters: attribSetters,
    };
  }

  /**
   * Sets attributes and buffers including the `ELEMENT_ARRAY_BUFFER` if appropriate
   *
   * Example:
   *
   *     var programInfo = createProgramInfo(
   *         gl, ["some-vs", "some-fs");
   *
   *     var arrays = {
   *       position: { numComponents: 3, data: [0, 0, 0, 10, 0, 0, 0, 10, 0, 10, 10, 0], },
   *       texcoord: { numComponents: 2, data: [0, 0, 0, 1, 1, 0, 1, 1],                 },
   *     };
   *
   *     var bufferInfo = createBufferInfoFromArrays(gl, arrays);
   *
   *     gl.useProgram(programInfo.program);
   *
   * This will automatically bind the buffers AND set the
   * attributes.
   *
   *     setBuffersAndAttributes(programInfo.attribSetters, bufferInfo);
   *
   * For the example above it is equivilent to
   *
   *     gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
   *     gl.enableVertexAttribArray(a_positionLocation);
   *     gl.vertexAttribPointer(a_positionLocation, 3, gl.FLOAT, false, 0, 0);
   *     gl.bindBuffer(gl.ARRAY_BUFFER, texcoordBuffer);
   *     gl.enableVertexAttribArray(a_texcoordLocation);
   *     gl.vertexAttribPointer(a_texcoordLocation, 4, gl.FLOAT, false, 0, 0);
   *
   * @param {WebGLRenderingContext} gl A WebGLRenderingContext.
   * @param {Object.<string, function>} setters Attribute setters as returned from `createAttributeSetters`
   * @param {module:webgl-utils.BufferInfo} buffers a BufferInfo as returned from `createBufferInfoFromArrays`.
   * @memberOf module:webgl-utils
   */
  function setBuffersAndAttributes(gl, setters, buffers) {
    setAttributes(setters, buffers.attribs);
    if (buffers.indices) {
      gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, buffers.indices);
    }
  }

  // Add your prefix here.
  var browserPrefixes = [
    "",
    "MOZ_",
    "OP_",
    "WEBKIT_",
  ];

  /**
   * Given an extension name like WEBGL_compressed_texture_s3tc
   * returns the supported version extension, like
   * WEBKIT_WEBGL_compressed_teture_s3tc
   * @param {string} name Name of extension to look for
   * @return {WebGLExtension} The extension or undefined if not
   *     found.
   * @memberOf module:webgl-utils
   */
  function getExtensionWithKnownPrefixes(gl, name) {
    for (var ii = 0; ii < browserPrefixes.length; ++ii) {
      var prefixedName = browserPrefixes[ii] + name;
      var ext = gl.getExtension(prefixedName);
      if (ext) {
        return ext;
      }
    }
  }

  /**
   * Resize a canvas to match the size its displayed.
   * @param {HTMLCanvasElement} canvas The canvas to resize.
   * @param {boolean} true if the canvas was resized.
   * @memberOf module:webgl-utils
   */
  function resizeCanvasToDisplaySize(canvas) {
    var width = canvas.clientWidth;
    var height = canvas.clientHeight;
    if (canvas.width !== width ||
        canvas.height !== height) {
      canvas.width = width;
      canvas.height = height;
      return true;
    }
    return false;
  }

  /**
   * Get's the iframe in the parent document
   * that is displaying the specified window .
   * @param {Window} window window to check.
   * @return {HTMLIFrameElement?) the iframe element if window is in an iframe
   */
  function getIFrameForWindow(window) {
    if (!isInIFrame(window)) {
      return;
    }
    var iframes = window.parent.document.getElementsByTagName("iframe");
    for (var ii = 0; ii < iframes.length; ++ii) {
      var iframe = iframes[ii];
      if (iframe.contentDocument === window.document) {
        return iframe;  // eslint-disable-line
      }
    }
  }

  /**
   * Returns true if window is on screen. The main window is
   * always on screen windows in iframes might not be.
   * @param {Window} window the window to check.
   * @return {boolean} true if window is on screen.
   */
  function isFrameVisible(window) {
    try {
      var iframe = getIFrameForWindow(window);
      if (!iframe) {
        return true;
      }

      var bounds = iframe.getBoundingClientRect();
      var isVisible = bounds.top < window.parent.innerHeight && bounds.bottom >= 0 &&
                      bounds.left < window.parent.innerWidth && bounds.right >= 0;

      return isVisible && isFrameVisible(window.parent);
    } catch (e) {
      return true;  // We got a security error?
    }
  }

  /**
   * Returns true if element is on screen.
   * @param {HTMLElement} element the element to check.
   * @return {boolean} true if element is on screen.
   */
  function isOnScreen(element) {
    var isVisible = true;

    if (element) {
      var bounds = element.getBoundingClientRect();
      isVisible = bounds.top < topWindow.innerHeight && bounds.bottom >= 0;
    }

    return isVisible && isFrameVisible(topWindow);
  }

  // Add `push` to a typed array. It just keeps a 'cursor'
  // and allows use to `push` values into the array so we
  // don't have to manually compute offsets
  function augmentTypedArray(typedArray, numComponents) {
    var cursor = 0;
    typedArray.push = function() {
      for (var ii = 0; ii < arguments.length; ++ii) {
        var value = arguments[ii];
        if (value instanceof Array || (value.buffer && value.buffer instanceof ArrayBuffer)) {
          for (var jj = 0; jj < value.length; ++jj) {
            typedArray[cursor++] = value[jj];
          }
        } else {
          typedArray[cursor++] = value;
        }
      }
    };
    typedArray.reset = function(opt_index) {
      cursor = opt_index || 0;
    };
    typedArray.numComponents = numComponents;
    Object.defineProperty(typedArray, 'numElements', {
      get: function() {
        return this.length / this.numComponents | 0;
      },
    });
    return typedArray;
  }

  /**
   * creates a typed array with a `push` function attached
   * so that you can easily *push* values.
   *
   * `push` can take multiple arguments. If an argument is an array each element
   * of the array will be added to the typed array.
   *
   * Example:
   *
   *     var array = createAugmentedTypedArray(3, 2);  // creates a Float32Array with 6 values
   *     array.push(1, 2, 3);
   *     array.push([4, 5, 6]);
   *     // array now contains [1, 2, 3, 4, 5, 6]
   *
   * Also has `numComponents` and `numElements` properties.
   *
   * @param {number} numComponents number of components
   * @param {number} numElements number of elements. The total size of the array will be `numComponents * numElements`.
   * @param {constructor} opt_type A constructor for the type. Default = `Float32Array`.
   * @return {ArrayBuffer} A typed array.
   * @memberOf module:webgl-utils
   */
  function createAugmentedTypedArray(numComponents, numElements, opt_type) {
    var Type = opt_type || Float32Array;
    return augmentTypedArray(new Type(numComponents * numElements), numComponents);
  }

  function createBufferFromTypedArray(gl, array, type, drawType) {
    type = type || gl.ARRAY_BUFFER;
    var buffer = gl.createBuffer();
    gl.bindBuffer(type, buffer);
    gl.bufferData(type, array, drawType || gl.STATIC_DRAW);
    return buffer;
  }

  function allButIndices(name) {
    return name !== "indices";
  }

  function createMapping(obj) {
    var mapping = {};
    Object.keys(obj).filter(allButIndices).forEach(function(key) {
      mapping["a_" + key] = key;
    });
    return mapping;
  }

  function getGLTypeForTypedArray(gl, typedArray) {
    if (typedArray instanceof Int8Array)    { return gl.BYTE; }            // eslint-disable-line
    if (typedArray instanceof Uint8Array)   { return gl.UNSIGNED_BYTE; }   // eslint-disable-line
    if (typedArray instanceof Int16Array)   { return gl.SHORT; }           // eslint-disable-line
    if (typedArray instanceof Uint16Array)  { return gl.UNSIGNED_SHORT; }  // eslint-disable-line
    if (typedArray instanceof Int32Array)   { return gl.INT; }             // eslint-disable-line
    if (typedArray instanceof Uint32Array)  { return gl.UNSIGNED_INT; }    // eslint-disable-line
    if (typedArray instanceof Float32Array) { return gl.FLOAT; }           // eslint-disable-line
    throw "unsupported typed array type";
  }

  // This is really just a guess. Though I can't really imagine using
  // anything else? Maybe for some compression?
  function getNormalizationForTypedArray(typedArray) {
    if (typedArray instanceof Int8Array)    { return true; }  // eslint-disable-line
    if (typedArray instanceof Uint8Array)   { return true; }  // eslint-disable-line
    return false;
  }

  function isArrayBuffer(a) {
    return a.buffer && a.buffer instanceof ArrayBuffer;
  }

  function guessNumComponentsFromName(name, length) {
    var numComponents;
    if (name.indexOf("coord") >= 0) {
      numComponents = 2;
    } else if (name.indexOf("color") >= 0) {
      numComponents = 4;
    } else {
      numComponents = 3;  // position, normals, indices ...
    }

    if (length % numComponents > 0) {
      throw "can not guess numComponents. You should specify it.";
    }

    return numComponents;
  }

  function makeTypedArray(array, name) {
    if (isArrayBuffer(array)) {
      return array;
    }

    if (Array.isArray(array)) {
      array = {
        data: array,
      };
    }

    if (!array.numComponents) {
      array.numComponents = guessNumComponentsFromName(name, array.length);
    }

    var type = array.type;
    if (!type) {
      if (name === "indices") {
        type = Uint16Array;
      }
    }
    var typedArray = createAugmentedTypedArray(array.numComponents, array.data.length / array.numComponents | 0, type);
    typedArray.push(array.data);
    return typedArray;
  }

  /**
   * @typedef {Object} AttribInfo
   * @property {number} [numComponents] the number of components for this attribute.
   * @property {number} [size] the number of components for this attribute.
   * @property {number} [type] the type of the attribute (eg. `gl.FLOAT`, `gl.UNSIGNED_BYTE`, etc...) Default = `gl.FLOAT`
   * @property {boolean} [normalized] whether or not to normalize the data. Default = false
   * @property {number} [offset] offset into buffer in bytes. Default = 0
   * @property {number} [stride] the stride in bytes per element. Default = 0
   * @property {WebGLBuffer} buffer the buffer that contains the data for this attribute
   * @memberOf module:webgl-utils
   */

  /**
   * Creates a set of attribute data and WebGLBuffers from set of arrays
   *
   * Given
   *
   *      var arrays = {
   *        position: { numComponents: 3, data: [0, 0, 0, 10, 0, 0, 0, 10, 0, 10, 10, 0], },
   *        texcoord: { numComponents: 2, data: [0, 0, 0, 1, 1, 0, 1, 1],                 },
   *        normal:   { numComponents: 3, data: [0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1],     },
   *        color:    { numComponents: 4, data: [255, 255, 255, 255, 255, 0, 0, 255, 0, 0, 255, 255], type: Uint8Array, },
   *        indices:  { numComponents: 3, data: [0, 1, 2, 1, 2, 3],                       },
   *      };
   *
   * returns something like
   *
   *      var attribs = {
   *        a_position: { numComponents: 3, type: gl.FLOAT,         normalize: false, buffer: WebGLBuffer, },
   *        a_texcoord: { numComponents: 2, type: gl.FLOAT,         normalize: false, buffer: WebGLBuffer, },
   *        a_normal:   { numComponents: 3, type: gl.FLOAT,         normalize: false, buffer: WebGLBuffer, },
   *        a_color:    { numComponents: 4, type: gl.UNSIGNED_BYTE, normalize: true,  buffer: WebGLBuffer, },
   *      };
   *
   * @param {WebGLRenderingContext} gl The webgl rendering context.
   * @param {Object.<string, array|typedarray>} arrays The arrays
   * @param {Object.<string, string>} [opt_mapping] mapping from attribute name to array name.
   *     if not specified defaults to "a_name" -> "name".
   * @return {Object.<string, module:webgl-utils.AttribInfo>} the attribs
   * @memberOf module:webgl-utils
   */
  function createAttribsFromArrays(gl, arrays, opt_mapping) {
    var mapping = opt_mapping || createMapping(arrays);
    var attribs = {};
    Object.keys(mapping).forEach(function(attribName) {
      var bufferName = mapping[attribName];
      var array = makeTypedArray(arrays[bufferName], bufferName);
      attribs[attribName] = {
        buffer:        createBufferFromTypedArray(gl, array),
        numComponents: array.numComponents || guessNumComponentsFromName(bufferName),
        type:          getGLTypeForTypedArray(gl, array),
        normalize:     getNormalizationForTypedArray(array),
      };
    });
    return attribs;
  }

  /**
   * tries to get the number of elements from a set of arrays.
   */
  function getNumElementsFromNonIndexedArrays(arrays) {
    var key = Object.keys(arrays)[0];
    var array = arrays[key];
    if (isArrayBuffer(array)) {
      return array.numElements;
    } else {
      return array.data.length / array.numComponents;
    }
  }

  /**
   * @typedef {Object} BufferInfo
   * @property {number} numElements The number of elements to pass to `gl.drawArrays` or `gl.drawElements`.
   * @property {WebGLBuffer} [indices] The indices `ELEMENT_ARRAY_BUFFER` if any indices exist.
   * @property {Object.<string, module:webgl-utils.AttribInfo>} attribs The attribs approriate to call `setAttributes`
   * @memberOf module:webgl-utils
   */

  /**
   * Creates a BufferInfo from an object of arrays.
   *
   * This can be passed to {@link module:webgl-utils.setBuffersAndAttributes} and to
   * {@link module:webgl-utils:drawBufferInfo}.
   *
   * Given an object like
   *
   *     var arrays = {
   *       position: { numComponents: 3, data: [0, 0, 0, 10, 0, 0, 0, 10, 0, 10, 10, 0], },
   *       texcoord: { numComponents: 2, data: [0, 0, 0, 1, 1, 0, 1, 1],                 },
   *       normal:   { numComponents: 3, data: [0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1],     },
   *       indices:  { numComponents: 3, data: [0, 1, 2, 1, 2, 3],                       },
   *     };
   *
   *  Creates an BufferInfo like this
   *
   *     bufferInfo = {
   *       numElements: 4,        // or whatever the number of elements is
   *       indices: WebGLBuffer,  // this property will not exist if there are no indices
   *       attribs: {
   *         a_position: { buffer: WebGLBuffer, numComponents: 3, },
   *         a_normal:   { buffer: WebGLBuffer, numComponents: 3, },
   *         a_texcoord: { buffer: WebGLBuffer, numComponents: 2, },
   *       },
   *     };
   *
   *  The properties of arrays can be JavaScript arrays in which case the number of components
   *  will be guessed.
   *
   *     var arrays = {
   *        position: [0, 0, 0, 10, 0, 0, 0, 10, 0, 10, 10, 0],
   *        texcoord: [0, 0, 0, 1, 1, 0, 1, 1],
   *        normal:   [0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1],
   *        indices:  [0, 1, 2, 1, 2, 3],
   *     };
   *
   *  They can also by TypedArrays
   *
   *     var arrays = {
   *        position: new Float32Array([0, 0, 0, 10, 0, 0, 0, 10, 0, 10, 10, 0]),
   *        texcoord: new Float32Array([0, 0, 0, 1, 1, 0, 1, 1]),
   *        normal:   new Float32Array([0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1]),
   *        indices:  new Uint16Array([0, 1, 2, 1, 2, 3]),
   *     };
   *
   *  Or augmentedTypedArrays
   *
   *     var positions = createAugmentedTypedArray(3, 4);
   *     var texcoords = createAugmentedTypedArray(2, 4);
   *     var normals   = createAugmentedTypedArray(3, 4);
   *     var indices   = createAugmentedTypedArray(3, 2, Uint16Array);
   *
   *     positions.push([0, 0, 0, 10, 0, 0, 0, 10, 0, 10, 10, 0]);
   *     texcoords.push([0, 0, 0, 1, 1, 0, 1, 1]);
   *     normals.push([0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1]);
   *     indices.push([0, 1, 2, 1, 2, 3]);
   *
   *     var arrays = {
   *        position: positions,
   *        texcoord: texcoords,
   *        normal:   normals,
   *        indices:  indices,
   *     };
   *
   * For the last example it is equivalent to
   *
   *     var bufferInfo = {
   *       attribs: {
   *         a_position: { numComponents: 3, buffer: gl.createBuffer(), },
   *         a_texcoods: { numComponents: 2, buffer: gl.createBuffer(), },
   *         a_normals: { numComponents: 3, buffer: gl.createBuffer(), },
   *       },
   *       indices: gl.createBuffer(),
   *       numElements: 6,
   *     };
   *
   *     gl.bindBuffer(gl.ARRAY_BUFFER, bufferInfo.attribs.a_position.buffer);
   *     gl.bufferData(gl.ARRAY_BUFFER, arrays.position, gl.STATIC_DRAW);
   *     gl.bindBuffer(gl.ARRAY_BUFFER, bufferInfo.attribs.a_texcoord.buffer);
   *     gl.bufferData(gl.ARRAY_BUFFER, arrays.texcoord, gl.STATIC_DRAW);
   *     gl.bindBuffer(gl.ARRAY_BUFFER, bufferInfo.attribs.a_normal.buffer);
   *     gl.bufferData(gl.ARRAY_BUFFER, arrays.normal, gl.STATIC_DRAW);
   *     gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, bufferInfo.indices);
   *     gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, arrays.indices, gl.STATIC_DRAW);
   *
   * @param {WebGLRenderingContext} gl A WebGLRenderingContext
   * @param {Object.<string, array|object|typedarray>} arrays Your data
   * @param {Object.<string, string>} [opt_mapping] an optional mapping of attribute to array name.
   *    If not passed in it's assumed the array names will be mapped to an attibute
   *    of the same name with "a_" prefixed to it. An other words.
   *
   *        var arrays = {
   *           position: ...,
   *           texcoord: ...,
   *           normal:   ...,
   *           indices:  ...,
   *        };
   *
   *        bufferInfo = createBufferInfoFromArrays(gl, arrays);
   *
   *    Is the same as
   *
   *        var arrays = {
   *           position: ...,
   *           texcoord: ...,
   *           normal:   ...,
   *           indices:  ...,
   *        };
   *
   *        var mapping = {
   *          a_position: "position",
   *          a_texcoord: "texcoord",
   *          a_normal:   "normal",
   *        };
   *
   *        bufferInfo = createBufferInfoFromArrays(gl, arrays, mapping);
   *
   * @return {module:webgl-utils.BufferInfo} A BufferInfo
   * @memberOf module:webgl-utils
   */
  function createBufferInfoFromArrays(gl, arrays, opt_mapping) {
    var bufferInfo = {
      attribs: createAttribsFromArrays(gl, arrays, opt_mapping),
    };
    var indices = arrays.indices;
    if (indices) {
      indices = makeTypedArray(indices, "indices");
      bufferInfo.indices = createBufferFromTypedArray(gl, indices, gl.ELEMENT_ARRAY_BUFFER);
      bufferInfo.numElements = indices.length;
    } else {
      bufferInfo.numElements = getNumElementsFromNonIndexedArrays(arrays);
    }

    return bufferInfo;
  }

  /**
   * Creates buffers from typed arrays
   *
   * Given something like this
   *
   *     var arrays = {
   *        positions: [1, 2, 3],
   *        normals: [0, 0, 1],
   *     }
   *
   * returns something like
   *
   *     buffers = {
   *       positions: WebGLBuffer,
   *       normals: WebGLBuffer,
   *     }
   *
   * If the buffer is named 'indices' it will be made an ELEMENT_ARRAY_BUFFER.
   *
   * @param {WebGLRenderingContext) gl A WebGLRenderingContext.
   * @param {Object<string, array|typedarray>} arrays
   * @return {Object<string, WebGLBuffer>} returns an object with one WebGLBuffer per array
   * @memberOf module:webgl-utils
   */
  function createBuffersFromArrays(gl, arrays) {
    var buffers = { };
    Object.keys(arrays).forEach(function(key) {
      var type = key === "indices" ? gl.ELEMENT_ARRAY_BUFFER : gl.ARRAY_BUFFER;
      var array = makeTypedArray(arrays[key], name);
      buffers[key] = createBufferFromTypedArray(gl, array, type);
    });

    // hrm
    if (arrays.indices) {
      buffers.numElements = arrays.indices.length;
    } else if (arrays.position) {
      buffers.numElements = arrays.position.length / 3;
    }

    return buffers;
  }

  /**
   * Calls `gl.drawElements` or `gl.drawArrays`, whichever is appropriate
   *
   * normally you'd call `gl.drawElements` or `gl.drawArrays` yourself
   * but calling this means if you switch from indexed data to non-indexed
   * data you don't have to remember to update your draw call.
   *
   * @param {WebGLRenderingContext} gl A WebGLRenderingContext
   * @param {enum} type eg (gl.TRIANGLES, gl.LINES, gl.POINTS, gl.TRIANGLE_STRIP, ...)
   * @param {module:webgl-utils.BufferInfo} bufferInfo as returned from createBufferInfoFromArrays
   * @param {number} [count] An optional count. Defaults to bufferInfo.numElements
   * @param {number} [offset] An optional offset. Defaults to 0.
   * @memberOf module:webgl-utils
   */
  function drawBufferInfo(gl, type, bufferInfo, count, offset) {
    var indices = bufferInfo.indices;
    var numElements = count === undefined ? bufferInfo.numElements : count;
    offset = offset === undefined ? offset : 0;
    if (indices) {
      gl.drawElements(type, numElements, gl.UNSIGNED_SHORT, offset);
    } else {
      gl.drawArrays(type, offset, numElements);
    }
  }

  /**
   * @typedef {Object} DrawObject
   * @property {module:webgl-utils.ProgramInfo} programInfo A ProgramInfo as returned from createProgramInfo
   * @property {module:webgl-utils.BufferInfo} bufferInfo A BufferInfo as returned from createBufferInfoFromArrays
   * @property {Object<string, ?>} uniforms The values for the uniforms
   * @memberOf module:webgl-utils
   */

  /**
   * Draws a list of objects
   * @param {WebGLRenderingContext} gl A WebGLRenderingContext
   * @param {DrawObject[]} objectsToDraw an array of objects to draw.
   * @memberOf module:webgl-utils
   */
  function drawObjectList(gl, objectsToDraw) {
    var lastUsedProgramInfo = null;
    var lastUsedBufferInfo = null;

    objectsToDraw.forEach(function(object) {
      var programInfo = object.programInfo;
      var bufferInfo = object.bufferInfo;
      var bindBuffers = false;

      if (programInfo !== lastUsedProgramInfo) {
        lastUsedProgramInfo = programInfo;
        gl.useProgram(programInfo.program);
        bindBuffers = true;
      }

      // Setup all the needed attributes.
      if (bindBuffers || bufferInfo !== lastUsedBufferInfo) {
        lastUsedBufferInfo = bufferInfo;
        setBuffersAndAttributes(gl, programInfo.attribSetters, bufferInfo);
      }

      // Set the uniforms.
      setUniforms(programInfo.uniformSetters, object.uniforms);

      // Draw
      drawBufferInfo(gl, gl.TRIANGLES, bufferInfo);
    });
  }

  // Replace requestAnimationFrame.
  if (topWindow.requestAnimationFrame) {
    topWindow.requestAnimationFrame = (function(oldRAF) {

      return function(callback, element) {
        var handler = function() {
          if (isOnScreen(element)) {
            oldRAF(callback, element);
          } else {
            oldRAF(handler, element);
          }
        };
        handler();
      };

    }(topWindow.requestAnimationFrame));
  }

  // All browsers that support WebGL support requestAnimationFrame
  topWindow.requestAnimFrame = topWindow.requestAnimationFrame;       // just to stay backward compatible.
  topWindow.cancelRequestAnimFrame = topWindow.cancelAnimationFrame;  // just to stay backward compatible.

  return {
    createAugmentedTypedArray: createAugmentedTypedArray,
    createAttribsFromArrays: createAttribsFromArrays,
    createBuffersFromArrays: createBuffersFromArrays,
    createBufferInfoFromArrays: createBufferInfoFromArrays,
    createAttributeSetters: createAttributeSetters,
    createProgram: createProgram,
    createProgramFromScripts: createProgramFromScripts,
    createProgramFromSources: createProgramFromSources,
    createProgramInfo: createProgramInfo,
    createUniformSetters: createUniformSetters,
    drawBufferInfo: drawBufferInfo,
    drawObjectList: drawObjectList,
    getWebGLContext: getWebGLContext,
    updateCSSIfInIFrame: updateCSSIfInIFrame,
    getExtensionWithKnownPrefixes: getExtensionWithKnownPrefixes,
    resizeCanvasToDisplaySize: resizeCanvasToDisplaySize,
    setAttributes: setAttributes,
    setBuffersAndAttributes: setBuffersAndAttributes,
    setUniforms: setUniforms,
    setupWebGL: setupWebGL,
  };

}));


text:
package net.astechdesign.clients.repo;

import org.junit.Test;

import javax.sql.DataSource;

public class DBBuilderTest {

    @Test
    public void buildDB() throws Exception {

        DataSource dataSource = TestDataSource.getDataSource();
        DBBuilder.initialiseDb(dataSource);
        DBBuilder.initialiseDb(dataSource);

    }
}


text:
<?php
namespace Anand\LaravelPaytmWallet\Providers;
use Anand\LaravelPaytmWallet\Traits\HasTransactionStatus;
use Illuminate\Http\Request;

class StatusCheckProvider extends PaytmWalletProvider{
	use HasTransactionStatus;

	private $parameters = null;
    protected $response;

	public function prepare($params = array()){
		$defaults = [
			'order' => NULL,
		];

		$_p = array_merge($defaults, $params);
		foreach ($_p as $key => $value) {

			if ($value == NULL) {

				throw new \Exception(' \''.$key.'\' parameter not specified in array passed in prepare() method');

				return false;
			}
		}
		$this->parameters = $_p;
		return $this;
	}

	public function check(){
		if ($this->parameters == null) {
			throw new \Exception("prepare() method not called");
		}
		return $this->beginTransaction();
	}

	private function beginTransaction(){
		$params = array(
			'MID' => $this->merchant_id,
			'ORDERID' => $this->parameters['order']
		);
		$chk = getChecksumFromArray($params, $this->merchant_key);
		$params['CHECKSUMHASH'] = $chk;
		$this->response = $this->api_call_new($this->paytm_txn_status_url, $params);
		return $this;
	}

	public function response(){
		return $this->response;
	}

    public function getOrderId(){
        return $this->response()['ORDERID'];
    }
    public function getTransactionId(){
        return $this->response()['TXNID'];
    }

}


text:
package rst.pdfbox.layout.elements;

import java.io.IOException;

/**
 * If a drawable is marked as {@link Dividable}, it can be (vertically) divided
 * in case it does not fit on the (remaining) page.
 */
public interface Dividable {

    /**
     * Divides the drawable vetically into pieces where the first part is to
     * respect the given remaining height. The page height allows to make better
     * decisions on how to divide best.
     *
     * @param remainingHeight
     *            the remaining height on the page dictating the height of the
     *            first part.
     * @param nextPageHeight
     *            the height of the next page allows to make better decisions on
     *            how to divide best, e.g. maybe the element fits completely on
     *            the next page.
     * @return the Divided containing the first part and the tail.
     * @throws IOException by pdfbox.
     */
    Divided divide(final float remainingHeight, final float nextPageHeight)
	    throws IOException;

    /**
     * A container for the result of a {@link Dividable#divide(float, float)}
     * operation.
     */
    public static class Divided {

	private final Drawable first;
	private final Drawable tail;

	public Divided(Drawable first, Drawable tail) {
	    this.first = first;
	    this.tail = tail;
	}

	public Drawable getFirst() {
	    return first;
	}

	public Drawable getTail() {
	    return tail;
	}

    }

}


text:
package com.example.swipebackactivity.app;

import com.example.swipebackactivity.SwipeBackLayout;

public interface SwipeBackActivityBase {
     SwipeBackLayout getSwipeBackLayout();

      void setSwipeBackEnable(boolean enable);

     void scrollToFinishActivity();

}