text:
using UnityEngine;

public class PlayerBase : MonoBehaviour
{
    public bool canFlap = true;
    protected int gravityValue;
    public int gemGoodValue;
    public int gemBadValue;

    private Rigidbody2D rigidBody;
    public Rigidbody2D RigidBody
    {
        get
        {
            if (rigidBody == null)
            {
                return rigidBody = GetComponent<Rigidbody2D>();
            }

            return rigidBody;
        }
    }

    public void DisableInput()
    {
        canFlap = false;
        RigidBody.gravityScale = 0;
    }

    public void EnableInput()
    {
        canFlap = true;
        RigidBody.gravityScale = gravityValue;
    }

    protected void Die(string playerName, int amount)
    {
        canFlap = false;
    }
}


text:
var INTERVAL_MILLS_MIN_TRESHOLD = 200;
var DEFATUL_INTERVAL_MILLS = 250;

function save_options() {
  var intervalMills = document.getElementById('intervalMills').value;
  if (intervalMills < INTERVAL_MILLS_MIN_TRESHOLD) { return; }

  chrome.storage.local.set({
    "intervalMills": intervalMills
  }, function() {
    var status = document.getElementById('status');
    status.textContent = 'Сохранено!';
    setTimeout(function() { status.textContent = ''; }, 1000);
  });
}

function restore_options() {
  chrome.storage.local.get("intervalMills", function(items) {
    if (items.intervalMills) {
      document.getElementById('intervalMills').value = items.intervalMills;
    } else {
      document.getElementById('intervalMills').value = DEFATUL_INTERVAL_MILLS;
    }
  });
}

document.addEventListener('DOMContentLoaded', restore_options);
document.getElementById('save').addEventListener('click', save_options);

redpajama_set_name: RedPajamaGithub


text:
package net.mightyelemental.imgEvolution;

import java.util.Random;

import org.newdawn.slick.AppGameContainer;
import org.newdawn.slick.Color;
import org.newdawn.slick.Game;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.Image;
import org.newdawn.slick.Input;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.openal.SoundStore;

public class ImageEvolution implements Game {

	public static ImageGen target, guess;

	int	targetFit		= 0;
	int	generationCount	= 0;

	public ImageEvolution() throws SlickException {

	}

	public static void main(String[] args) {
		AppGameContainer appGc;
		try {
			SoundStore.get().init();
			appGc = new AppGameContainer(new ImageEvolution());
			appGc.setDisplayMode(800, (int) (800 / 16.0 * 9.0), false);
			appGc.setTargetFrameRate(60);
			appGc.setShowFPS(false);
			appGc.setAlwaysRender(true);
			appGc.start();
		} catch (SlickException e) {
			e.printStackTrace();
			System.exit(1);
		}
	}

	public void newGeneration() throws SlickException {
		int bestFitness = calcFitness(guess);
		generationCount++;
		while (bestFitness == calcFitness(guess)) {
			ImageGen ig = new ImageGen(guess);
			ig.setPixel(rand.nextInt(target.imgSize), rand.nextInt(target.imgSize), rand.nextInt(256));
			if ( calcFitness(ig) > bestFitness ) {
				guess.setPixels(ig.pixels);
				break;
			}
		}
	}

	int pos = 0;

	public void newGenerationV2() {
		if ( pos == -1 ) return;
		int bestFitness = calcFitness(guess);
		generationCount++;
		int bestCol = -1;
		int prevFit = Integer.MIN_VALUE;
		for ( int i = 0; i < 256; i++ ) {
			guess.pixels[pos] = i;
			int f = calcFitness(guess);
			if ( f > bestFitness ) {
				bestCol = i;
				bestFitness = f;
			}
			if ( f < prevFit ) break;
			prevFit = f;
		}
		guess.pixels[pos] = bestCol;
		// if ( pos % (guess.imgSize / 2) == 0 ) {
		guess.imgBeenEdited = true;
		// }
		pos++;
		if ( pos >= guess.pixels.length ) pos = -1;
	}

	public void newGenerationV3() throws SlickException {
		int bestFitness = calcFitness(guess);
		generationCount++;
		int[] pix = new int[guess.pixels.length];
		int x = generationCount < (pix.length / 6) ? 100 : (generationCount < 1000 ? generationCount : 1000);
		for ( int i = 0; i < x; i++ ) {
			ImageGen ig = new ImageGen(guess);
			ig.setPixel(rand.nextInt(target.imgSize), rand.nextInt(target.imgSize), rand.nextInt(256));
			if ( calcFitness(ig) > bestFitness ) {
				pix = ig.pixels;
				bestFitness = calcFitness(ig);
			}
		}
		if ( bestFitness != calcFitness(guess) ) {
			guess.setPixels(pix);
		}
	}

	public void newGenerationV4() throws SlickException {
		int bestFitness = calcFitness(guess);
		generationCount++;
		for ( int i = 0; i < guess.pixels.length; i++ ) {
			guess.setPixel(i, guess.pixels[i] + 1);
			if ( calcFitness(guess) < bestFitness ) {
				guess.setPixel(i, guess.pixels[i] - 1);
			} else {
				bestFitness = calcFitness(guess);
			}
		}
	}

	public int calcFitness(ImageGen img) {
		int fitness = 0;
		int combo = 0;

		for ( int i = 0; i < img.pixels.length; i++ ) {
			if ( img.pixels[i] == target.pixels[i] ) {
				combo++;
				fitness += 1 + combo;
			} else {
				fitness -= Math.abs(img.pixels[i] - target.pixels[i]);
				combo = 0;
			}
		}

		return fitness;
	}

	@Override
	public boolean closeRequested() {
		return false;
	}

	@Override
	public String getTitle() {
		return "Image Evolution";
	}

	@Override
	public void init(GameContainer gc) throws SlickException {
		gc.setClearEachFrame(true);
		target = new ImageGen(ResourceLoader.loadImage("biancalow"));
		targetFit = calcFitness(target);
		guess = new ImageGen(target.imgSize);
	}

	@Override
	public void render(GameContainer gc, Graphics g) throws SlickException {
		Image i = target.getImage().getScaledCopy(200, 200);
		g.setAntiAlias(false);
		g.drawImage(i, 50, 50);
		g.setColor(Color.green);
		g.drawRect(49, 49, i.getWidth() + 2, i.getHeight() + 2);
		i = guess.getImage().getScaledCopy(200, 200);
		g.drawImage(i, 260, 50);
		g.setColor(Color.red);
		g.drawRect(259, 49, i.getWidth() + 2, i.getHeight() + 2);
		g.setColor(Color.black);
		g.fillRect(200, 300, 500, 50);
		g.setColor(Color.white);
		g.drawString("Time " + (System.currentTimeMillis() - start) / 1000 + " seconds", 200, 300);
		g.drawString(generationCount + " generations", 200, 330);

	}

	Random rand = new Random();

	long start = System.currentTimeMillis();

	int ticks;

	@Override
	public void update(GameContainer gc, int delta) throws SlickException {
		// target.setPixel(rand.nextInt(target.imgSize), rand.nextInt(target.imgSize),
		// rand.nextInt(256));
		// ticks++;
		if ( gc.getInput().isKeyDown(Input.KEY_SPACE) ) {
			start = System.currentTimeMillis();
			ticks++;
		}

		if ( ticks > 1 ) {
			newGenerationV3();
		}

		if ( pos == -1 ) {
			System.err.println("TIME = " + (System.currentTimeMillis() - start) + " ("
					+ (System.currentTimeMillis() - start) / 1000 + ")");
			System.exit(0);
		}
	}

}


text:
var photoUtils = realsense.DepthEnabledPhotography.PhotoUtils;
var measurement = new realsense.DepthEnabledPhotography.Measurement();
var xdmUtils = realsense.DepthEnabledPhotography.XDMUtils;
var motionEffect = new realsense.DepthEnabledPhotography.MotionEffect();
var imgData;

function getStream(successCallback, errorCallback) {
  navigator.getUserMedia({ video: true }, function getSuccessCallback(stream) {
    var photoCapture = new realsense.DepthEnabledPhotography.PhotoCapture(stream);
    setTimeout(function() {
      photoCapture.takePhoto().then(function(photo) {
        successCallback(photo);
      });
    }, 3000);
  }, function(ex) {
    errorCallback(ex);
  });
}

function getContainerImage(photo, callback1, callback2) {
  photo.queryContainerImage().then(callback1, callback2);
}

function fillCanvas(image) {
  imgCanvas.width = image.width;
  imgCanvas.height = image.height;
  imgContext.clearRect(0, 0, image.width, image.height);
  imgData = imgContext.createImageData(image.width, image.height);
  imgData.data.set(image.data);
  imgContext.putImageData(imgData, 0, 0);
}

function ConvertDepthToRGBUsingHistogram(
    depthImage, nearColor, farColor, rgbImage) {
  var depthImageData = depthImage.data;
  var imageSize = depthImage.width * depthImage.height;
  for (var l = 0; l < imageSize; ++l) {
    rgbImage[l * 4] = 0;
    rgbImage[l * 4 + 1] = 0;
    rgbImage[l * 4 + 2] = 0;
    rgbImage[l * 4 + 3] = 255;
  }
  // Produce a cumulative histogram of depth values
  var histogram = new Int32Array(256 * 256);
  for (var i = 0; i < imageSize; ++i) {
    if (depthImageData[i]) {
      ++histogram[depthImageData[i]];
    }
  }
  for (var j = 1; j < 256 * 256; ++j) {
    histogram[j] += histogram[j - 1];
  }

  // Remap the cumulative histogram to the range 0..256
  for (var k = 1; k < 256 * 256; k++) {
    histogram[k] = (histogram[k] << 8) / histogram[256 * 256 - 1];
  }

  // Produce RGB image by using the histogram to interpolate between two colors
  for (var l = 0; l < imageSize; ++l) {
    if (depthImageData[l]) { // For valid depth values (depth > 0)
      // Use the histogram entry (in the range of 0..256) to interpolate between nearColor and
      // farColor
      var t = histogram[depthImageData[l]];
      rgbImage[l * 4] = ((256 - t) * nearColor[0] + t * farColor[0]) >> 8;
      rgbImage[l * 4 + 1] = ((256 - t) * nearColor[1] + t * farColor[1]) >> 8;
      rgbImage[l * 4 + 2] = ((256 - t) * nearColor[2] + t * farColor[2]) >> 8;
      rgbImage[l * 4 + 3] = 255;
    }
  }
}

function covertDateToString () {
  var date = new Date();
  var dateString =
      date.getFullYear() +
      ('0' + (date.getMonth() + 1)).slice(-2) +
      ('0' + date.getDate()).slice(-2) +
      ('0' + date.getHours()).slice(-2) +
      ('0' + date.getMinutes()).slice(-2) +
      ('0' + date.getSeconds()).slice(-2);
  return dateString;
}


text:
using namespace std;
namespace po = boost::program_options;
namespace fs = boost::filesystem;
namespace sys = boost::system;

namespace puppet { namespace compiler {

    static po::options_description create_options()
    {
        // Build a list of options visible on the command line
        // Keep this list sorted alphabetically based on each option's long-form name
        po::options_description options("");
        options.add_options()
            (
                "code-dir",
                po::value<string>(),
                "The Puppet code directory to use. Defaults to the current platform's code directory."
            )
            (
                "color",
                "Forces color output on platforms that support colorized output."
            )
            (
                "debug,d",
                "Enable debug output."
            )
            (
                "environment,e",
                po::value<string>()->default_value("production"),
                "The environment to compile for."
            )
            (
                "environment-dir",
                po::value<vector<string>>(),
                "Specifies a directory to search for environments."
            )
            (
                "facts,f",
                po::value<string>(),
                "The path to the YAML facts file to use. Defaults to the current system's facts."
            )
            (
                "help",
                "Print this help message."
            )
            (
                "log-level,l",
                po::value<logging::level>()->default_value(logging::level::notice, "notice"),
                "Set logging level.\nSupported levels: debug, info, notice, warning, error, alert, emergency, critical."
            )
            (
                "module-dir",
                po::value<vector<string>>(),
                "Specifies a directory to search for global modules."
            )
            (
                "node,n",
                po::value<string>(),
                "The node name to use. Defaults to the 'fqdn' fact."
            )
            (
                "no-color",
                "Disables color output."
            )
            (
                "output,o",
                po::value<string>()->default_value("catalog.json"),
                "The output path for the compiled catalog."
            )
            (
                "verbose",
                "Enable verbose (info) output."
            )
            (
                "version,v",
                "Print the version and exit."
            )
            ;
        return options;
    }

    static logging::level get_level(po::variables_map const& vm)
    {
        // Check for conflicting options
        if (vm.count("color") && vm.count("no-color")) {
            throw settings_exception("color and no-color options conflict: please specify only one.");
        }
        if ((vm.count("debug") + vm.count("verbose") + (vm["log-level"].defaulted() ? 0 : 1)) > 1) {
            throw settings_exception("debug, verbose, and log-level options conflict: please specify only one.");
        }

        // Override the log level for debug/verbose
        if (vm.count("debug")) {
            return logging::level::debug;
        }
        if (vm.count("verbose")) {
            return logging::level::info;
        }
        return vm["log-level"].as<logging::level>();
    }

    static string get_code_directory(po::variables_map const& vm)
    {
        string directory;
        if (vm.count("code-dir")) {
            directory = vm["code-dir"].as<string>();
        }
        if (directory.empty()) {
            directory = settings::default_code_directory();
        } else {
            // Not default, so ensure the path exists by getting the code path
            sys::error_code ec;
            auto path = fs::canonical(directory, ec);
            if (ec) {
                throw settings_exception((boost::format("invalid code directory '%1%': %2%.") % directory % ec.message()).str());
            }
            directory = path.string();
        }
        return directory;
    }

    static string get_environment(po::variables_map const& vm)
    {
        return vm["environment"].as<string>();
    }

    static shared_ptr<facts::provider> get_facts(po::variables_map const& vm)
    {
        if (vm.count("facts")) {
            return make_shared<facts::yaml>(vm["facts"].as<string>());
        }

        // Default to facter
        return make_shared<facts::facter>();
    }

    static string get_node(po::variables_map const& vm, facts::provider& facts)
    {
        // Check to see if it was explicitly set
        string name;
        if (vm.count("node")) {
            name = vm["node"].as<string>();
        }
        if (!name.empty()) {
            return name;
        }

        // If no node name was specified, use the FQDN fact
        // NOTE: the following uses of boost::get are safe because facts never contain runtime variables
        // Next try "networking" fact
        auto networking = facts.lookup("networking");
        if (networking) {
            if (auto ptr = boost::get<runtime::values::hash const>(networking.get())) {
                auto it = ptr->find(string("fqdn"));
                if (it != ptr->end()) {
                    if (auto str = boost::get<string const>(&it->second)) {
                        name = *str;
                    }
                }
                // Fallback to the hostname and domain if present
                if (name.empty()) {
                    auto hostname = ptr->find(string("hostname"));
                    if (hostname != ptr->end()) {
                        if (auto str = boost::get<string const>(&hostname->second)) {
                            name = *str;
                        }
                        if (!name.empty()) {
                            auto domain = ptr->find(string("domain"));
                            if (domain != ptr->end()) {
                                if (auto str = boost::get<string const>(&domain->second)) {
                                    name += "." + *str;
                                }
                            }
                        }
                    }
                }
            }
        }

        // Next try the legacy fqdn fact
        if (name.empty()) {
            auto fqdn = facts.lookup("fqdn");
            if (fqdn) {
                if (auto ptr = boost::get<string const>(fqdn.get())) {
                    name = *ptr;
                }
            }
        }

        // Next try legacy hostname + domain facts
        if (name.empty()) {
            auto hostname = facts.lookup("hostname");
            if (hostname) {
                if (auto ptr = boost::get<string const>(hostname.get())) {
                    name = *ptr;
                }
                if (!name.empty()) {
                    auto domain = facts.lookup("domain");
                    if (domain) {
                        if (auto ptr = boost::get<string const>(domain.get())) {
                            name += "." + *ptr;
                        }
                    }
                }
            }
        }

        // If still empty, user must explicitly specify
        if (name.empty()) {
            throw settings_exception("node name cannot be determined from facts: please specify the --node option to set the node name.");
        }
        return name;
    }

    static vector<string> get_manifests(po::variables_map const& vm)
    {
        vector<string> manifests;
        if (vm.count("manifests")) {
            manifests = vm["manifests"].as<vector<string>>();
            for (auto& manifest : manifests) {
                manifest = fs::absolute(manifest).string();
            }
        }
        return manifests;
    }

    static string get_environment_directory(po::variables_map const& vm, string const& code_directory, string const& environment)
    {
        bool specified = false;
        vector<string> directories;
        if (vm.count("environment-dir")) {
            directories = vm["environment-dir"].as<vector<string>>();
            specified = true;
        } else {
            directories = settings::default_environment_directories();
        }

        for (auto& directory : directories) {
            // Replace all references to $codedir with the code directory
            boost::replace_all(directory, "$codedir", code_directory);

            sys::error_code ec;
            auto path = fs::canonical(directory, ec);
            if (ec) {
                // TODO: it'd be nice to log that the directory does not exist
                continue;
            }

            path /= environment;
            if (fs::exists(path, ec)) {
                return path.string();
            }

            // TODO: it'd be nice to log that the directory does not exist
        }

        // If directories were specified, it's an error if the environment's directory cannot be found
        if (specified) {
            throw settings_exception((boost::format("could not locate an environment directory for environment '%1%'.") % environment).str());
        }

        // Use the default
        return (fs::path(directories.back()) / environment).string();
    }

    static vector<string> get_module_directories(po::variables_map const& vm, string const& code_directory)
    {
        vector<string> directories;
        if (vm.count("module-dir")) {
            directories = vm["module-dir"].as<vector<string>>();
        } else {
            directories = settings::default_module_directories();
        }

        for (auto& directory : directories) {
            // Replace all references to $codedir with the code directory
            boost::replace_all(directory, "$codedir", code_directory);

            sys::error_code ec;
            auto path = fs::canonical(directory, ec);
            if (ec) {
                // TODO: it'd be nice to log that the directory does not exist
                directory.clear();
                continue;
            }
            directory = path.string();
        }

        // Remove all empty directories
        directories.erase(
            remove_if(directories.begin(), directories.end(), [](string const& directory) { return directory.empty(); }),
            directories.end());
        return directories;
    }

    settings::settings() :
        _log_level(logging::level::notice),
        _show_help(false),
        _show_version(false)
    {
        parse(0, nullptr);
    }

    settings::settings(int argc, char const* argv[]) :
        _log_level(logging::level::notice),
        _show_help(false),
        _show_version(false)
    {
        parse(argc, argv);
    }

    string const& settings::code_directory() const
    {
        return _code_directory;
    }

    string const& settings::environment() const
    {
        return _environment;
    }

    string const& settings::environment_directory() const
    {
        return _environment_directory;
    }

    vector<string> const& settings::module_directories() const
    {
        return _module_directories;
    }

    vector<string> const& settings::manifests() const
    {
        return _manifests;
    }

    string const& settings::node_name() const
    {
        return _node_name;
    }

    shared_ptr<facts::provider> const& settings::facts() const
    {
        return _facts;
    }

    logging::level settings::log_level() const
    {
        return _log_level;
    }

    bool settings::show_help() const
    {
        return _show_help;
    }

    bool settings::show_version() const
    {
        return _show_version;
    }

    void settings::print_usage()
    {
        cout <<
            "Synopsis\n"
            "========\n"
            "\n"
            "Compiles Puppet manifests into Puppet catalogs.\n"
            "\n"
            "Usage\n"
            "=====\n"
            "\n"
            "  puppetcpp [options] [[manifest] [manifest] ...]\n"
            "\n"
            "Options\n"
            "=======\n\n"
            << create_options() <<
            "\nDescription\n"
            "===========\n"
            "\n"
            "Compiles a Puppet manifest into a Puppet catalog. When invoked with no options,\n"
            "the compiler will compile the manifest for the 'production' environment.\n"
            "\n"
            "Manifests will be evaluated in the order they are presented on the command line.\n"
            "\n"
            "Examples\n"
            "========\n\n"
            "  puppetcpp\n"
            "  puppetcpp manifest.pp\n"
            "  puppetcpp -e test -f facts.yaml"
            << endl;
    }

    void settings::parse(int argc, char const* argv[])
    {
        po::variables_map vm;

        if (argc > 1) {
            auto visible_options = create_options();

            // Build a list of "hidden" options that are not visible on the command line
            po::options_description hidden_options("");
            hidden_options.add_options()
                    ("manifests", po::value<vector<string>>());

            // Create the supported command line options (visible + hidden)
            po::options_description command_line_options;
            command_line_options.add(visible_options).add(hidden_options);

            // Build a list of positional options (in our case, just manifest files)
            po::positional_options_description positional_options;
            positional_options.add("manifests", -1);

            try {
                // Store the options
                po::store(
                    po::command_line_parser(argc, argv).
                        style(po::command_line_style::unix_style & ~po::command_line_style::allow_guessing).
                        options(command_line_options).
                        positional(positional_options).
                        run(), vm);

                // Check for help or version before notifying
                if (vm.count("help")) {
                    _show_help = true;
                    return;
                }
                if (vm.count("version")) {
                    _show_version = true;
                    return;
                }

                // Notify the callbacks
                po::notify(vm);
            } catch (po::error const &ex) {
                throw settings_exception(ex.what());
            }
        }

        // Populate the logging level
        _log_level = get_level(vm);

        // Populate the code directory
        _code_directory = get_code_directory(vm);

        // Populate the environment
        _environment = get_environment(vm);

        // Populate the environment's directory
        _environment_directory = get_environment_directory(vm, _code_directory, _environment);

        // Populate the module directories
        _module_directories = get_module_directories(vm, _code_directory);

        // Populate the facts provider
        _facts = get_facts(vm);

        // Populate the node name
        _node_name = get_node(vm, *_facts);

        // Populate the manifests to compile
        _manifests = get_manifests(vm);
    }

}}  // namespace puppet::compiler


text:
using System;
using NUnit.Framework;
using System.Linq;
using Underscore.Object.Reflection;

namespace Underscore.Test.Object.Reflection
{
	[TestFixture]
	public class AttributeTest
	{
		[AttributeUsage(AttributeTargets.All,AllowMultiple=true)]
		public class TestMultipleAttribute : Attribute
		{
			public string Info { get; set; }
		}

		[AttributeUsage(AttributeTargets.All , AllowMultiple = true)]
		public class TestSingleAttribute : Attribute
		{
			public string Info { get; set; }
		}

		[TestSingle(Info="OnClass")]
		public class Person
		{

			[TestSingle(Info = "OnField")]
			public string Field { get; set; }

			[TestSingle(Info="OnProperty")]
			public string FirstName { get; set; }

			public string LastName { get; set; }

			public string NickName { get; set; }

			public string MiddleName { get; set; }

			public string Title { get; set; }

			public string Suffix { get; set; }

			public int Age { get; set; }

		}

		[TestMultiple(Info="First")]
		[TestMultiple(Info="Second")]
		class Employee
		{
			public string FirstName { get; set; }
			public string LastName { get; set; }
			public decimal Salary { get; set; }
		}

		class MixedAttributesExample
		{
			[TestMultiple(Info="First")]
			[TestMultiple(Info="Second")]
			[TestSingle(Info="Single")]
			public string A { get; set; }
		}

		[Test]
		public void AttributeHasCustomAttribute()
		{
			Assert.IsFalse(
				_.Object.Attribute.Has<TestMultipleAttribute>(typeof(Person))
		   );

			Assert.IsFalse(
				_.Object.Attribute.Has<TestMultipleAttribute>(new Person())
		   );

			Assert.IsFalse(
				_.Object.Attribute.Has<TestMultipleAttribute>(null)
		   );

			var fnProp = typeof(Person).GetMember("FirstName").FirstOrDefault();

			Assert.IsFalse(
			   _.Object.Attribute.Has<TestMultipleAttribute>(fnProp)
		   );

			Assert.IsTrue(
				_.Object.Attribute.Has<TestSingleAttribute>(fnProp)
		   );

			var mp = typeof(MixedAttributesExample).GetMember("A").First();

			Assert.IsTrue(
				_.Object.Attribute.Has<TestSingleAttribute>(mp)
		   );

			Assert.IsTrue(
				_.Object.Attribute.Has<TestMultipleAttribute>(mp)
		   );

		}

		[Test]
		public void AttributeGetCustomAttribute()
		{
			var multiAttr = _.Object.Attribute.Find<TestMultipleAttribute>(typeof(Person));

			Assert.IsNull(multiAttr);

			multiAttr = _.Object.Attribute.Find<TestMultipleAttribute>(new Person());

			Assert.IsNull(multiAttr);

			multiAttr = _.Object.Attribute.Find<TestMultipleAttribute>(null);

			var fnProp = typeof(Person).GetMember("FirstName").FirstOrDefault();

			multiAttr = _.Object.Attribute.Find<TestMultipleAttribute>(fnProp);

			Assert.IsNull(multiAttr);

			var sattr = _.Object.Attribute.Find<TestSingleAttribute>(fnProp);

			Assert.IsNotNull(sattr);
			Assert.AreEqual("OnProperty" , sattr.Info);

			var mp = typeof(MixedAttributesExample).GetMember("A").First();

			sattr = _.Object.Attribute.Find<TestSingleAttribute>(mp);

			Assert.IsNotNull(sattr);
			Assert.AreEqual("Single" , sattr.Info);

			multiAttr = _.Object.Attribute.Find<TestMultipleAttribute>(mp);

			Assert.IsNotNull(multiAttr);
			Assert.IsTrue("First" ==  multiAttr.Info  || "Second" == multiAttr.Info);
		}

		[Test]
		public void AttributeGetCustomAttributes()
		{

			var multiAttr = _.Object.Attribute.All<TestMultipleAttribute>(typeof(Person));

			Assert.IsNotNull(multiAttr);
			Assert.AreEqual(0 , multiAttr.Count());

			multiAttr = _.Object.Attribute.All<TestMultipleAttribute>(new Person());

			Assert.IsNotNull(multiAttr);
			Assert.AreEqual(0 , multiAttr.Count());

			multiAttr = _.Object.Attribute.All<TestMultipleAttribute>(null);

			Assert.IsNotNull(multiAttr);
			Assert.AreEqual(0 , multiAttr.Count());

			var fnProp = typeof(Person).GetMember("FirstName").FirstOrDefault();
			multiAttr = _.Object.Attribute.All<TestMultipleAttribute>(fnProp);

			Assert.IsNotNull(multiAttr);
			Assert.AreEqual(0 , multiAttr.Count());

			var sattr = _.Object.Attribute.All<TestSingleAttribute>(fnProp);

			Assert.IsNotNull(sattr);
			Assert.AreEqual(1 , sattr.Count());
			Assert.AreEqual("OnProperty" , sattr.First().Info);

			var mp = typeof(MixedAttributesExample).GetMember("A").First();

			sattr = _.Object.Attribute.All<TestSingleAttribute>(mp);

			Assert.IsNotNull(sattr);
			Assert.AreEqual(1 , sattr.Count());
			Assert.AreEqual("Single" , sattr.First().Info);

			multiAttr = _.Object.Attribute.All<TestMultipleAttribute>(mp);

			Assert.IsNotNull(multiAttr);
			Assert.AreEqual(2 , multiAttr.Count());
			var firstOne = multiAttr.First().Info;
			var secondOne = multiAttr.Skip(1).First().Info;
			Assert.IsTrue("First" == firstOne || "Second" == firstOne);
			Assert.IsTrue("Second"  == secondOne || "First" == secondOne);
			Assert.IsTrue(firstOne != secondOne);
		}
	}
}


text:
#ifndef MAYA_FUNCS_H
#define MAYA_FUNCS_H

#include "pandatoolbase.h"
#include "luse.h"
#include "config_maya.h"

#include "pre_maya_include.h"
#include <maya/MFnAttribute.h>
#include <maya/MPlug.h>
#include <maya/MStatus.h>
#include <maya/MFnDependencyNode.h>
#include <maya/MObject.h>
#include <maya/MString.h>
#include <maya/MVector.h>
#include "post_maya_include.h"

bool
get_maya_plug(MObject &node, const std::string &attribute_name, MPlug &plug);

bool
is_connected(MObject &node, const std::string &attribute_name);

template<class ValueType>
bool
get_maya_attribute(MObject &node, const std::string &attribute_name,
                   ValueType &value);

template<class ValueType>
bool
set_maya_attribute(MObject &node, const std::string &attribute_name,
                   ValueType &value);

bool
has_attribute(MObject &node, const std::string &attribute_name);

bool
remove_attribute(MObject &node, const std::string &attribute_name);

bool
get_bool_attribute(MObject &node, const std::string &attribute_name,
                   bool &value);

bool
get_angle_attribute(MObject &node, const std::string &attribute_name,
                    double &value);

bool
get_vec2_attribute(MObject &node, const std::string &attribute_name,
                    LVecBase2 &value);

bool
get_vec3_attribute(MObject &node, const std::string &attribute_name,
                    LVecBase3 &value);

bool
get_vec2d_attribute(MObject &node, const std::string &attribute_name,
                    LVecBase2d &value);

bool
get_vec3d_attribute(MObject &node, const std::string &attribute_name,
                    LVecBase3d &value);

bool
get_mat4d_attribute(MObject &node, const std::string &attribute_name,
                    LMatrix4d &value);

void
get_tag_attribute_names(MObject &node, pvector<std::string> &tag_names);

bool
get_enum_attribute(MObject &node, const std::string &attribute_name,
                   std::string &value);

bool
get_string_attribute(MObject &node, const std::string &attribute_name,
                     std::string &value);

bool
set_string_attribute(MObject &node, const std::string &attribute_name,
                     const std::string &value);

void
describe_maya_attribute(MObject &node, const std::string &attribute_name);

bool
describe_compound_attribute(MObject &node);

std::string
string_mfndata_type(MFnData::Type type);

void
list_maya_attributes(MObject &node);

// Also, we must define some output functions for Maya objects, since we can't
// use those built into Maya (which forward-defines the ostream type
// incorrectly).
INLINE std::ostream &operator << (std::ostream &out, const MString &str);
INLINE std::ostream &operator << (std::ostream &out, const MVector &vec);

#include "maya_funcs.I"
#include "maya_funcs.T"

#endif


text:
'use strict';

import { WebviewExtension } from '../webview_extension';

export class KeyboardInitExtension implements WebviewExtension {
    private startingKeys: number[];

    public constructor(startingKeys: number[]) {
        this.startingKeys = startingKeys;
    }

    public generateContent(): string {
        return `\
const numKeys = 256;
const numStates = 4;
let keyBoardData = new Uint8Array(numKeys * numStates);
let keyBoardTexture = new THREE.DataTexture(keyBoardData, numKeys, numStates, THREE.LuminanceFormat, THREE.UnsignedByteType);
keyBoardTexture.magFilter = THREE.NearestFilter;
keyBoardTexture.needsUpdate = true;
let pressedKeys = [];
let releasedKeys = [];
let toggledKeys = [${this.startingKeys}];
for (let key of toggledKeys) {
    keyBoardData[key + 512] = 255; // Toggled
}`;
    }
}


text:
<% if (!selectionMod) { %>
    <% if (can_create) { %>

            <a class="btn btn-info" href="#<%- Backbone.history.generateUrl('newMedia') %>" role="button"><%- Translator.trans('open_orchestra_backoffice.add')%>

    <% } %>

 <%- Translator.trans('open_orchestra_media_admin.media.title_list') %>

<% } %>
<form class="form-horizontal search-engine ">

        <input type="hidden" name='language' value="<%- language %>">
        <%- Translator.trans('open_orchestra_media_admin.table.media.label') %>

            <input type="text" name='label' class="form-control" id="label">

    <% if ('' == filterType) { %>

            <%- Translator.trans('open_orchestra_media_admin.table.media.type') %>

                    <select name='type' class="form-control" id="select-type">
                        <% _.each(types, function(label, type) { %>
                            <option value="<%- type %>"><%- Translator.trans(label) %></option>
                        <% }); %>
                    </select>

    <% } %>

        <%- Translator.trans('open_orchestra_media_admin.table.media.folder') %>

                <select name='folderId' class="form-control" id="folderId">
                    <option value=""><%- Translator.trans('open_orchestra_media_admin.search_engine.folder.all') %></option>
                    <% _.each(foldersTree.models[0].get('children'), function(child) { %>
                        <%= renderTemplate('Media/folderTreeOptionView', {tree: child, depth: 1, renderTemplate: renderTemplate, selectionMod: selectionMod, folderId: folderId}) %>
                    <% }); %>
                </select>

            <button class="btn btn-info col-md-offset-4 submit"><%- Translator.trans('open_orchestra_backoffice.search_engine.filter') %></button>

</form>

<% if (! selectionMod) { %>

        <button class="btn btn-danger btn-delete disabled"><%- Translator.trans('open_orchestra_backoffice.table.delete_button') %></button>

<% } %>


text:
export function retry(this: any, func: Function, retryMax: number, config: any = {}) {
  let retryNum = 0;
  const { retryDelay = 500, errorHandler = () => true } = config;
  const funcR = (...arg) => {
    return new Promise((resolve, reject) => {
      func(...arg)
        .then(result => {
          retryNum = 0;
          resolve(result);
        })
        .catch(err => {
          if (retryNum < retryMax && errorHandler(err)) {
            retryNum++;
            setTimeout(() => {
              resolve(funcR(...arg));
            }, retryDelay);
          } else {
            retryNum = 0;
            reject(err);
          }
        });
    });
  };

  return funcR;
}


text:
var x = 0;
var peat = []
if (!localStorage.peatList) {
    localStorage.peatList = "[]";
}
peat = JSON.parse(localStorage.peatList);
peaAdd = function(){
	var task = document.getElementById('taskpea').value;
    if (task != '') {
        // Add the task to array and refresh list
        peat[peat.length] = task;
        peaRefresh();
        // Clear the input
        document.getElementById('taskpea').value = '';
    }
};
peaRefresh = function(){
	var $tasks = $('#tlpea');
    // Clear the existing task list
    $tasks.empty();
    if (peat.length) {
        for (var i=0;i<peat.length;i++){
            // Append each task
			x = i;
            var li = '
' + peat[i] + '
'
            $tasks.append(li);
			$(function () {
			$("#confirmpea"+i).bind("singletap", function() {
				$.UIPopup({
					id: "warning",
					title: 'Completed?',
					message: 'Have you really completed this task?',
					cancelButton: 'No',
					continueButton: 'Yes',
					callback: function() {
						peat.splice(x,1);
						peaRefresh();
					}
				});
			});
			});
        }
    }
    localStorage.peatList = JSON.stringify(peat || []);
}


text:
title: "thank you"
bg: mainblue
color: white
fa-icon: users
---

### WHOEVER DELETES YOU, WE WILL FIND THEM!

### Get it **FREE** on the App Store


text:
import i18next from 'i18next';
import { $rootScope } from 'ngimport';
import * as _ from 'underscore';
import { SyncService } from '../storage/sync.service';
import store from '../store/store';
import { loaded } from './actions';
import { observeStore } from '../redux-utils';
import { Unsubscribe } from 'redux';
import { Settings, initialSettingsState } from './reducer';

let readyResolve;
export const settingsReady = new Promise((resolve) => (readyResolve = resolve));

// This is a backwards-compatibility shim for all the code that directly uses settings
export let settings = initialSettingsState;

const saveSettings = _.throttle((settings) => {
  return SyncService.set({
    'settings-v1.0': settings
  });
}, 1000);

function saveSettingsOnUpdate() {
  return observeStore(
    (state) => state.settings,
    (_currentState, nextState) => {
      settings = nextState;
      saveSettings(nextState);
    }
  );
}

let unsubscribe: Unsubscribe;

// Load settings async.
export function initSettings() {
  if (unsubscribe) {
    // Stop saving settings changes
    unsubscribe();
  }

  SyncService.get().then((data) => {
    data = data || {};

    const savedSettings = (data['settings-v1.0'] || {}) as Partial<Settings>;

    $rootScope.$evalAsync(() => {
      const languageChanged = savedSettings.language !== i18next.language;
      store.dispatch(loaded(savedSettings));
      const settings = store.getState().settings;
      localStorage.setItem('dimLanguage', settings.language);
      if (languageChanged) {
        i18next.changeLanguage(settings.language, () => {
          $rootScope.$applyAsync(() => {
            $rootScope.$broadcast('i18nextLanguageChange');
          });
        });
      }

      readyResolve();
      // Start saving settings changes
      unsubscribe = saveSettingsOnUpdate();
    });
  });
}


text:
require "routing/shared_examples"

describe "routing for OpsController" do
  let(:controller_name) { "ops" }

  %w(
    explorer
    fetch_audit_log
    fetch_build
    fetch_log
    fetch_production_log
    log_collection_form_fields
    log_protocol_changed
    schedule_form_fields
    show_product_update
  ).each do |task|
    describe "##{task}" do
      it 'routes with GET' do
        expect(get("/#{controller_name}/#{task}")).to route_to("#{controller_name}##{task}")
      end
    end
  end

  %w(
    accordion_select
    activate
    apply_imports
    ap_ce_delete
    ap_ce_select
    ap_edit
    ap_form_field_changed
    ap_set_active_tab
    aps_list
    category_delete
    category_edit
    category_field_changed
    category_update
    ce_accept
    ce_delete
    ce_new_cat
    ce_select
    change_tab
    cu_collection_field_changed
    cu_collection_update
    cu_repair
    cu_repair_field_changed
    db_backup
    db_backup_form_field_changed
    db_gc_collection
    db_list
    diagnostics_server_list
    diagnostics_tree_select
    diagnostics_worker_selected
    edit_rhn
    explorer
    fetch_build
    forest_accept
    forest_delete
    forest_form_field_changed
    forest_select
    log_depot_edit
    log_depot_field_changed
    log_depot_validate
    orphaned_records_delete
    perf_chart_chooser
    product_updates_list
    rbac_group_edit
    rbac_group_field_changed
    rbac_group_seq_edit
    rbac_group_user_lookup
    rbac_groups_list
    rbac_role_edit
    rbac_role_field_changed
    rbac_roles_list
    rbac_tags_edit
    rbac_tenants_list
    rbac_user_edit
    rbac_user_field_changed
    rbac_users_list
    region_edit
    region_form_field_changed
    repo_default_name
    restart_server
    rhn_buttons
    rhn_default_server
    rhn_validate
    schedule_edit
    schedule_form_field_changed
    schedule_form_filter_type_field_changed
    schedules_list
    schedule_update
    settings_form_field_changed
    settings_update
    show
    show_product_update
    smartproxy_affinity_field_changed
    tag_edit_form_field_changed
    tl_chooser
    tree_autoload_dynatree
    tree_select
    update
    upload_csv
    upload_form_field_changed
    upload_login_logo
    upload_logo
    validate_replcation_worker
    wait_for_task
    x_button
    x_show
    zone_edit
    zone_field_changed
  ).each do |task|
    describe "##{task}" do
      it 'routes with POST' do
        expect(post("/#{controller_name}/#{task}")).to route_to("#{controller_name}##{task}")
      end
    end
  end
end


text:
const fs = require('fs')
const path = require('path')
const unescape = require('lodash.unescape')
const PluginError = require('plugin-error')
const through = require('through2')
const nunjucks = require('nunjucks')
const frontMatter = require('front-matter')
const marked = require('marked')
const preferLocal = require('prefer-local')

let defaults = {
  path: '.',
  ext: '.html',
  extLayout: '.njk',
  data: {},
  useBlock: true,
  block: 'content',
  marked: null,
  escape: true,
  inheritExtension: false,
  envOptions: {
    watch: false
  },
  manageEnv: null
}

module.exports = options => {
  options = Object.assign({}, defaults, options)
  nunjucks.configure(options.envOptions)

  const compile = new nunjucks.Environment(new nunjucks.FileSystemLoader(options.path), options.envOptions)

  if (typeof (options.manageEnv) === 'function') {
    options.manageEnv.call(null, compile)
  }

  /*
   * file = file
   * cb   = callback function
   */
  return through.obj(function (file, enc, cb) {
    let data = {}
    if (typeof options.data === 'object') {
      data = Object.assign({}, options.data)
    } else {
      data = JSON.parse(fs.readFileSync(path.resolve(options.data), 'utf8'))
    }

    if (file.isNull()) {
      this.push(file)
      return cb()
    }

    if (file.data) {
      data = Object.assign({}, file.data, data)
    }

    if (file.isStream()) {
      this.emit('error', new PluginError('gulp-nunjucks-md', 'Streaming not supported'))
      return cb()
    }

    const isMarkdown = /\.md|\.markdown/.test(path.extname(file.path))
    const frontmatter = frontMatter(file.contents.toString())
    const haveAttributes = Object.keys(frontmatter.attributes).length
    let _fileContent = frontmatter.body
    // merge front-matter data
    if (haveAttributes) data = Object.assign({}, data, { page: frontmatter.attributes })
    // process markdown
    const _shouldEscape = preferLocal(data, 'page.escape', options.escape)
    if (isMarkdown) _fileContent = md(_fileContent, options, _shouldEscape)

    if (preferLocal(data, 'page.layout')) {
      const _canUseBlock = preferLocal(data, 'page.useBlock', options.useBlock)
      const _extendLayout = `{% extends "${data.page.layout}${options.extLayout}" %}`
      const _extendBlock = `{% block ${options.block} %}${_fileContent}{% endblock %}`
      _fileContent = `${_extendLayout} ${_canUseBlock ? _extendBlock : _fileContent}`
    } else if (haveAttributes) {
      this.emit('error', new PluginError('gulp-nunjucks-md', 'Layout not declared in front-matter or data'))
    }

    try {
      file.contents = Buffer.from(compile.renderString(_fileContent, data))
      // Replace extension with mentioned/default extension
      // only if inherit extension flag is not provided(truthy)
      if (!options.inheritExtension) {
        file.extname = options.ext
      }
      this.push(file)
    } catch (err) {
      this.emit('error', new PluginError('gulp-nunjucks-md', err, { fileName: file.path }))
    }
    cb()
  })
}

function md (text, options, _shouldEscape) {
  const render = new marked.Renderer()
  marked.setOptions(options.marked)
  render.text = text => unescape(text)
  return _shouldEscape ? marked(text) : marked(text, { renderer: render })
}

module.exports.setDefaults = function (options) {
  defaults = Object.assign({}, defaults, options)
}

module.exports.nunjucks = nunjucks


text:
/**
 * @fileoverview The <Bubble /> component renders a single message in the conversation thread.
 */

import React, { Component, PropTypes } from 'react';
import defaults from './defaults.js';
import { Author, Message, BubbleCSSClasses } from './types.js';

class Bubble extends Component {

  static propTypes = {
    shouldScroll: PropTypes.bool,
    author: Author,
    message: Message.isRequired,
    cssClasses: BubbleCSSClasses,
  };

  componentDidUpdate() {
    if (this.props.shouldScroll) {
      this.refs.bubble.scrollIntoView(false);
    }
  }

  render() {
    const { message, author, cssClasses } = this.props;
    const { contents } = message;
    const {
      position = defaults.position,
      color = defaults.color,
      background = defaults.background,
    } = author || {};
    // TODO: add support for more animations
    // const itemAnimation = 'item_slide_in_up';
    const itemClassName = `${position === 'left' ? cssClasses.left : cssClasses.right} item_slide_in_up`;
    return (

          {contents}

    );
  }
}

export default Bubble;


text:
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { Router } from '@angular/router';

import { MaterialModule } from '@angular/material';

import { AppComponent } from './app.component';
import { AppRoutingModule } from './app-routing.module';

import { HomeModule } from './home/home.module';
import { EmployeesModule } from './employees/employees.module';

import { DynamicFormModule } from './employees/forms/dynamic-reactive-form/dynamic-form.module';

import { RsInputComponent } from './fields/components/rs-input.component';
import { TestRsInputComponent } from './fields/samples/test-rs-input.component';

@NgModule({
  imports: [
    BrowserModule,
    FormsModule,
    MaterialModule.forRoot(),
    HomeModule,
    EmployeesModule,
    DynamicFormModule,
    AppRoutingModule
  ],
  declarations: [
    AppComponent,
    RsInputComponent,
    TestRsInputComponent
  ],
  bootstrap: [AppComponent]
})
export class AppModule {
  // Diagnostic only: inspect router configuration
  constructor(router: Router) {
    console.log('Routes: ', JSON.stringify(router.config, undefined, 2));
  }
}


text:
package org.ovirt.engine.core.bll;

import org.ovirt.engine.core.common.queries.GetHostsForStorageOperationParameters;

public class GetHostsForStorageOperationQuery<P extends GetHostsForStorageOperationParameters> extends QueriesCommandBase<P> {
    public GetHostsForStorageOperationQuery(P parameters) {
        super(parameters);
    }

    @Override
    protected void executeQueryCommand() {
        getQueryReturnValue().setReturnValue(getDbFacade().getVdsDao().getHostsForStorageOperation(
                getParameters().getId(), getParameters().isLocalFsOnly()));
    }
}


text:
Changelog
=========

1.1
-------
#. Add 1.7 compatible migration

1.0
-------
#. Change installation name


text:
package org.kie.workbench.common.screens.library.client.settings.sections.validation;

import org.guvnor.common.services.project.model.MavenRepositoryMetadata;
import org.guvnor.common.services.project.model.MavenRepositorySource;
import org.guvnor.common.services.project.model.ModuleRepositories;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;

import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyBoolean;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;

@RunWith(MockitoJUnitRunner.class)
public class ValidationItemPresenterTest {

    private ValidationItemPresenter validationItemPresenter;

    @Mock
    public ValidationItemView view;

    @Before
    public void before() {
        validationItemPresenter = spy(new ValidationItemPresenter(view));
    }

    @Test
    public void testSetup() {

        final ModuleRepositories.ModuleRepository projectRepository = mock(ModuleRepositories.ModuleRepository.class);
        final ValidationPresenter parentPresenter = mock(ValidationPresenter.class);

        doReturn(new MavenRepositoryMetadata("test",
                                             "https://test.url",
                                             MavenRepositorySource.LOCAL))
                .when(projectRepository).getMetadata();

        validationItemPresenter.setup(projectRepository,
                                      parentPresenter);

        verify(view).init(eq(validationItemPresenter));
        verify(view).setInclude(anyBoolean());
        verify(view).setId(any());
        verify(view).setUrl(any());
        verify(view).setSource(any());
    }

    @Test
    public void testSetInclude() {

        final ModuleRepositories.ModuleRepository projectRepository = mock(ModuleRepositories.ModuleRepository.class);
        final ValidationPresenter parentPresenter = mock(ValidationPresenter.class);

        validationItemPresenter.projectRepository = projectRepository;
        validationItemPresenter.parentPresenter = parentPresenter;

        validationItemPresenter.setInclude(true);

        verify(projectRepository).setIncluded(eq(true));
        verify(parentPresenter).fireChangeEvent();
    }
}


text:
package org.market.tool.bean;

import java.io.File;

import cn.bmob.v3.datatype.BmobFile;

public class MyBmobFile extends BmobFile {

	/**
	 *
	 */
	private static final long serialVersionUID = 1L;
	private String localFilePath;
	private int index;

	public MyBmobFile(File file){
		super(file);
	}

	public String getLocalFilePath() {
		return localFilePath;
	}

	public void setLocalFilePath(String localFilePath) {
		this.localFilePath = localFilePath;
	}

	public int getIndex() {
		return index;
	}

	public void setIndex(int index) {
		this.index = index;
	}

}


text:
<!DOCTYPE html>

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>Gentellela Alela! | </title>

    <link href="../vendors/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet">

    <link href="../vendors/font-awesome/css/font-awesome.min.css" rel="stylesheet">

    <link href="../vendors/nprogress/nprogress.css" rel="stylesheet">

    <link href="../vendors/google-code-prettify/bin/prettify.min.css" rel="stylesheet">

    <link href="../build/css/custom.min.css" rel="stylesheet">

               Gentellela Alela!

                Welcome,

John Doe

General

 Home

Dashboard

Dashboard2

Dashboard3

 Forms

General Form

Advanced Components

Form Validation

Form Wizard

Form Upload

Form Buttons

 UI Elements

General Elements

Media Gallery

Typography

Icons

Glyphicons

Widgets

Invoice

Inbox

Calendar

 Tables

Tables

Table Dynamic

 Data Presentation

Chart JS

Chart JS2

Moris JS

ECharts

Other Charts

Layouts

Fixed Sidebar

Fixed Footer

Live On

 Additional Pages

E-commerce

Projects

Project Detail

Contacts

Profile

 Extras

403 Error

404 Error

500 Error

Plain Page

Login Page

Pricing Tables

 Multilevel Menu

Level One

Level One

Level Two

Level Two

Level Two

Level One

 Landing Page Coming Soon

                    John Doe

 Profile

                        50%
                        Settings

Help

 Log Out

                    6

                          John Smith
                          3 mins ago

                          Film festivals used to be do-or-die moments for movie makers. They were where...

                          John Smith
                          3 mins ago

                          Film festivals used to be do-or-die moments for movie makers. They were where...

                          John Smith
                          3 mins ago

                          Film festivals used to be do-or-die moments for movie makers. They were where...

                          John Smith
                          3 mins ago

                          Film festivals used to be do-or-die moments for movie makers. They were where...

                          See All Alerts

Inbox Design Some examples to get you started

                    <input type="text" class="form-control" placeholder="Search for...">

                      <button class="btn btn-default" type="button">Go!</button>

Inbox DesignUser Mail

Settings 1

Settings 2

                        <button id="compose" class="btn btn-sm btn-success btn-block" type="button">COMPOSE</button>

Dennis Mugo 3.00 PM

Ut enim ad minim veniam, quis nostrud exercitation enim ad minim veniam, quis nostrud exercitation...

Jane Nobert 4.09 PM

To Ut enim ad minim veniam, quis nostrud exercitation enim ad minim veniam, quis nostrud exercitation...

Musimbi Anne 4.09 PM

CC Ut enim ad minim veniam, quis nostrud exercitation enim ad minim veniam, quis nostrud exercitation...

Jon Dibbs 4.09 PM

Ut enim ad minim veniam, quis nostrud exercitation enim ad minim veniam, quis nostrud exercitation...

                              .

Debbis & Raymond 4.09 PM

Ut enim ad minim veniam, quis nostrud exercitation enim ad minim veniam, quis nostrud exercitation...

                              .

Debbis & Raymond 4.09 PM

Ut enim ad minim veniam, quis nostrud exercitation enim ad minim veniam, quis nostrud exercitation...

Dennis Mugo 3.00 PM

Ut enim ad minim veniam, quis nostrud exercitation enim ad minim veniam, quis nostrud exercitation...

Jane Nobert 4.09 PM

Ut enim ad minim veniam, quis nostrud exercitation enim ad minim veniam, quis nostrud exercitation...

                                <button class="btn btn-sm btn-primary" type="button"> Reply</button>
                                <button class="btn btn-sm btn-default" type="button"  data-placement="top" data-toggle="tooltip" data-original-title="Forward"></button>
                                <button class="btn btn-sm btn-default" type="button" data-placement="top" data-toggle="tooltip" data-original-title="Print"></button>
                                <button class="btn btn-sm btn-default" type="button" data-placement="top" data-toggle="tooltip" data-original-title="Trash"></button>

 8:02 PM 12 FEB 2014

 Donec vitae leo at sem lobortis porttitor eu consequat risus. Mauris sed congue orci. Donec ultrices faucibus rutrum.

                                Jon Doe
                                (jon.doe@gmail.com) to
                                me

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
                              Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Riusmod tempor incididunt ut labor erem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris
                              nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt
                              mollit anim id est laborum.

Modesed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate
                              velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

                               3 attachments —
                              Download all attachments |
                              View all images

                                  image-name.jpg

                                12KB

                                  View -
                                  Download

                                  img_name.jpg

                                40KB

                                  View -
                                  Download

                                  img_name.jpg

                                30KB

                                  View -
                                  Download

                            <button class="btn btn-sm btn-primary" type="button"> Reply</button>
                            <button class="btn btn-sm btn-default" type="button"  data-placement="top" data-toggle="tooltip" data-original-title="Forward"></button>
                            <button class="btn btn-sm btn-default" type="button" data-placement="top" data-toggle="tooltip" data-original-title="Print"></button>
                            <button class="btn btn-sm btn-default" type="button" data-placement="top" data-toggle="tooltip" data-original-title="Trash"></button>

            Gentelella - Bootstrap Admin Template by Colorlib

        New Message
        <button type="button" class="close compose-close">
          ×
        </button>

Huge

Normal

Small

              <input class="span2" placeholder="URL" type="text" data-edit="createLink" />
              <button class="btn" type="button">Add</button>

            <input type="file" data-role="magic-overlay" data-target="#pictureBtn" data-edit="insertImage" />

        <button id="send" class="btn btn-sm btn-success" type="button">Send</button>

    >


text:
#ifndef _JPEG_FW_DEF_H_
#define _JPEG_FW_DEF_H_

#ifdef   __cplusplus
    extern   "C"
    {
#endif

#include "sci_types.h"
#include "jpeg_common.h"
//#include "jpeg_exif_header.h"

//#if !defined(_SIMULATION_)
//#include "os_api.h"
//#endif

typedef BOOLEAN (*JINF_READ_FILE_FUNC)(uint8 *buf, uint32 offset, uint32 bytes_to_read, uint32 *bytes_read_ptr);

/*function of write JPEG stream data or RGB data.*/
typedef BOOLEAN (*JINF_WRITE_FILE_FUNC)(uint8 *buf_ptr, uint32 file_offset, uint32 bytes_to_write, uint32 *written_bytes_ptr);

typedef struct yuv_format_tag
{
	uint8 	*y_data_ptr;
	uint8 	*u_data_ptr;
	uint8 	*v_data_ptr;
	uint32 	input_mcu_info;
	uint32  out_mcu_info;
	uint32	input_endian; //0: big, 1: little.
}YUV_FORMAT_T;

typedef struct mem_structure_tag
{
	void 	*buf_ptr;
	uint32 	 buf_size;
}JPEG_MEMORY_T;

typedef struct enc_input_para_tag
{
	uint32				width;
	uint32				height;
	uint8* 	 			stream_buf0;
	uint8*				stream_buf1;
	uint32 	 			bitstream_buf_len;
	YUV_FORMAT_T		yuv_0_info;
	YUV_FORMAT_T		yuv_1_info;
	JPEG_MEMORY_T		enc_buf;
	JPEG_QUALITY_E		quant_level;

	uint8				work_mode; //0: only encoder, 1: switch decoder and encoder.
	BOOLEAN				mbio_bfr0_valid; //0: invalid, 1: valid
	BOOLEAN				mbio_bfr1_valid; //0: invalid, 1: valid
	BOOLEAN 			bsm_buf0_valid;//0: invalid, 1: valid
	BOOLEAN				bsm_buf1_valid;//0: invalid, 1: valid
	BOOLEAN				is_first_slice;
	BOOLEAN				is_last_slice;
	uint32				restart_interval;
} JPEG_ENC_INPUT_PARA_T;

typedef struct enc_output_para_tag
{
	uint32   output_bitstream_size;
} JPEG_ENC_OUTPUT_PARA_T;

typedef struct jpeg_dec_input_param_tag
{
	uint16				data_type;				//0:RGB  1:YUV
	uint16	 			scaling_down_factor;
	uint8* 	 			pingpong_buf_0_ptr;
	uint8* 	 			pingpong_buf_1_ptr;
	uint32    				pingpong_buf_len;
	YUV_FORMAT_T		yuv_0_addr;			// yuv data address
	YUV_FORMAT_T		yuv_1_addr;			// yuv data address
	JPEG_MEMORY_T 		dec_buf;
	JPEG_QUALITY_E		quant_level;
	JINF_READ_FILE_FUNC  read_bitstream;
	BOOLEAN				progressive_mode;	//added by xiaowei.luo,20090113

	uint32				input_width;
	uint32				input_height;
	uint32				input_mcu_info;

	uint8				work_mode; //0: only decoder, 1: switch decoder and encoder.
	BOOLEAN				mbio_bfr0_valid; //0: invalid, 1: valid
	BOOLEAN				mbio_bfr1_valid; //0: invalid, 1: valid
	BOOLEAN 			bsm_buf0_valid;//0: invalid, 1: valid
	BOOLEAN				bsm_buf1_valid;//0: invalid, 1: valid

	BOOLEAN				is_first_slice;
	uint8*				bitstream_ptr;	//bitstream start address, contain the header.
	uint32    				bitstream_len;
	uint32				header_len;		//header length, return after parsing header.
}JPEG_DEC_INPUT_PARA_T;

typedef struct jpeg_dec_outputparam_tag
{
   	uint32 				output_width;		// width of output image
	uint32 				output_height;		// height of output image

}JPEG_DEC_OUTPUT_PARA_T;
typedef struct fraction_type
{
	uint32 numerator;
	uint32 denominator;
}FRACTION_TYPE_T;
typedef struct app1_t{
	uint32 thumb_width;
	uint32 thumb_height;
	uint32 thumbnail_len;
	void *thumbnail_virt_addr;
	FRACTION_TYPE_T Latitude_dd;
	FRACTION_TYPE_T Latitude_mm;
	FRACTION_TYPE_T Latitude_ss;
	uint32 Latitude_ref; //0: North latitude, 1: South latitude
	FRACTION_TYPE_T Longitude_dd;
	FRACTION_TYPE_T Longitude_mm;
	FRACTION_TYPE_T Longitude_ss;
	uint32 Longitude_ref; //0: East Longitude, 1: West Longitude
	const char *image_description;
	const char *make;
	const char *model;
	const char *copyright;
	uint32 orientation;
	const char *datetime;
	const char *gps_date;
	const char *gps_process_method;
	uint32 gps_hour;
	uint32 gps_minuter;
	uint32 gps_second;
	uint32 image_width;
	uint32 image_height;
	FRACTION_TYPE_T focal_length;

	uint32 	stream_buf_len;
//	JINF_EXIF_INFO_T *dc_exif_info_ptr;
}APP1_T;

///////////////////////////////////////////////////////////////////////////
//								Common									///
///////////////////////////////////////////////////////////////////////////

/*waiting the AHB master is idle*/
PUBLIC BOOLEAN	  JPEG_HWWaitingEnd(void);
/*reset the vsp*/
PUBLIC void		  JPEG_HWResetVSP(void);
/*set the bsm pingpang buffer can be read by hardware, for JPEG decoding*/
PUBLIC void		  JPEG_HWSet_BSM_Buf_ReadOnly(uint8 buf_id);
/*set the bsm pingpang buffer can be write by hardware, for JPEG encoding*/
PUBLIC void		  JPEG_HWSet_BSM_Buf_WriteOnly(uint8 buf_id);
/*set the mbio pingpang buffer can be read by hardware, for JPEG encoding*/
PUBLIC void		  JPEG_HWSet_MBIO_Buf_ReadOnly(uint8 buf_id);
/*set the mbio pingpang buffer can be write by hardware, for JPEG decoding*/
PUBLIC void		  JPEG_HWSet_MBIO_Buf_WriteOnly(uint8 buf_id);

///////////////////////////////////////////////////////////////////////////
//								Decode									///
///////////////////////////////////////////////////////////////////////////

/*head parsing by firmware*/
PUBLIC JPEG_RET_E JPEG_FWParseHead(JPEG_DEC_INPUT_PARA_T *input_para_ptr);

/*initialization of firmware when normal jpeg picture decoding*/
PUBLIC JPEG_RET_E JPEG_HWDecInit(JPEG_DEC_INPUT_PARA_T *input_para_ptr);

/*jpeg decoding by hardware*/
PUBLIC JPEG_RET_E JPEG_HWDecStart(uint32 num_of_rows, JPEG_DEC_OUTPUT_PARA_T *output_para_ptr);

/*decode defined number of MCU according to synchronism mode by hardware*/
PUBLIC JPEG_RET_E JPEG_HWDecStartMCUSynchro(uint32 num_of_rows, JPEG_DEC_OUTPUT_PARA_T *output_para_ptr);

/*read out bitstream information when current slice decoding is finished. only used in switch mode*/
PUBLIC JPEG_RET_E JpegDec_FwReadoutDecInfo(uint32 *bitstrm_byte_offset_ptr, uint32 bitstrm_bfr_switch_cnt);

/*close decoder and release resource*/
PUBLIC void JpegDec_FwClose(JPEG_DEC_INPUT_PARA_T *jpeg_dec_input);

PUBLIC void JpegDec_BackupLast100ByteBs(uint8 *bitstrm_ptr, uint32 pingpang_buf_len)	;

PUBLIC JPEG_RET_E JpegDec_SetFlushWordFlag(int32 flag);

///////////////////////////////////////////////////////////////////////////
//								Encode									///
///////////////////////////////////////////////////////////////////////////

/*initialization of encoding by hardware*/
PUBLIC JPEG_RET_E JPEG_HWEncInit(JPEG_ENC_INPUT_PARA_T *input_para_ptr);

/*head writting by hardware*/
PUBLIC JPEG_RET_E JPEG_HWWriteHead(APP1_T *app1_t);
//PUBLIC JPEG_RET_E JPEG_HWWriteHead(void);
PUBLIC JPEG_RET_E JPEG_HWWriteHeadForThumbnail(void);

/*tail writting by hardware*/
PUBLIC JPEG_RET_E JPEG_HWWriteTail(void);
PUBLIC JPEG_RET_E JPEG_HWWriteTailForThumbnail(void);

/*start the hardware to encode the jpeg*/
PUBLIC JPEG_RET_E JPEG_HWEncStart(uint32 width, uint32 height, JPEG_ENC_OUTPUT_PARA_T *output_para_ptr);

/*obtain the encoded size of bitstream*/
PUBLIC uint32	JPEG_HWGetSize(void);

/*close encoder and release resource*/
PUBLIC void JpegEnc_FwClose(JPEG_ENC_INPUT_PARA_T *jpeg_enc_input);

PUBLIC void JPEG_HWUpdateMBIOBufInfo(void);
PUBLIC void JPEGDEC_HWUpdateMBIOBufInfo(void);

/**---------------------------------------------------------------------------*
**                         Compiler Flag                                      *
**---------------------------------------------------------------------------*/
#ifdef   __cplusplus
    }
#endif
/**---------------------------------------------------------------------------*/
// End
#endif


text:
using namespace Halide;

int main(int argc, char **argv) {
    const Buffer<> foo;
    foo.raw_buffer();

    printf("I should not have reached here\n");
    return 0;
}


text:
//==============================================================================
//         Copyright 2003 - 2012   LASMEA UMR 6602 CNRS/Univ. Clermont II
//         Copyright 2009 - 2012   LRI    UMR 8623 CNRS/Univ Paris Sud XI
//
//          Distributed under the Boost Software License, Version 1.0.
//                 See accompanying file LICENSE.txt or copy at
//                     http://www.boost.org/LICENSE_1_0.txt
//==============================================================================
#ifndef NT2_POLYNOM_FUNCTIONS_POLYVALM_HPP_INCLUDED
#define NT2_POLYNOM_FUNCTIONS_POLYVALM_HPP_INCLUDED
#include <nt2/include/functor.hpp>
#include <nt2/sdk/meta/size_as.hpp>
#include <nt2/sdk/meta/value_as.hpp>
#include <nt2/core/container/dsl/size.hpp>
#include <nt2/sdk/meta/tieable_hierarchy.hpp>
#include <nt2/core/container/dsl/value_type.hpp>

namespace nt2 { namespace tag
  {
   /*!
     @brief polyvalm generic tag

     Represents the polyvalm function in generic contexts.

     @par Models:
        Hierarchy
   **/
    struct polyvalm_ : ext::unspecified_<polyvalm_>
    {
      /// @brief Parent hierarchy
      typedef ext::unspecified_<polyvalm_> parent;
    };
  }
  /*!
    computes the value of a polynomial p at a square matrix a using matricial product.
    the polynomial is supposed to be given by an array coefficients
    in decreasing degrees order

    @par Semantic:

    For every expression p representing and a representing a square matrix

    @code
    auto r = polyvalm(p, a);
    @endcode

    Computes \f$\displaystyle \sum_0^n p_i \mbox{mpow}(a, i)\f$.

    @see @funcref{mpower}
    @param a0

    @param a1

    @return an expression
  **/
  NT2_FUNCTION_IMPLEMENTATION(tag::polyvalm_, polyvalm, 2)

}

 namespace nt2 { namespace ext
{
  /// INTERNAL ONLY
  template<class Domain, int N, class Expr>
  struct  size_of<tag::polyvalm_,Domain,N,Expr>
  {
    typedef typename  boost::proto::result_of::child_c<Expr&,1>::value_type::extent_type result_type;

    BOOST_FORCEINLINE result_type operator()(Expr& e) const
    {
      return boost::proto::child_c<1>(e).extent();
    }
  };

  /// INTERNAL ONLY
  template<class Domain, int N, class Expr>
  struct  value_type<tag::polyvalm_,Domain,N,Expr>
        : meta::value_as<Expr,0>
  {};
} }
#endif


text:
package org.clulab.processors

class TestUniversalEnhancedDependencies extends FatdynetTest {

  "CluProcessor" should "parse some basic sentences correctly" in {
    var doc = proc.annotate("Ras1 is associated with cancer.")
    doc.sentences.head.universalBasicDependencies.get.hasEdge(2, 0, "nsubjpass") should be(true)
    doc.sentences.head.universalBasicDependencies.get.hasEdge(2, 1, "auxpass") should be(true)

    doc = proc.annotate("Ras1 has phosphorylated Mek2.")
    doc.sentences.head.universalBasicDependencies.get.hasEdge(2, 0, "nsubj") should be(true)
    doc.sentences.head.universalBasicDependencies.get.hasEdge(2, 1, "aux") should be(true)

    doc = proc.annotate("John has travelled to China.")
    doc.sentences.head.universalBasicDependencies.get.hasEdge(2, 0, "nsubj") should be(true)
    doc.sentences.head.universalBasicDependencies.get.hasEdge(2, 1, "aux") should be(true)
    doc.sentences.head.universalBasicDependencies.get.hasEdge(2, 4, "nmod") should be(true)
    doc.sentences.head.universalBasicDependencies.get.hasEdge(4, 3, "case") should be(true)

    doc = proc.annotate("John is traveling to China.")
    doc.sentences.head.universalBasicDependencies.get.hasEdge(2, 0, "nsubj") should be(true)
    doc.sentences.head.universalBasicDependencies.get.hasEdge(2, 1, "aux") should be(true)
    doc.sentences.head.universalBasicDependencies.get.hasEdge(2, 4, "nmod") should be(true)
    doc.sentences.head.universalBasicDependencies.get.hasEdge(4, 3, "case") should be(true)

    doc = proc.annotate("John Doe will travel to China.")
    doc.sentences.head.universalBasicDependencies.get.hasEdge(3, 1, "nsubj") should be(true)
    doc.sentences.head.universalBasicDependencies.get.hasEdge(1, 0, "compound") should be(true)
    doc.sentences.head.universalBasicDependencies.get.hasEdge(3, 2, "aux") should be(true)
    doc.sentences.head.universalBasicDependencies.get.hasEdge(3, 5, "nmod") should be(true)
    doc.sentences.head.universalBasicDependencies.get.hasEdge(5, 4, "case") should be(true)

    doc = proc.annotate("Mary has been reading a book")
    doc.sentences.head.universalBasicDependencies.get.hasEdge(3, 0, "nsubj") should be(true)
    doc.sentences.head.universalBasicDependencies.get.hasEdge(3, 1, "aux") should be(true)
    doc.sentences.head.universalBasicDependencies.get.hasEdge(3, 2, "aux") should be(true)
    doc.sentences.head.universalBasicDependencies.get.hasEdge(3, 5, "dobj") should be(true)

    doc = proc.annotate("Mary is reading a book.")
    doc.sentences.head.universalBasicDependencies.get.hasEdge(2, 0, "nsubj") should be(true)
    doc.sentences.head.universalBasicDependencies.get.hasEdge(2, 1, "aux") should be(true)
    doc.sentences.head.universalBasicDependencies.get.hasEdge(2, 4, "dobj") should be(true)

    doc = proc.annotate("Paul and Mary are reading a book.")
    doc.sentences.head.universalBasicDependencies.get.hasEdge(4, 0, "nsubj") should be(true)
    doc.sentences.head.universalBasicDependencies.get.hasEdge(0, 2, "conj") should be(true)
    doc.sentences.head.universalBasicDependencies.get.hasEdge(4, 3, "aux") should be(true)
    doc.sentences.head.universalBasicDependencies.get.hasEdge(4, 6, "dobj") should be(true)
  }

  it should "collapse prepositions" in {
    val doc = proc.annotate("Mary traveled to China")
    doc.sentences.head.universalEnhancedDependencies.get.hasEdge(1, 3, "nmod_to") should be(true)
    doc.sentences.head.universalEnhancedDependencies.get.hasEdge(1, 2, "nmod") should be(false)
    doc.sentences.head.universalEnhancedDependencies.get.hasEdge(3, 2, "case") should be(true)
  }

  it should "identify agents in passive voice" in {
    val doc = proc.annotate("Mary was congratulated by Jane")
    doc.sentences.head.universalEnhancedDependencies.get.hasEdge(2, 4, "nmod_by") should be(true)
    doc.sentences.head.universalEnhancedDependencies.get.hasEdge(2, 0, "nsubjpass") should be(true)
  }

  it should "capture raised subjects" in {
    val doc = proc.annotate("Mary wants to buy a book")
    doc.sentences.head.universalEnhancedDependencies.get.hasEdge(3, 0, "nsubj") should be(true)
  }

  it should "propagate subjects and objects in conjoined verbs" in {
    var doc = proc.annotate("The store buys and sells cameras.")
    doc.sentences.head.universalEnhancedDependencies.get.hasEdge(2, 1, "nsubj") should be(true)
    doc.sentences.head.universalEnhancedDependencies.get.hasEdge(4, 1, "nsubj") should be(true)
    doc.sentences.head.universalEnhancedDependencies.get.hasEdge(4, 5, "dobj") should be(true)
    doc.sentences.head.universalEnhancedDependencies.get.hasEdge(2, 5, "dobj") should be(true)

    doc = proc.annotate("Cameras are bought and sold by the store")
    doc.sentences.head.universalEnhancedDependencies.get.hasEdge(2, 0, "nsubjpass") should be(true)
    doc.sentences.head.universalEnhancedDependencies.get.hasEdge(4, 0, "nsubjpass") should be(true)
    doc.sentences.head.universalEnhancedDependencies.get.hasEdge(2, 7, "nmod_by") should be(true)
    doc.sentences.head.universalEnhancedDependencies.get.hasEdge(4, 7, "nmod_by") should be(true)

    doc = proc.annotate("She was watching a movie or reading a book")
    doc.sentences.head.universalEnhancedDependencies.get.hasEdge(2, 0, "nsubj") should be(true)
    //doc.sentences.head.universalEnhancedDependencies.get.hasEdge(6, 0, "nsubj") should be(true) // TODO: this currently fails with CluProcessor, because the conj is incorrectly assigned between 4 and 6 (rather than 2 and 6)
    doc.sentences.head.universalEnhancedDependencies.get.hasEdge(2, 4, "dobj") should be(true)
    doc.sentences.head.universalEnhancedDependencies.get.hasEdge(6, 8, "dobj") should be(true)

    doc = proc.annotate("She was watching a movie or reading")
    doc.sentences.head.universalEnhancedDependencies.get.hasEdge(6, 4, "dobj") should be(false)
  }

  it should "propagate conjoined subjects and objects to same verb" in {
    var doc = proc.annotate("Paul and Mary are reading a book")
    doc.sentences.head.universalEnhancedDependencies.get.hasEdge(4, 0, "nsubj") should be(true)
    doc.sentences.head.universalEnhancedDependencies.get.hasEdge(4, 2, "nsubj") should be(true)

    doc = proc.annotate("John is reading a book and a newspaper")
    doc.sentences.head.universalEnhancedDependencies.get.hasEdge(2, 4, "dobj") should be(true)
    doc.sentences.head.universalEnhancedDependencies.get.hasEdge(2, 7, "dobj") should be(true)

    doc = proc.annotate("Mary and John wanted to buy a hat")
    doc.sentences.head.universalEnhancedDependencies.get.hasEdge(3, 0, "nsubj") should be(true)
    doc.sentences.head.universalEnhancedDependencies.get.hasEdge(3, 2, "nsubj") should be(true)
    doc.sentences.head.universalEnhancedDependencies.get.hasEdge(5, 0, "nsubj") should be(true)
    doc.sentences.head.universalEnhancedDependencies.get.hasEdge(5, 2, "nsubj") should be(true)
  }

  it should "push subjects/objects inside relative clauses" in {
    var doc = proc.annotate("the boy who lived") // FAIL
    doc.sentences.head.universalEnhancedDependencies.get.hasEdge(3, 1, "nsubj") should be(true)
    doc.sentences.head.universalEnhancedDependencies.get.hasEdge(3, 2, "nsubj") should be(false)

    doc = proc.annotate("the book, which I read, was great.")
    doc.sentences.head.universalEnhancedDependencies.get.hasEdge(5, 4, "nsubj") should be(true)
    doc.sentences.head.universalEnhancedDependencies.get.hasEdge(5, 1, "dobj") should be(true)
    doc.sentences.head.universalEnhancedDependencies.get.hasEdge(5, 3, "dobj") should be(false)
  }

  it should "generate correct conj_ dependencies" in {
    var doc = proc.annotate("Disagreements over land rights for crop cultivation and livestock grazing continue to be a major source of conflict.")
    doc.sentences.head.universalEnhancedDependencies.get.hasEdge(6, 9, "conj_and") should be(true)

    doc = proc.annotate("Because of this inadequate transportation infrastructure, it is difficult and expensive for subsistence farmers to transport surpluses to markets.")
    doc.sentences.head.universalEnhancedDependencies.get.hasEdge(9, 11, "conj_and") should be(true)

    doc = proc.annotate("Use of improved cultivars and mechanization will be increased and use of critical interventions may lead to increases in productivity and efficient use of resources.")
    doc.sentences.head.universalEnhancedDependencies.get.hasEdge(3, 5, "conj_and") should be(true)
    doc.sentences.head.universalEnhancedDependencies.get.hasEdge(8, 15, "ccomp") should be(true)
    doc.sentences.head.universalEnhancedDependencies.get.hasEdge(19, 21, "conj_and") should be(true) // this is not great, but better than nothing...
  }

  it should "create xsubj dependencies" in {
    val doc = proc.annotate("Disagreements over land rights for crop cultivation and livestock grazing continue to be a major source of conflict.")
    doc.sentences.head.universalEnhancedDependencies.get.hasEdge(0, 15, "nsubj:xsubj") should be(true)
  }

  it should "replicate copulative nsubj across conjunctions" in {
    val doc = proc.annotate("Because of this inadequate transportation infrastructure, it is difficult and expensive for subsistence farmers to transport surpluses to markets.")
    doc.sentences.head.universalEnhancedDependencies.get.hasEdge(9, 7, "nsubj") should be(true)
    doc.sentences.head.universalEnhancedDependencies.get.hasEdge(11, 7, "nsubj") should be(true)
  }

  it should "replicate nmod_ dependencies across conjunctions" in {
    var doc = proc.annotate("Conflict and economic decline have led to violence and displacement.")
    doc.sentences.head.universalEnhancedDependencies.get.hasEdge(5, 7, "nmod_to") should be(true)
    doc.sentences.head.universalEnhancedDependencies.get.hasEdge(5, 9, "nmod_to") should be(true)

    doc = proc.annotate("Use of improved cultivars and mechanization will be increased and use of critical interventions may lead to increases in productivity and efficient use of resources.")
    doc.sentences.head.universalEnhancedDependencies.get.hasEdge(0, 3, "nmod_of") should be(true)
    doc.sentences.head.universalEnhancedDependencies.get.hasEdge(0, 5, "nmod_of") should be(true)
  }
}


text:
package com.intellij.compiler.options;

import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleType;

import javax.swing.*;
import javax.swing.table.DefaultTableCellRenderer;
import java.awt.*;

public class ModuleTableCellRenderer extends DefaultTableCellRenderer {
  @Override
  public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
    try {
      return super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
    }
    finally {
      final Module module = (Module)value;
      if (module != null) {
        setText(module.getName());
        setIcon(ModuleType.get(module).getIcon());
      }
      else {
        setText("");
        setIcon(null);
      }
    }
  }
}


text:
GLFWwindow *v_frame;
void glClear(GLenum);
void glFinish();
void glClearColor(GLclampf, GLclampf, GLclampf, GLclampf);
void glBlendFunc(GLenum, GLenum);
void glEnable(GLenum);
void glGetIntegerv(GLenum, GLint *);
void glViewport(GLint, GLint, GLint, GLint);

int scrw;
int scrh;

void V_visualinit()
{
	int vp[4];
	if(!glfwInit())
	{
		printf("glfw init failed\n");
		exit(-1);
	}
	glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
	glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
	glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
	glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
	v_frame = glfwCreateWindow(1366, 768, "toasterdev v1s", glfwGetPrimaryMonitor(), '\0');
	if(!v_frame)
	{
		printf("failed to create OpenGL 3.3 context\n");
		glfwTerminate();
		exit(-1);
	}
	glfwMakeContextCurrent(v_frame);
	glfwSwapInterval(0);
	glGetIntegerv(GL_VIEWPORT, vp);
	scrw = vp[2];
	scrh = vp[3];
	V_memoryinit();
	V_bufferinit();
	V_modelinit();
	V_textureinit();
	V_programinit();
	V_loaderinit();
	V_entityinit();
	glEnable(GL_BLEND);
	glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
	glClearColor(0.1f, 0.3f, 0.3f, 1.f);
	glViewport(0, 0, scrw, scrh);
}

void V_usearg()
{
	//can either pass an argument index or the argument string
	//one common argument could be to load a file
	//this requires two strings, but if the first string is passed
	//the program won't know where to look for the second string
	//two versions of the function, one for single argument args
	//one for args that require two strings
}

void V_update()
{
	V_render();
}

void V_visualclose()
{
	V_entityclose();
	V_loaderclose();
	V_programclose();
	V_textureclose();
	V_modelclose();
	V_bufferclose();
	V_memoryclose();
	if(v_frame)
	{
		glfwTerminate();
		v_frame = '\0';
	}
}

void V_render()
{
	glClear(GL_COLOR_BUFFER_BIT);

	glFlush();
	glfwSwapBuffers(v_frame);
}


text:
import { loadConfigSync } from '@common/util/config-loader'

describe('readConfigSync', () => {
  it('1', () => {
    const config = loadConfigSync('config/config-test.json')
    expect(config.appName).toBe('Test')
    expect(config.appNamel).toBe('test')
  })
  it('if file not found', () => {
    expect(() => {
      loadConfigSync('config/not-exist.json')
    }).toThrow()
  })
})


text:
ICA_TESTRUNNING="TestRunning"      # The test is running
ICA_TESTCOMPLETED="TestCompleted"  # The test completed successfully
ICA_TESTABORTED="TestAborted"      # ERROR during setup of test
ICA_TESTFAILED="TestFailed"        # ERROR during test

CONSTANTS_FILE="constants.sh"
LogMsg()
{
    echo `date "+%a %b %d %T %Y"` : ${1}    # To add the time-stamp to the log file
}

UpdateTestState()
{
    echo $1 > ~/state.txt
}

#
# Create the state.txt file so ICA knows we are running
#
LogMsg "Updating test case state to running"
UpdateTestState $ICA_TESTRUNNING

#
# Source the constants.sh file
#
if [ -e ./${CONSTANTS_FILE} ]; then
    source ${CONSTANTS_FILE}
else
    echo "Warn : no ${CONSTANTS_FILE} found"
fi

if [ -e ~/summary.log ]; then
    rm -rf ~/summary.log
fi

# Convert eol
dos2unix perf_utils.sh

# Source perf_utils.sh
. perf_utils.sh || {
    echo "ERROR: unable to source perf_utils.sh!"
    echo "TestAborted" > state.txt
    exit 2
}

# Convert eol
dos2unix utils.sh

# Source perf_utils.sh
. utils.sh || {
    echo "ERROR: unable to source utils.sh!"
    echo "TestAborted" > state.txt
    exit 2
}

# Applying performance parameters
setup_io_scheduler
if [ $? -ne 0 ]; then
    echo "Unable to add performance parameters."
    LogMsg "Unable to add performance parameters."
    UpdateTestState $ICA_TESTABORTED
fi

echo "Kernel version: $(uname -r)" >> ~/summary.log

# Get distro
GetDistro

case "$DISTRO" in
    "UBUNTU")
        LogMsg "Run test on Ubuntu. Install dependencies..."
        apt update
        apt -y install make gcc mdadm libaio-dev
        sts=$?
        if [ 0 -ne ${sts} ]; then
            echo "Failed to install the dependencies!" >> ~/summary.log
            UpdateTestState $ICA_TESTABORTED
            exit 41
        fi
        # Disable multipath so that it doesn't lock the disks
         if [ -e /etc/multipath.conf ]; then
            rm /etc/multipath.conf
        fi
        echo -e "blacklist {\n\tdevnode \"^sd[a-z]\"\n}" >> /etc/multipath.conf
        service multipath-tools reload
        service multipath-tools restart

    ;;
    "RHEL"|"CENTOS")
        LogMsg "Run test on RHEL. Install dependencies..."
        yum -y install libaio-devel mdadm zlib-dev
        sts=$?
        if [ 0 -ne ${sts} ]; then
            echo "Failed to install the dependencies!" >> ~/summary.log
            UpdateTestState $ICA_TESTABORTED
            exit 41
        fi
    ;;
    "SLES")
        LogMsg "Run test on SLES. Install dependencies..."
        zypper --non-interactive install libaio-devel mdadm
        sts=$?
        if [ 0 -ne ${sts} ]; then
            echo "Failed to install the dependencies!" >> ~/summary.log
            UpdateTestState $ICA_TESTABORTED
            exit 41
        fi
    ;;
esac

# Setup FIO-tool
setup_fio
if [ $? -ne 0 ]; then
    LogMsg "ERROR: FIO failed."
    echo "ERROR: FIO failed." >> ~/summary.log
    UpdateTestState $ICA_TESTABORTED
fi

# Run FIO
if [ "${TC_COVERED}" == "FIO" ]; then
    echo "INFO: Run FIO on single disk."
    fio_single_disk
        if [ $? -ne 0 ]; then
            LogMsg "ERROR: Unable to run FIO."
            echo "ERROR: Unable to run FIO." >> ~/summary.log
            UpdateTestState $ICA_TESTABORTED
        fi
else
    echo "INFO: Run FIO on multiple disks."
    fio_raid
    if [ $? -ne 0 ]; then
        LogMsg "ERROR: Unable to run FIO."
        echo "ERROR: Unable to run FIO." >> ~/summary.log
        UpdateTestState $ICA_TESTABORTED
     fi
fi

LogMsg "FIO test completed successfully"
echo "FIO test completed successfully" >> ~/summary.log

LogMsg "Updating test case state to completed"
UpdateTestState $ICA_TESTCOMPLETED


text:
// Package webhook implements the authorizer.Authorizer interface using HTTP webhooks.
package webhook

import (
	"context"
	"encoding/json"
	"fmt"
	"time"

	"k8s.io/klog"

	authorization "k8s.io/api/authorization/v1beta1"
	"k8s.io/apimachinery/pkg/runtime"
	"k8s.io/apimachinery/pkg/runtime/schema"
	"k8s.io/apimachinery/pkg/util/cache"
	"k8s.io/apiserver/pkg/authentication/user"
	"k8s.io/apiserver/pkg/authorization/authorizer"
	"k8s.io/apiserver/pkg/util/webhook"
	"k8s.io/client-go/kubernetes/scheme"
	authorizationclient "k8s.io/client-go/kubernetes/typed/authorization/v1beta1"
)

var (
	groupVersions = []schema.GroupVersion{authorization.SchemeGroupVersion}
)

const (
	retryBackoff = 500 * time.Millisecond
	// The maximum length of requester-controlled attributes to allow caching.
	maxControlledAttrCacheSize = 10000
)

// Ensure Webhook implements the authorizer.Authorizer interface.
var _ authorizer.Authorizer = (*WebhookAuthorizer)(nil)

type WebhookAuthorizer struct {
	subjectAccessReview authorizationclient.SubjectAccessReviewInterface
	responseCache       *cache.LRUExpireCache
	authorizedTTL       time.Duration
	unauthorizedTTL     time.Duration
	initialBackoff      time.Duration
	decisionOnError     authorizer.Decision
}

// NewFromInterface creates a WebhookAuthorizer using the given subjectAccessReview client
func NewFromInterface(subjectAccessReview authorizationclient.SubjectAccessReviewInterface, authorizedTTL, unauthorizedTTL time.Duration) (*WebhookAuthorizer, error) {
	return newWithBackoff(subjectAccessReview, authorizedTTL, unauthorizedTTL, retryBackoff)
}

// New creates a new WebhookAuthorizer from the provided kubeconfig file.
//
// The config's cluster field is used to refer to the remote service, user refers to the returned authorizer.
//
//     # clusters refers to the remote service.
//     clusters:
//     - name: name-of-remote-authz-service
//       cluster:
//         certificate-authority: /path/to/ca.pem      # CA for verifying the remote service.
//         server: https://authz.example.com/authorize # URL of remote service to query. Must use 'https'.
//
//     # users refers to the API server's webhook configuration.
//     users:
//     - name: name-of-api-server
//       user:
//         client-certificate: /path/to/cert.pem # cert for the webhook plugin to use
//         client-key: /path/to/key.pem          # key matching the cert
//
// For additional HTTP configuration, refer to the kubeconfig documentation
// https://kubernetes.io/docs/user-guide/kubeconfig-file/.
func New(kubeConfigFile string, authorizedTTL, unauthorizedTTL time.Duration) (*WebhookAuthorizer, error) {
	subjectAccessReview, err := subjectAccessReviewInterfaceFromKubeconfig(kubeConfigFile)
	if err != nil {
		return nil, err
	}
	return newWithBackoff(subjectAccessReview, authorizedTTL, unauthorizedTTL, retryBackoff)
}

// newWithBackoff allows tests to skip the sleep.
func newWithBackoff(subjectAccessReview authorizationclient.SubjectAccessReviewInterface, authorizedTTL, unauthorizedTTL, initialBackoff time.Duration) (*WebhookAuthorizer, error) {
	return &WebhookAuthorizer{
		subjectAccessReview: subjectAccessReview,
		responseCache:       cache.NewLRUExpireCache(1024),
		authorizedTTL:       authorizedTTL,
		unauthorizedTTL:     unauthorizedTTL,
		initialBackoff:      initialBackoff,
		decisionOnError:     authorizer.DecisionNoOpinion,
	}, nil
}

// Authorize makes a REST request to the remote service describing the attempted action as a JSON
// serialized api.authorization.v1beta1.SubjectAccessReview object. An example request body is
// provided below.
//
//     {
//       "apiVersion": "authorization.k8s.io/v1beta1",
//       "kind": "SubjectAccessReview",
//       "spec": {
//         "resourceAttributes": {
//           "namespace": "kittensandponies",
//           "verb": "GET",
//           "group": "group3",
//           "resource": "pods"
//         },
//         "user": "jane",
//         "group": [
//           "group1",
//           "group2"
//         ]
//       }
//     }
//
// The remote service is expected to fill the SubjectAccessReviewStatus field to either allow or
// disallow access. A permissive response would return:
//
//     {
//       "apiVersion": "authorization.k8s.io/v1beta1",
//       "kind": "SubjectAccessReview",
//       "status": {
//         "allowed": true
//       }
//     }
//
// To disallow access, the remote service would return:
//
//     {
//       "apiVersion": "authorization.k8s.io/v1beta1",
//       "kind": "SubjectAccessReview",
//       "status": {
//         "allowed": false,
//         "reason": "user does not have read access to the namespace"
//       }
//     }
//
// TODO(mikedanese): We should eventually support failing closed when we
// encounter an error. We are failing open now to preserve backwards compatible
// behavior.
func (w *WebhookAuthorizer) Authorize(ctx context.Context, attr authorizer.Attributes) (decision authorizer.Decision, reason string, err error) {
	r := &authorization.SubjectAccessReview{}
	if user := attr.GetUser(); user != nil {
		r.Spec = authorization.SubjectAccessReviewSpec{
			User:   user.GetName(),
			UID:    user.GetUID(),
			Groups: user.GetGroups(),
			Extra:  convertToSARExtra(user.GetExtra()),
		}
	}

	if attr.IsResourceRequest() {
		r.Spec.ResourceAttributes = &authorization.ResourceAttributes{
			Namespace:   attr.GetNamespace(),
			Verb:        attr.GetVerb(),
			Group:       attr.GetAPIGroup(),
			Version:     attr.GetAPIVersion(),
			Resource:    attr.GetResource(),
			Subresource: attr.GetSubresource(),
			Name:        attr.GetName(),
		}
	} else {
		r.Spec.NonResourceAttributes = &authorization.NonResourceAttributes{
			Path: attr.GetPath(),
			Verb: attr.GetVerb(),
		}
	}
	key, err := json.Marshal(r.Spec)
	if err != nil {
		return w.decisionOnError, "", err
	}
	if entry, ok := w.responseCache.Get(string(key)); ok {
		r.Status = entry.(authorization.SubjectAccessReviewStatus)
	} else {
		var (
			result *authorization.SubjectAccessReview
			err    error
		)
		webhook.WithExponentialBackoff(ctx, w.initialBackoff, func() error {
			result, err = w.subjectAccessReview.CreateContext(ctx, r)
			return err
		})
		if err != nil {
			// An error here indicates bad configuration or an outage. Log for debugging.
			klog.Errorf("Failed to make webhook authorizer request: %v", err)
			return w.decisionOnError, "", err
		}
		r.Status = result.Status
		if shouldCache(attr) {
			if r.Status.Allowed {
				w.responseCache.Add(string(key), r.Status, w.authorizedTTL)
			} else {
				w.responseCache.Add(string(key), r.Status, w.unauthorizedTTL)
			}
		}
	}
	switch {
	case r.Status.Denied && r.Status.Allowed:
		return authorizer.DecisionDeny, r.Status.Reason, fmt.Errorf("webhook subject access review returned both allow and deny response")
	case r.Status.Denied:
		return authorizer.DecisionDeny, r.Status.Reason, nil
	case r.Status.Allowed:
		return authorizer.DecisionAllow, r.Status.Reason, nil
	default:
		return authorizer.DecisionNoOpinion, r.Status.Reason, nil
	}

}

//TODO: need to finish the method to get the rules when using webhook mode
func (w *WebhookAuthorizer) RulesFor(user user.Info, namespace string) ([]authorizer.ResourceRuleInfo, []authorizer.NonResourceRuleInfo, bool, error) {
	var (
		resourceRules    []authorizer.ResourceRuleInfo
		nonResourceRules []authorizer.NonResourceRuleInfo
	)
	incomplete := true
	return resourceRules, nonResourceRules, incomplete, fmt.Errorf("webhook authorizer does not support user rule resolution")
}

func convertToSARExtra(extra map[string][]string) map[string]authorization.ExtraValue {
	if extra == nil {
		return nil
	}
	ret := map[string]authorization.ExtraValue{}
	for k, v := range extra {
		ret[k] = authorization.ExtraValue(v)
	}

	return ret
}

// subjectAccessReviewInterfaceFromKubeconfig builds a client from the specified kubeconfig file,
// and returns a SubjectAccessReviewInterface that uses that client. Note that the client submits SubjectAccessReview
// requests to the exact path specified in the kubeconfig file, so arbitrary non-API servers can be targeted.
func subjectAccessReviewInterfaceFromKubeconfig(kubeConfigFile string) (authorizationclient.SubjectAccessReviewInterface, error) {
	localScheme := runtime.NewScheme()
	if err := scheme.AddToScheme(localScheme); err != nil {
		return nil, err
	}
	if err := localScheme.SetVersionPriority(groupVersions...); err != nil {
		return nil, err
	}

	gw, err := webhook.NewGenericWebhook(localScheme, scheme.Codecs, kubeConfigFile, groupVersions, 0)
	if err != nil {
		return nil, err
	}
	return &subjectAccessReviewClient{gw}, nil
}

type subjectAccessReviewClient struct {
	w *webhook.GenericWebhook
}

func (t *subjectAccessReviewClient) Create(subjectAccessReview *authorization.SubjectAccessReview) (*authorization.SubjectAccessReview, error) {
	return t.CreateContext(context.Background(), subjectAccessReview)
}

func (t *subjectAccessReviewClient) CreateContext(ctx context.Context, subjectAccessReview *authorization.SubjectAccessReview) (*authorization.SubjectAccessReview, error) {
	result := &authorization.SubjectAccessReview{}
	err := t.w.RestClient.Post().Context(ctx).Body(subjectAccessReview).Do().Into(result)
	return result, err
}

// shouldCache determines whether it is safe to cache the given request attributes. If the
// requester-controlled attributes are too large, this may be a DoS attempt, so we skip the cache.
func shouldCache(attr authorizer.Attributes) bool {
	controlledAttrSize := int64(len(attr.GetNamespace())) +
		int64(len(attr.GetVerb())) +
		int64(len(attr.GetAPIGroup())) +
		int64(len(attr.GetAPIVersion())) +
		int64(len(attr.GetResource())) +
		int64(len(attr.GetSubresource())) +
		int64(len(attr.GetName())) +
		int64(len(attr.GetPath()))
	return controlledAttrSize < maxControlledAttrCacheSize
}