text:
package integration

import (
	"fmt"
	"testing"
	"time"

	_ "github.com/apache/beam/sdks/v2/go/pkg/beam/runners/dataflow"
	_ "github.com/apache/beam/sdks/v2/go/pkg/beam/runners/flink"
	_ "github.com/apache/beam/sdks/v2/go/pkg/beam/runners/samza"
	_ "github.com/apache/beam/sdks/v2/go/pkg/beam/runners/spark"
	"github.com/apache/beam/sdks/v2/go/test/integration/internal/jars"
	"github.com/google/go-cmp/cmp"
	"github.com/google/go-cmp/cmp/cmpopts"
)

type testProcess struct {
	killed bool
	jar    string
}

func (p *testProcess) Kill() error {
	p.killed = true
	return nil
}

func failRun(_ time.Duration, _ string, _ ...string) (jars.Process, error) {
	return nil, fmt.Errorf("unexpectedly running a jar, failing")
}

func succeedRun(_ time.Duration, jar string, _ ...string) (jars.Process, error) {
	return &testProcess{jar: jar}, nil
}

// TestExpansionServices_GetAddr_Addresses tests calling GetAddr on provided addresses.
func TestExpansionServices_GetAddr_Addresses(t *testing.T) {
	addrsMap := map[string]string{
		"label1": "testAddr1",
		"label2": "testAddr2",
		"label3": "testAddr3",
	}
	jarsMap := map[string]string{
		"label2": "jarFilepath2",
	}
	es := &ExpansionServices{
		addrs:    addrsMap,
		jars:     jarsMap,
		procs:    make([]jars.Process, 0),
		run:      failRun,
		waitTime: 0,
	}

	// Ensure we get the same map we put in, and that addresses take priority over jars if
	// both are given for the same label.
	for label, wantAddr := range addrsMap {
		gotAddr, err := es.GetAddr(label)
		if err != nil {
			t.Errorf("unexpected error when getting address for \"%v\": %v", label, err)
			continue
		}
		if gotAddr != wantAddr {
			t.Errorf("incorrect address for \"%v\", want %v, got %v", label, wantAddr, gotAddr)
		}
	}
	// Check that nonexistent labels fail.
	if _, err := es.GetAddr("nonexistent_label"); err == nil {
		t.Errorf("did not receive error when calling GetAddr with nonexistent label")
	}
}

// TestExpansionServices_GetAddr_Jars tests calling GetAddr on provided jars.
func TestExpansionServices_GetAddr_Jars(t *testing.T) {
	addrsMap := map[string]string{}
	jarsMap := map[string]string{
		"label1": "jarFilepath1",
		"label2": "jarFilepath2",
		"label3": "jarFilepath3",
	}
	es := &ExpansionServices{
		addrs:    addrsMap,
		jars:     jarsMap,
		procs:    make([]jars.Process, 0),
		run:      succeedRun,
		waitTime: 0,
	}

	// Call GetAddr on each jar twice, checking that the addresses remain consistent.
	gotMap := make(map[string]string)
	for label := range jarsMap {
		gotAddr, err := es.GetAddr(label)
		if err != nil {
			t.Errorf("unexpected error when getting address for \"%v\": %v", label, err)
			continue
		}
		gotMap[label] = gotAddr
	}
	for label, gotAddr := range gotMap {
		secondAddr, err := es.GetAddr(label)
		if err != nil {
			t.Errorf("unexpected error when getting address for \"%v\": %v", label, err)
			continue
		}
		if secondAddr != gotAddr {
			t.Errorf("getAddr returned different address when called twice for \"%v\", "+
				"attempt 1: %v, attempt 2: %v", label, gotAddr, secondAddr)
		}
	}
	// Check that all jars were run.
	gotJars := make([]string, 0)
	for _, proc := range es.procs {
		testProc := proc.(*testProcess)
		gotJars = append(gotJars, testProc.jar)
	}
	wantJars := make([]string, 0)
	for _, jar := range jarsMap {
		wantJars = append(wantJars, jar)
	}
	lessFunc := func(a, b string) bool { return a < b }
	if diff := cmp.Diff(wantJars, gotJars, cmpopts.SortSlices(lessFunc)); diff != "" {
		t.Errorf("processes in ExpansionServices does not match jars that should be running: diff(-want,+got):\n%v", diff)
	}
}

// TestExpansionServices_Shutdown tests that a shutdown correctly kills all jars started by an
// ExpansionServices.
func TestExpansionServices_Shutdown(t *testing.T) {
	addrsMap := map[string]string{}
	jarsMap := map[string]string{
		"label1": "jarFilepath1",
		"label2": "jarFilepath2",
		"label3": "jarFilepath3",
	}
	es := &ExpansionServices{
		addrs:    addrsMap,
		jars:     jarsMap,
		procs:    make([]jars.Process, 0),
		run:      succeedRun,
		waitTime: 0,
	}
	// Call getAddr on each label to run jars.
	for label := range addrsMap {
		_, err := es.GetAddr(label)
		if err != nil {
			t.Errorf("unexpected error when getting address for \"%v\": %v", label, err)
			continue
		}
	}

	// Shutdown and confirm that jars are killed and addresses can no longer be retrieved.
	procs := es.procs
	es.Shutdown()
	for _, proc := range procs {
		testProc := proc.(*testProcess)
		if !testProc.killed {
			t.Errorf("process for jar %v was not killed on Shutdown()", testProc.jar)
		}
	}
	for label := range addrsMap {
		_, err := es.GetAddr(label)
		if err == nil {
			t.Errorf("calling GetAddr after Shutdown did not return an error for \"%v\"", label)
		}
	}
}

redpajama_set_name: RedPajamaGithub


text:
package org.eclipse.jgit.patch;

import static org.eclipse.jgit.lib.Constants.encodeASCII;
import static org.eclipse.jgit.util.RawParseUtils.match;
import static org.eclipse.jgit.util.RawParseUtils.nextLF;
import static org.eclipse.jgit.util.RawParseUtils.parseBase10;

/** Part of a "GIT binary patch" to describe the pre-image or post-image */
public class BinaryHunk {
	private static final byte[] LITERAL = encodeASCII("literal ");

	private static final byte[] DELTA = encodeASCII("delta ");

	/** Type of information stored in a binary hunk. */
	public static enum Type {
		/** The full content is stored, deflated. */
		LITERAL_DEFLATED,

		/** A Git pack-style delta is stored, deflated. */
		DELTA_DEFLATED;
	}

	private final FileHeader file;

	/** Offset within {@link #file}.buf to the "literal" or "delta " line. */
	final int startOffset;

	/** Position 1 past the end of this hunk within {@link #file}'s buf. */
	int endOffset;

	/** Type of the data meaning. */
	private Type type;

	/** Inflated length of the data. */
	private int length;

	BinaryHunk(final FileHeader fh, final int offset) {
		file = fh;
		startOffset = offset;
	}

	/** @return header for the file this hunk applies to */
	public FileHeader getFileHeader() {
		return file;
	}

	/** @return the byte array holding this hunk's patch script. */
	public byte[] getBuffer() {
		return file.buf;
	}

	/** @return offset the start of this hunk in {@link #getBuffer()}. */
	public int getStartOffset() {
		return startOffset;
	}

	/** @return offset one past the end of the hunk in {@link #getBuffer()}. */
	public int getEndOffset() {
		return endOffset;
	}

	/** @return type of this binary hunk */
	public Type getType() {
		return type;
	}

	/** @return inflated size of this hunk's data */
	public int getSize() {
		return length;
	}

	int parseHunk(int ptr, final int end) {
		final byte[] buf = file.buf;

		if (match(buf, ptr, LITERAL) >= 0) {
			type = Type.LITERAL_DEFLATED;
			length = parseBase10(buf, ptr + LITERAL.length, null);

		} else if (match(buf, ptr, DELTA) >= 0) {
			type = Type.DELTA_DEFLATED;
			length = parseBase10(buf, ptr + DELTA.length, null);

		} else {
			// Not a valid binary hunk. Signal to the caller that
			// we cannot parse any further and that this line should
			// be treated otherwise.
			//
			return -1;
		}
		ptr = nextLF(buf, ptr);

		// Skip until the first blank line; that is the end of the binary
		// encoded information in this hunk. To save time we don't do a
		// validation of the binary data at this point.
		//
		while (ptr < end) {
			final boolean empty = buf[ptr] == '\n';
			ptr = nextLF(buf, ptr);
			if (empty)
				break;
		}

		return ptr;
	}
}


text:
require 'sinatra/base'
require 'json'
require 'mysql2-cs-bind'
require 'digest/sha2'
require 'dalli'
require 'rack/session/dalli'
require 'erubis'
require 'tempfile'

class Isucon3App < Sinatra::Base
  $stdout.sync = true
  use Rack::Session::Dalli, {
    :key => 'isucon_session',
    :cache => Dalli::Client.new('localhost:11211')
  }

  helpers do
    set :erb, :escape_html => true

    def connection
      config = JSON.parse(IO.read(File.dirname(__FILE__) + "/../config/#{ ENV['ISUCON_ENV'] || 'local' }.json"))['database']
      return $mysql if $mysql
      $mysql = Mysql2::Client.new(
        :host => config['host'],
        :port => config['port'],
        :username => config['username'],
        :password => config['password'],
        :database => config['dbname'],
        :reconnect => true,
      )
    end

    def get_user
      mysql = connection
      user_id = session["user_id"]
      if user_id
        user = mysql.xquery("SELECT * FROM users WHERE id=?", user_id).first
        headers "Cache-Control" => "private"
      end
      return user || {}
    end

    def require_user(user)
      unless user["username"]
        redirect "/"
        halt
      end
    end

    def gen_markdown(md)
      tmp = Tempfile.open("isucontemp")
      tmp.puts(md)
      tmp.close
      html = `../bin/markdown #{tmp.path}`
      tmp.unlink
      return html
    end

    def anti_csrf
      if params["sid"] != session["token"]
        halt 400, "400 Bad Request"
      end
    end

    def url_for(path)
      scheme = request.scheme
      if (scheme == 'http' && request.port == 80 ||
          scheme == 'https' && request.port == 443)
        port = ""
      else
        port = ":#{request.port}"
      end
      base = "#{scheme}://#{request.host}#{port}#{request.script_name}"
      "#{base}#{path}"
    end
  end

  get '/' do
    mysql = connection
    user  = get_user

    total = mysql.query("SELECT count(*) AS c FROM memos WHERE is_private=0").first["c"]
    memos = mysql.query("SELECT * FROM memos WHERE is_private=0 ORDER BY created_at DESC, id DESC LIMIT 100")
    memos.each do |row|
      row["username"] = mysql.xquery("SELECT username FROM users WHERE id=?", row["user"]).first["username"]
    end
    erb :index, :layout => :base, :locals => {
      :memos => memos,
      :page  => 0,
      :total => total,
      :user  => user,
    }
  end

  get '/recent/:page' do
    mysql = connection
    user  = get_user

    page  = params["page"].to_i
    total = mysql.xquery('SELECT count(*) AS c FROM memos WHERE is_private=0').first["c"]
    memos = mysql.xquery("SELECT * FROM memos WHERE is_private=0 ORDER BY created_at DESC, id DESC LIMIT 100 OFFSET #{page * 100}")
    if memos.count == 0
      halt 404, "404 Not Found"
    end
    memos.each do |row|
      row["username"] = mysql.xquery("SELECT username FROM users WHERE id=?", row["user"]).first["username"]
    end
    erb :index, :layout => :base, :locals => {
      :memos => memos,
      :page  => page,
      :total => total,
      :user  => user,
    }
  end

  post '/signout' do
    user = get_user
    require_user(user)
    anti_csrf

    session.destroy
    redirect "/"
  end

  get '/signin' do
    user = get_user
    erb :signin, :layout => :base, :locals => {
      :user => user,
    }
  end

  post '/signin' do
    mysql = connection

    username = params[:username]
    password = params[:password]
    user = mysql.xquery('SELECT id, username, password, salt FROM users WHERE username=?', username).first
    if user && user["password"] == Digest::SHA256.hexdigest(user["salt"] + password)
      session.clear
      session["user_id"] = user["id"]
      session["token"] = Digest::SHA256.hexdigest(Random.new.rand.to_s)
      mysql.xquery("UPDATE users SET last_access=now() WHERE id=?", user["id"])
      redirect "/mypage"
    else
      erb :signin, :layout => :base, :locals => {
        :user => {},
      }
    end
  end

  get '/mypage' do
    mysql = connection
    user  = get_user
    require_user(user)

    memos = mysql.xquery('SELECT id, content, is_private, created_at, updated_at FROM memos WHERE user=? ORDER BY created_at DESC', user["id"])
    erb :mypage, :layout => :base, :locals => {
      :user  => user,
      :memos => memos,
    }
  end

  get '/memo/:memo_id' do
    mysql = connection
    user  = get_user

    memo = mysql.xquery('SELECT id, user, content, is_private, created_at, updated_at FROM memos WHERE id=?', params[:memo_id]).first
    unless memo
      halt 404, "404 Not Found"
    end
    if memo["is_private"] == 1
      if user["id"] != memo["user"]
        halt 404, "404 Not Found"
      end
    end
    memo["username"] = mysql.xquery('SELECT username FROM users WHERE id=?', memo["user"]).first["username"]
    memo["content_html"] = gen_markdown(memo["content"])
    if user["id"] == memo["user"]
      cond = ""
    else
      cond = "AND is_private=0"
    end
    memos = []
    older = nil
    newer = nil
    results = mysql.xquery("SELECT * FROM memos WHERE user=? #{cond} ORDER BY created_at", memo["user"])
    results.each do |m|
      memos.push(m)
    end
    0.upto(memos.count - 1).each do |i|
      if memos[i]["id"] == memo["id"]
        older = memos[i - 1] if i > 0
        newer = memos[i + 1] if i < memos.count
      end
    end
    erb :memo, :layout => :base, :locals => {
      :user  => user,
      :memo  => memo,
      :older => older,
      :newer => newer,
    }
  end

  post '/memo' do
    mysql = connection
    user  = get_user
    require_user(user)
    anti_csrf

    mysql.xquery(
      'INSERT INTO memos (user, content, is_private, created_at) VALUES (?, ?, ?, ?)',
      user["id"],
      params["content"],
      params["is_private"].to_i,
      Time.now,
    )
    memo_id = mysql.last_id
    redirect "/memo/#{memo_id}"
  end

  run! if app_file == $0
end


text:
![Angularity Logo](http://angularity.github.io/assets/logo.png)

[![NPM](https://nodei.co/npm/angularity.png)](http://angularity.github.io)

[![Build Status](https://travis-ci.org/angularity/node-angularity.svg?branch=master)](https://travis-ci.org/angularity/node-angularity)
[![Build status](https://ci.appveyor.com/api/projects/status/6b1xir7y1j0wm64a/branch/master?svg=true)](https://ci.appveyor.com/project/impaler/node-angularity/branch/master)

> **-- IMPORTANT ANNOUNCEMENT --**
>
> Angularity is now **deprecated** and may be removed at any time.
>
> Do **not** use for new projects.
>
> Use the [Webpack implementation](https://www.npmjs.com/package/webpack-angularity-solution) for existing Angularity (Browserify/SASS) projects using **Angular 1.x**.

Build projects, not build systems.

- Hand picked and industry proven front end technologies.
- A complete and scalable single page application workflow.

![AngularJs, Browserify, BabelJs, NodeJs](angularity-library-logos.png)

## Features

A complete frontend development solution for:
modules, minification, source maps, linting, testing, live reloading, release and workflow tooling

- No complicated build files per project
- Kickstart your workflow with IDE integration and command line interface
- Write with the latest ES6 Javascript features
- Use CommonJs/NodeJs syntax
- In-built support for Karma tests
- Build with minification and source-map safe bundles
- Use both Bower and NPM for your vendor dependencies
- Convenient CI integration with custom reporters
- Plugin system to create your own tasks

## Documentation

[angularity.github.io](http://angularity.github.io)

## Maintained by

Ben Holloway, Chris Decoster, Brendan Graetz, Tony Sepentulevski

## Licence

MIT


text:
package org.mifos.application.meeting.util.helpers;

import org.mifos.application.meeting.business.MeetingTypeEntity;

/**
 * When ever we require a frequency(recurrence pattern) to be stored, we create
 * a "meeting" (this is not necessarily a meeting in the sense we present to the
 * users).
 *
 * See also {@link MeetingTypeEntity}.
 */
public enum MeetingType {
    /* Schedule of loan installment payments for an account */
    LOAN_INSTALLMENT((short) 1),

    /*
     * This is not to generate a schedule, but to calculate the interest after
     * the specified time period.
     */
    SAVINGS_INTEREST_CALCULATION_TIME_PERIOD((short) 2),

    /* Schedule for posting interest to an account */
    SAVINGS_INTEREST_POSTING((short) 3),

    /* This is what we call a "meeting" in the user interface. */
    CUSTOMER_MEETING((short) 4),

    /* Recurrence of a fee. Can be for either a loan or a customer. */
    PERIODIC_FEE((short) 5);

    Short value;

    MeetingType(Short value) {
        this.value = value;
    }

    public Short getValue() {
        return value;
    }

    public static MeetingType fromInt(int value) {
        for (MeetingType meetingType : MeetingType.values()) {
            if (meetingType.getValue() == value) {
                return meetingType;
            }
        }
        throw new RuntimeException("meeting type " + value + " unrecognized");
    }

}


text:
from setuptools import setup, find_packages
import sys

install_requires = []
if sys.version_info < (3, 4):
    install_requires.append('enum34')
    install_requires.append('asyncio==0.2.1')

setup(
    name="Vase",
    version="0.1.4",
    author="Vladimir Kryachko",
    author_email="v.kryachko@gmail.com",
    description = "Async Web framework based on Tulip/asyncio",
    classifiers=[
        "Programming Language :: Python",
        "Programming Language :: Python :: 3",
        "Programming Language :: Python :: 3.4",
    ],
    install_requires = install_requires,
    packages=find_packages(exclude=["*.tests", "*.tests.*", "tests.*", "tests"]),
)


text:
 38"
            tooltip-append-to-body="true">
          {{ app.name }}

           Type: Batch
           Type: Realtime

 158"
       tooltip-append-to-body="true">
      {{ app.description | myEllipsis: 158 }}

      {{ appStatus }}

      View in CDAP

        Start

        Stop

        Start

        Stop

      Run Once

      Clone

      Delete

<my-dag data-is-disabled="true" data-config="nodes"></my-dag>

          {{ tab.title }}


text:
import { Component } from '@angular/core';

import { NavController } from 'ionic-angular';

import { SignupPage } from '../signup/signup';
import { TabsPage } from '../tabs/tabs';
import { UserData } from '../../providers/user-data';

@Component({
  selector: 'page-login',
  templateUrl: 'login.html'
})
export class LoginPage {
  login: {username?: string, password?: string} = {};
  submitted = false;

  constructor(public navCtrl: NavController, public userData: UserData) { }

  onLogin(form) {
    this.submitted = true;

    if (form.valid) {
      this.userData.login(this.login.username);
      this.navCtrl.push(TabsPage);
    }
  }

  onSignup() {
    this.navCtrl.push(SignupPage);
  }
}


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

{% block css %}<link href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">{% endblock css %}

{% block main %}

	<legend>Sign in with WPI CCC Account</legend>
	<form method="POST" action="" accept-charset="UTF-8">

			<input type="text" id="username" class="form-control" name="username" placeholder="Username">

			<input type="password" id="password" class="form-control" name="password" placeholder="Password">

			<button type="submit" name="submit" class="btn btn-info btn-block">Sign in</button>

	</form>

{% endblock main %}


text:
import Ember from 'ember';

export default Ember.Mixin.create({
  beforeModel(transition) {
    var superResult = this._super(transition);

    if (this.get('session.isAuthenticated')) {
      transition.abort();
      var config = this.container.lookupFactory('config:environment');
      this.transitionTo(config['ember-parse'].session.ifAlreadyAuthenticatedRoute);
    }

    return superResult;
  }
});


text:
using System;
using Vlc.DotNet.Core.Interops.Signatures;

namespace Vlc.DotNet.Core.Interops
{
    public sealed partial class VlcManager
    {
        public void SetMute(VlcMediaPlayerInstance mediaPlayerInstance, bool status)
        {
            if (mediaPlayerInstance == IntPtr.Zero)
                throw new ArgumentException("Media player instance is not initialized.");
            GetInteropDelegate<SetMute>().Invoke(mediaPlayerInstance, status ? 1 : 0);
        }
    }
}


text:
package org.neo4j.shell;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.io.Serializable;
import java.lang.reflect.Method;
import java.rmi.ConnectException;
import java.rmi.RemoteException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.atomic.AtomicBoolean;

import org.neo4j.graphdb.GraphDatabaseService;
import org.neo4j.graphdb.factory.GraphDatabaseFactory;
import org.neo4j.helpers.Args;
import org.neo4j.kernel.Version;
import org.neo4j.shell.impl.RmiLocation;
import org.neo4j.shell.impl.ShellBootstrap;
import org.neo4j.shell.impl.SimpleAppServer;
import org.neo4j.shell.impl.SystemOutput;
import org.neo4j.shell.kernel.GraphDatabaseShellServer;

import static org.neo4j.io.fs.FileUtils.newBufferedFileReader;
import static org.neo4j.kernel.impl.util.Charsets.UTF_8;

/**
 * Can start clients, either remotely to another JVM running a server
 * or by starting a local {@link GraphDatabaseShellServer} in this JVM
 * and connecting to it.
 */
public class StartClient
{
    private AtomicBoolean hasBeenShutdown = new AtomicBoolean();

    /**
     * Prints the version and edition of neo4j and exits.
     */
    public static final String ARG_VERSION = "version";

    /**
     * The path to the local (this JVM) {@link GraphDatabaseService} to
     * start and connect to.
     */
    public static final String ARG_PATH = "path";

    /**
     * Whether or not the shell client should be readonly.
     */
    public static final String ARG_READONLY = "readonly";

    /**
     * The host (ip or name) to connect remotely to.
     */
    public static final String ARG_HOST = "host";

    /**
     * The port to connect remotely on. A server must have been started
     * on that port.
     */
    public static final String ARG_PORT = "port";

    /**
     * The RMI name to use.
     */
    public static final String ARG_NAME = "name";

    /**
     * The PID (process ID) to connect to.
     */
    public static final String ARG_PID = "pid";

    /**
     * Commands (a line can contain more than one command, with && in between)
     * to execute when the shell client has been connected.
     */
    public static final String ARG_COMMAND = "c";

    /**
     * File a file with shell commands to execute when the shell client has
     * been connected.
     */
    public static final String ARG_FILE = "file";

    /**
     * Special character used to request reading from stdin rather than a file.
     * Uses the dash character, which is a common way to specify this.
     */
    public static final String ARG_FILE_STDIN = "-";

    /**
     * Configuration file to load and use if a local {@link GraphDatabaseService}
     * is started in this JVM.
     */
    public static final String ARG_CONFIG = "config";

    private final GraphDatabaseFactory factory;
    private final PrintStream out;
    private final PrintStream err;

    // Visible for testing
    StartClient( PrintStream out, PrintStream err )
    {
        this.factory = loadEditionDatabaseFactory();
        this.out = out;
        this.err = err;
    }

    /**
     * Starts a shell client. Remote or local depending on the arguments.
     *
     * @param arguments the arguments from the command line. Can contain
     * information about whether to start a local
     * {@link GraphDatabaseShellServer} or connect to an already running
     * {@link GraphDatabaseService}.
     */
    public static void main( String[] arguments )
    {
        InterruptSignalHandler signalHandler = InterruptSignalHandler.getHandler();
        try
        {
            new StartClient( System.out, System.err ).start( arguments, signalHandler );
        }
        catch ( ShellExecutionFailureException e )
        {
            e.dumpMessage( System.out, System.err );
            System.exit( 1 );
        }
    }

    private static GraphDatabaseFactory loadEditionDatabaseFactory()
    {
        GraphDatabaseFactory factory;
        try
        {
            factory = (GraphDatabaseFactory) Class.forName( "org.neo4j.graphdb.factory.EnterpriseGraphDatabaseFactory" )
                    .newInstance();
        }
        catch ( Exception e )
        {
            factory = new GraphDatabaseFactory();
        }
        return factory;
    }

    // visible for testing
    void start( String[] arguments, CtrlCHandler signalHandler )
    {
        Args args = Args.withFlags( ARG_READONLY ).parse( arguments );
        if ( args.has( "?" ) || args.has( "h" ) || args.has( "help" ) || args.has( "usage" ) )
        {
            printUsage( out );
            return;
        }

        String path = args.get( ARG_PATH, null );
        String host = args.get( ARG_HOST, null );
        String port = args.get( ARG_PORT, null );
        String name = args.get( ARG_NAME, null );
        String pid = args.get( ARG_PID, null );
        boolean version = args.getBoolean( ARG_VERSION, false, true );

        if ( version )
        {
            out.printf( "Neo4j %s, version %s", factory.getEdition(), Version.getKernelVersion() );
        }
        else if ( (path != null && (port != null || name != null || host != null || pid != null))
             || (pid != null && host != null) )
        {
            err.println( "You have supplied both " +
                         ARG_PATH + " as well as " + ARG_HOST + "/" + ARG_PORT + "/" + ARG_NAME + ". " +
                         "You should either supply only " + ARG_PATH +
                         " or " + ARG_HOST + "/" + ARG_PORT + "/" + ARG_NAME + " so that either a local or " +
                         "remote shell client can be started" );
        }
        // Local
        else if ( path != null )
        {
            try
            {
                checkNeo4jDependency();
            }
            catch ( ShellException e )
            {
                throw new ShellExecutionFailureException( e, args );
            }
            startLocal( args, signalHandler );
        }
        // Remote
        else
        {
            String readonly = args.get( ARG_READONLY, null );
            if ( readonly != null )
            {
                err.println( "Warning: -" + ARG_READONLY + " is ignored unless you connect with -" + ARG_PATH + "!" );
            }

            // Start server on the supplied process
            if ( pid != null )
            {
                startServer( pid, args );
            }
            startRemote( args, signalHandler );
        }
    }

    private static final Method attachMethod, loadMethod;

    static
    {
        Method attach, load;
        try
        {
            Class<?> vmClass = Class.forName( "com.sun.tools.attach.VirtualMachine" );
            attach = vmClass.getMethod( "attach", String.class );
            load = vmClass.getMethod( "loadAgent", String.class, String.class );
        }
        catch ( Exception e )
        {
            attach = load = null;
        }
        attachMethod = attach;
        loadMethod = load;
    }

    private static void checkNeo4jDependency() throws ShellException
    {
        try
        {
            Class.forName( "org.neo4j.graphdb.GraphDatabaseService" );
        }
        catch ( Exception e )
        {
            throw new ShellException( "Neo4j not found on the classpath" );
        }
    }

    private void startLocal( Args args, CtrlCHandler signalHandler )
    {
        String dbPath = args.get( ARG_PATH, null );
        if ( dbPath == null )
        {
            err.println( "ERROR: To start a local Neo4j service and a " +
                         "shell client on top of that you need to supply a path to a " +
                         "Neo4j store or just a new path where a new store will " +
                         "be created if it doesn't exist. -" + ARG_PATH +
                         " /my/path/here" );
            return;
        }

        try
        {
            boolean readOnly = args.getBoolean( ARG_READONLY, false, true );
            tryStartLocalServerAndClient( dbPath, readOnly, args, signalHandler );
        }
        catch ( Exception e )
        {
            throw new ShellExecutionFailureException( e, args );
        }
    }

    private void tryStartLocalServerAndClient( String dbPath, boolean readOnly, Args args,
            CtrlCHandler signalHandler ) throws Exception
    {
        String configFile = args.get( ARG_CONFIG, null );
        final GraphDatabaseShellServer server = getGraphDatabaseShellServer( dbPath, readOnly, configFile );
        Runtime.getRuntime().addShutdownHook( new Thread()
        {
            @Override
            public void run()
            {
                shutdownIfNecessary( server );
            }
        } );

        if ( !isCommandLine( args ) )
        {
            out.println( "NOTE: Local Neo4j graph database service at '" + dbPath + "'" );
        }
        ShellClient client = ShellLobby.newClient( server, getSessionVariablesFromArgs( args ),
                new SystemOutput( out ), signalHandler );
        grabPromptOrJustExecuteCommand( client, args );

        shutdownIfNecessary( server );
    }

    protected GraphDatabaseShellServer getGraphDatabaseShellServer( String dbPath, boolean readOnly, String configFile )
            throws RemoteException
    {
        return new GraphDatabaseShellServer( factory, dbPath, readOnly, configFile );
    }

    private void shutdownIfNecessary( ShellServer server )
    {
        try
        {
            if ( hasBeenShutdown.compareAndSet( false, true ) )
            {
                server.shutdown();
            }
        }
        catch ( RemoteException e )
        {
            throw new RuntimeException( e );
        }
    }

    private void startServer( String pid, Args args )
    {
        String port = args.get( "port", Integer.toString( SimpleAppServer.DEFAULT_PORT ) );
        String name = args.get( "name", SimpleAppServer.DEFAULT_NAME );
        try
        {
            String jarfile = new File(
                    getClass().getProtectionDomain().getCodeSource().getLocation().toURI() ).getAbsolutePath();
            Object vm = attachMethod.invoke( null, pid );
            loadMethod.invoke( vm, jarfile, new ShellBootstrap( Integer.parseInt( port ), name ).serialize() );
        }
        catch ( Exception e )
        {
            throw new ShellExecutionFailureException( e, args );
        }
    }

    private void startRemote( Args args, CtrlCHandler signalHandler )
    {
        try
        {
            String host = args.get( ARG_HOST, "localhost" );
            int port = args.getNumber( ARG_PORT, SimpleAppServer.DEFAULT_PORT ).intValue();
            String name = args.get( ARG_NAME, SimpleAppServer.DEFAULT_NAME );
            ShellClient client = ShellLobby.newClient( RmiLocation.location( host, port, name ),
                    getSessionVariablesFromArgs( args ), signalHandler );
            if ( !isCommandLine( args ) )
            {
                out.println( "NOTE: Remote Neo4j graph database service '" + name + "' at port " + port );
            }
            grabPromptOrJustExecuteCommand( client, args );
        }
        catch ( Exception e )
        {
            throw new ShellExecutionFailureException( e, args );
        }
    }

    private static boolean isCommandLine( Args args )
    {
        return args.get( ARG_COMMAND, null ) != null ||
               args.get( ARG_FILE, null ) != null;
    }

    private void grabPromptOrJustExecuteCommand( ShellClient client, Args args ) throws Exception
    {
        String command = args.get( ARG_COMMAND, null );
        if ( command != null )
        {
            client.evaluate( command );
            client.shutdown();
            return;
        }
        String fileName = args.get( ARG_FILE, null );
        if ( fileName != null )
        {
            BufferedReader reader = null;
            try
            {
                if ( fileName.equals( ARG_FILE_STDIN ) )
                {
                    reader = new BufferedReader( new InputStreamReader( System.in, UTF_8 ) );
                }
                else
                {
                    File file = new File( fileName );
                    if ( !file.exists() )
                    {
                        throw new ShellException( "File to execute " + "does not exist: " + fileName );
                    }
                    reader = newBufferedFileReader( file, UTF_8 );
                }
                executeCommandStream( client, reader );
            }
            finally
            {
                if ( reader != null )
                {
                    reader.close();
                }
            }
            return;
        }
        client.grabPrompt();
    }

    private void executeCommandStream( ShellClient client, BufferedReader reader ) throws IOException,
            ShellException
    {
        try
        {
            for ( String line; (line = reader.readLine()) != null; )
            {
                client.evaluate( line );
            }
        }
        finally
        {
            client.shutdown();
            reader.close();
        }
    }

    static Map<String,Serializable> getSessionVariablesFromArgs( Args args ) throws RemoteException, ShellException
    {
        String profile = args.get( "profile", null );
        Map<String,Serializable> session = new HashMap<>();
        if ( profile != null )
        {
            applyProfileFile( new File( profile ), session );
        }

        for ( Map.Entry<String,String> entry : args.asMap().entrySet() )
        {
            String key = entry.getKey();
            if ( key.startsWith( "D" ) )
            {
                key = key.substring( 1 );
                session.put( key, entry.getValue() );
            }
        }
        if ( isCommandLine( args ) )
        {
            session.put( "quiet", true );
        }
        return session;
    }

    private static void applyProfileFile( File file, Map<String,Serializable> session ) throws ShellException
    {
        try ( FileInputStream fis = new FileInputStream( file ) )
        {
            Properties properties = new Properties();
            properties.load( fis );
            for ( Object key : properties.keySet() )
            {
                String stringKey = (String) key;
                String value = properties.getProperty( stringKey );
                session.put( stringKey, value );
            }
        }
        catch ( IOException e )
        {
            throw new IllegalArgumentException( "Couldn't find profile '" +
                                                file.getAbsolutePath() + "'" );
        }
    }

    private static int longestString( String... strings )
    {
        int length = 0;
        for ( String string : strings )
        {
            if ( string.length() > length )
            {
                length = string.length();
            }
        }
        return length;
    }

    private static void printUsage( PrintStream out )
    {
        int port = SimpleAppServer.DEFAULT_PORT;
        String name = SimpleAppServer.DEFAULT_NAME;
        int longestArgLength = longestString( ARG_FILE, ARG_COMMAND,
                ARG_CONFIG,
                ARG_HOST, ARG_NAME,
                ARG_PATH, ARG_PID, ARG_PORT, ARG_READONLY );
        out.println(
                padArg( ARG_HOST, longestArgLength ) + "Domain name or IP of host to connect to (default: localhost)" +
                "\n" +
                padArg( ARG_PORT, longestArgLength ) + "Port of host to connect to (default: " +
                SimpleAppServer.DEFAULT_PORT + ")\n" +
                padArg( ARG_NAME, longestArgLength ) + "RMI name, i.e. rmi://<host>:<port>/<name> (default: "
                + SimpleAppServer.DEFAULT_NAME + ")\n" +
                padArg( ARG_PID, longestArgLength ) + "Process ID to connect to\n" +
                padArg( ARG_COMMAND, longestArgLength ) + "Command line to execute. After executing it the " +
                "shell exits\n" +
                padArg( ARG_FILE, longestArgLength ) + "File containing commands to execute, or '-' to read " +
                "from stdin. After executing it the shell exits\n" +
                padArg( ARG_READONLY, longestArgLength ) + "Connect in readonly mode (only for connecting " +
                "with -" + ARG_PATH + ")\n" +
                padArg( ARG_PATH, longestArgLength ) + "Points to a neo4j db path so that a local server can " +
                "be started there\n" +
                padArg( ARG_CONFIG, longestArgLength ) + "Points to a config file when starting a local " +
                "server\n\n" +

                "Example arguments for remote:\n" +
                "\t-" + ARG_PORT + " " + port + "\n" +
                "\t-" + ARG_HOST + " " + "192.168.1.234" + " -" + ARG_PORT + " " + port + " -" + ARG_NAME + "" +
                " " + name + "\n" +
                "\t-" + ARG_HOST + " " + "localhost" + " -" + ARG_READONLY + "\n" +
                "\t...or no arguments for default values\n" +
                "Example arguments for local:\n" +
                "\t-" + ARG_PATH + " /path/to/db" + "\n" +
                "\t-" + ARG_PATH + " /path/to/db -" + ARG_CONFIG + " /path/to/neo4j.config" + "\n" +
                "\t-" + ARG_PATH + " /path/to/db -" + ARG_READONLY
        );
    }

    private static String padArg( String arg, int length )
    {
        return " -" + pad( arg, length ) + "  ";
    }

    private static String pad( String string, int length )
    {
        // Rather inefficient
        while ( string.length() < length )
        {
            string = string + " ";
        }
        return string;
    }

    private static class ShellExecutionFailureException extends RuntimeException
    {
        private final Throwable cause;
        private final Args args;

        ShellExecutionFailureException( Throwable cause, Args args )
        {
            this.cause = cause;
            this.args = args;
        }

        private void dumpMessage( PrintStream out, PrintStream err )
        {
            String message = cause.getCause() instanceof ConnectException ?
                             "Connection refused" : cause.getMessage();
            err.println( "ERROR (-v for expanded information):\n\t" + message );
            if ( args.has( "v" ) )
            {
                cause.printStackTrace( err );
            }
            err.println();
            printUsage( out );
        }
    }
}


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

<title>Uses of Interface org.springframework.web.util.UriBuilder (Spring Framework 5.1.18.RELEASE API)</title>
<meta name="date" content="2020-09-15">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Spring Framework

Prev

Next

Frames

No Frames

All Classes

Uses of Interface
org.springframework.web.util.UriBuilder

Packages that use UriBuilder

Package
Description

org.springframework.mock.web.reactive.function.server

Mock objects for the functional web framework.

org.springframework.test.web.reactive.server

Support for testing Spring WebFlux server endpoints via
 WebTestClient.

org.springframework.web.reactive.function.client

Provides a reactive WebClient
 that builds on top of the
 org.springframework.http.client.reactive reactive HTTP adapter layer.

org.springframework.web.reactive.function.server

Provides the types that make up Spring's functional web framework.

org.springframework.web.reactive.function.server.support

Classes supporting the org.springframework.web.reactive.function.server package.

org.springframework.web.servlet.support

Support classes for Spring's web MVC framework.

org.springframework.web.util

Miscellaneous web utility classes, such as HTML escaping,
 Log4j initialization, and cookie handling.

Uses of UriBuilder in org.springframework.mock.web.reactive.function.server

Methods in org.springframework.mock.web.reactive.function.server that return UriBuilder

Modifier and Type
Method and Description

UriBuilder
MockServerRequest.uriBuilder()

Uses of UriBuilder in org.springframework.test.web.reactive.server

Method parameters in org.springframework.test.web.reactive.server with type arguments of type UriBuilder

Modifier and Type
Method and Description

S
WebTestClient.UriSpec.uri(Function<UriBuilder,URI> uriFunction)

Build the URI for the request with a UriBuilder obtained
 through the UriBuilderFactory configured for this client.

Uses of UriBuilder in org.springframework.web.reactive.function.client

Method parameters in org.springframework.web.reactive.function.client with type arguments of type UriBuilder

Modifier and Type
Method and Description

S
WebClient.UriSpec.uri(Function<UriBuilder,URI> uriFunction)

Build the URI for the request using the UriBuilderFactory
 configured for this client.

Uses of UriBuilder in org.springframework.web.reactive.function.server

Methods in org.springframework.web.reactive.function.server that return UriBuilder

Modifier and Type
Method and Description

UriBuilder
ServerRequest.uriBuilder()

Get a UriBuilderComponents from the URI associated with this
 ServerRequest.

Uses of UriBuilder in org.springframework.web.reactive.function.server.support

Methods in org.springframework.web.reactive.function.server.support that return UriBuilder

Modifier and Type
Method and Description

UriBuilder
ServerRequestWrapper.uriBuilder()

Uses of UriBuilder in org.springframework.web.servlet.support

Classes in org.springframework.web.servlet.support that implement UriBuilder

Modifier and Type
Class and Description

class
ServletUriComponentsBuilder

UriComponentsBuilder with additional static factory methods to create links
 based on the current HttpServletRequest.

Uses of UriBuilder in org.springframework.web.util

Classes in org.springframework.web.util that implement UriBuilder

Modifier and Type
Class and Description

class
UriComponentsBuilder

Builder for UriComponents.

Methods in org.springframework.web.util that return UriBuilder

Modifier and Type
Method and Description

UriBuilder
DefaultUriBuilderFactory.builder()

UriBuilder
UriBuilderFactory.builder()

Create a URI builder with default settings.

UriBuilder
UriBuilder.fragment(String fragment)

Set the URI fragment.

UriBuilder
UriBuilder.host(String host)

Set the URI host which may contain URI template variables, and may also
 be null to clear the host of this builder.

UriBuilder
UriBuilder.path(String path)

Append the given path to the existing path of this builder.

UriBuilder
UriBuilder.pathSegment(String... pathSegments)

Append path segments to the existing path.

UriBuilder
UriBuilder.port(int port)

Set the URI port.

UriBuilder
UriBuilder.port(String port)

Set the URI port .

UriBuilder
UriBuilder.query(String query)

Append the given query to the existing query of this builder.

UriBuilder
UriBuilder.queryParam(String name,
          Object... values)

Append the given query parameter to the existing query parameters.

UriBuilder
UriBuilder.queryParams(MultiValueMap<String,String> params)

Add the given query parameters.

UriBuilder
UriBuilder.replacePath(String path)

Set the path of this builder overriding the existing path values.

UriBuilder
UriBuilder.replaceQuery(String query)

Set the query of this builder overriding all existing query parameters.

UriBuilder
UriBuilder.replaceQueryParam(String name,
                 Object... values)

Set the query parameter values overriding all existing query values for
 the same parameter.

UriBuilder
UriBuilder.replaceQueryParams(MultiValueMap<String,String> params)

Set the query parameter values overriding all existing query values.

UriBuilder
UriBuilder.scheme(String scheme)

Set the URI scheme which may contain URI template variables,
 and may also be null to clear the scheme of this builder.

UriBuilder
DefaultUriBuilderFactory.uriString(String uriTemplate)

UriBuilder
UriBuilderFactory.uriString(String uriTemplate)

Initialize a builder with the given URI template.

UriBuilder
UriBuilder.userInfo(String userInfo)

Set the URI user info which may contain URI template variables, and
 may also be null to clear the user info of this builder.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Spring Framework

Prev

Next

Frames

No Frames

All Classes


text:
from future import standard_library
standard_library.install_aliases()
from builtins import object
import operator
import array
import urllib.request, urllib.parse, urllib.error
import urllib.request, urllib.error, urllib.parse
import json
import uservoice
from requests_oauthlib import OAuth1
from urllib.parse import parse_qs
import requests
version='0.0.23'

class APIError(RuntimeError): pass
class Unauthorized(APIError): pass
class NotFound(APIError): pass
class RateLimitExceeded(APIError): pass
class ApplicationError(APIError): pass

class Client(object):
    def __init__(self, subdomain_name, api_key, api_secret=None, oauth_token='', oauth_token_secret='', callback=None, protocol=None, uservoice_domain=None):
        self.request_token = None
        self.token = oauth_token
        self.secret = oauth_token_secret
        self.default_headers = { 'Content-Type': 'application/json', 'Accept': 'application/json',  'API-Client': 'uservoice-python-' + version }
        oauth_hooks = {}
        if api_secret:
            self.oauth = OAuth1(api_key, api_secret, resource_owner_key=self.token, resource_owner_secret=self.secret, callback_uri=callback)
        else:
            self.oauth = None
        self.api_url = "{protocol}://{subdomain_name}.{uservoice_domain}".format(
                           subdomain_name=subdomain_name,
                           protocol=(protocol or 'https'),
                           uservoice_domain=(uservoice_domain or 'uservoice.com')
                       )
        self.api_key = api_key
        self.api_secret = api_secret
        self.callback = callback
        self.subdomain_name = subdomain_name
        self.uservoice_domain = uservoice_domain
        self.protocol = protocol

    def get_request_token(self, callback=None):
        url = self.api_url + '/oauth/request_token'
        body = {}
        if self.callback or callback:
            body['oauth_callback'] = callback or self.callback
        oauth = OAuth1(self.api_key, self.api_secret, callback_uri=self.callback)
        resp = requests.post(url, body, headers=self.default_headers, auth=oauth)
        token = parse_qs(resp.text)
        if not 'oauth_token' in token or not 'oauth_token_secret' in token:
            raise Unauthorized('Failed to get request token')
        return self.login_with_access_token(token['oauth_token'][0], token['oauth_token_secret'][0])

    def authorize_url(self):
        self.request_token = self.get_request_token()
        url = self.api_url + '/oauth/authorize?oauth_token=' + self.request_token.token
        return url

    def login_with_verifier(self, verifier=None):
        url = self.api_url + '/oauth/access_token'
        oauth = OAuth1(self.api_key, self.api_secret, resource_owner_key=self.request_token.token, resource_owner_secret=self.request_token.secret, callback_uri=self.callback, verifier=verifier)
        resp = requests.post(url, auth=oauth)
        token = parse_qs(resp.text)
        return self.login_with_access_token(token['oauth_token'][0], token['oauth_token_secret'][0])

    def login_with_access_token(self, token, secret):
        return Client(self.subdomain_name, self.api_key, self.api_secret, oauth_token=token, oauth_token_secret=secret, callback=self.callback,
                                                                                protocol=self.protocol,
                                                                                uservoice_domain=self.uservoice_domain)

    def request(self, method, path, params={}):
        json_body = None
        get_parameters = {}
        method = method.upper()

        url = self.api_url + path
        if self.api_secret == None:
            if '?' in url:
                url += '&client=' + self.api_key
            else:
                url += '?client=' + self.api_key
        json_resp = None
        if method == 'POST':
            json_resp = requests.post(url, json.dumps(params), headers=self.default_headers, auth=self.oauth)
        elif method == 'PUT':
            json_resp = requests.put(url, json.dumps(params), headers=self.default_headers, auth=self.oauth)
        elif method == 'GET':
            json_resp = requests.get(url, headers=self.default_headers, auth=self.oauth)
        elif method == 'DELETE':
            json_resp = requests.delete(url, headers=self.default_headers, auth=self.oauth)

        attrs = {}
        try:
            if json_resp.status_code == 404:
                attrs = {'errors': {'type': 'record_not_found' }}
            elif json_resp.status_code == 429:
                attrs = {'errors': {'type': 'rate_limit_exceeded' }}
            else:
                attrs = json_resp.json()
        except json.JSONDecodeError as e:
            raise APIError(e)

        if 'errors' in attrs:
            if attrs['errors']['type'] == 'unauthorized':
                raise Unauthorized(attrs)
            elif attrs['errors']['type'] == 'record_not_found':
                raise NotFound(attrs)
            elif attrs['errors']['type'] == 'rate_limit_exceeded':
                raise RateLimitExceeded(attrs)
            elif attrs['errors']['type'] == 'application_error':
                raise ApplicationError(attrs)
            else:
                raise APIError(attrs)
        return attrs

    # handy delegate methods
    def get(self, path, params={}): return self.request('get', path, params)
    def put(self, path, params={}): return self.request('put', path, params)
    def post(self, path, params={}): return self.request('post', path, params)
    def delete(self, path, params={}): return self.request('delete', path, params)

    def get_collection(self, path, **opts):
        return uservoice.Collection(self, path, **opts)

    def login_as(self, email):
        resp = self.post('/api/v1/users/login_as', {
            'request_token': self.get_request_token().token,
            'user': { 'email': email }
        })
        if 'token' in resp:
            token = resp['token']['oauth_token']
            secret = resp['token']['oauth_token_secret']
            return self.login_with_access_token(token, secret)
        else:
            raise Unauthorized(resp)

    def login_as_owner(self):
        resp = self.post('/api/v1/users/login_as_owner', {
            'request_token': self.get_request_token().token
        })
        if 'token' in resp:
            token = resp['token']['oauth_token']
            secret = resp['token']['oauth_token_secret']
            return self.login_with_access_token(token, secret)
        else:
            raise Unauthorized(resp)

    def __enter__(self):
        return self

    def __exit__(self, type, value, traceback):
        pass


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:util="http://www.springframework.org/schema/util"
       xmlns:p="http://www.springframework.org/schema/p"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
                    http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">

    <bean id="characterEncodingFilter" class="org.springframework.web.filter.CharacterEncodingFilter"
            p:encoding="${httprequest.web.encoding:UTF-8}"
            p:forceEncoding="${httprequest.web.encoding.force:true}" />

    <bean id="responseHeadersSecurityFilter" class="org.apereo.cas.security.ResponseHeadersEnforcementFilter"
          p:enableCacheControl="${httpresponse.header.cache:false}"
          p:enableStrictTransportSecurity="${httpresponse.header.hsts:false}"
          p:enableXFrameOptions="${httpresponse.header.xframe:false}"
          p:enableXContentTypeOptions="${httpresponse.header.xcontent:false}"
          p:enableXSSProtection="${httpresponse.header.xss:false}" />

    <bean id="requestParameterSecurityFilter"
          class="org.apereo.cas.security.RequestParameterPolicyEnforcementFilter"
          p:allowMultiValueParameters="${cas.http.allow.multivalue.params:false}">
        <property name="parametersToCheck">
            <bean class="org.springframework.util.StringUtils" factory-method="commaDelimitedListToSet">
                <constructor-arg type="java.lang.String"
                                 value="${cas.http.check.params:ticket,service,renew,gateway,warn,method,target,SAMLart,pgtUrl,pgt,pgtId,pgtIou,targetService,entityId}"/>
            </bean>
        </property>
        <property name="charactersToForbid">
            <util:set />
        </property>
        <property name="onlyPostParameters">
            <bean class="org.springframework.util.StringUtils" factory-method="commaDelimitedListToSet">
                <constructor-arg type="java.lang.String"
                                 value="${cas.http.allow.post.params:username,password}"/>
            </bean>
        </property>
    </bean>
</beans>


text:
.. _command_line_tool_index:

Command Line Tool Index
=======================

.. toctree::
   :maxdepth: 1
   :caption: Setting up and running a simulation:

    w_init       <command_line_tools/w_init>
    w_bins       <command_line_tools/w_bins>
    w_run        <command_line_tools/w_run>
    w_truncate   <command_line_tools/w_truncate>
    w_fork       <command_line_tools/w_fork>

.. toctree::
   :maxdepth: 1
   :caption: Analyzing a simulation:

    w_assign     <command_line_tools/w_assign>
    w_trace      <command_line_tools/w_trace>
    w_fluxanl    <command_line_tools/w_fluxanl>
    w_ipa        <command_line_tools/w_ipa>
    w_pdist      <command_line_tools/w_pdist>
    w_succ       <command_line_tools/w_succ>
    w_crawl      <command_line_tools/w_crawl>
    w_direct     <command_line_tools/w_direct>
    w_select     <command_line_tools/w_select>
    w_states     <command_line_tools/w_states>
    w_eddist     <command_line_tools/w_eddist>
    w_ntop       <command_line_tools/w_ntop>

.. toctree::
   :maxdepth: 1
   :caption: Plotting tools:

    plothist     <command_line_tools/plothist>
    ploterr      <command_line_tools/ploterr>

.. toctree::
   :maxdepth: 1
   :caption: Deprecated tools:

    w_kinavg     <command_line_tools/w_kinavg>
    w_kinetics   <command_line_tools/w_kinetics>
    w_stateprobs <command_line_tools/w_stateprobs>


text:
#include "SkTextureCompressor.h"
#include "SkTextureCompressor_Blitter.h"
#include "SkTextureCompressor_Utils.h"

#include "SkBlitter.h"
#include "SkEndian.h"

// #define COMPRESS_R11_EAC_SLOW 1
// #define COMPRESS_R11_EAC_FAST 1
#define COMPRESS_R11_EAC_FASTEST 1

// Blocks compressed into R11 EAC are represented as follows:
// 0000000000000000000000000000000000000000000000000000000000000000
// |base_cw|mod|mul|  ----------------- indices -------------------
//
// To reconstruct the value of a given pixel, we use the formula:
// clamp[0, 2047](base_cw * 8 + 4 + mod_val*mul*8)
//
// mod_val is chosen from a palette of values based on the index of the
// given pixel. The palette is chosen by the value stored in mod.
// This formula returns a value between 0 and 2047, which is converted
// to a float from 0 to 1 in OpenGL.
//
// If mul is zero, then we set mul = 1/8, so that the formula becomes
// clamp[0, 2047](base_cw * 8 + 4 + mod_val)

static const int kNumR11EACPalettes = 16;
static const int kR11EACPaletteSize = 8;
static const int kR11EACModifierPalettes[kNumR11EACPalettes][kR11EACPaletteSize] = {
    {-3, -6, -9, -15, 2, 5, 8, 14},
    {-3, -7, -10, -13, 2, 6, 9, 12},
    {-2, -5, -8, -13, 1, 4, 7, 12},
    {-2, -4, -6, -13, 1, 3, 5, 12},
    {-3, -6, -8, -12, 2, 5, 7, 11},
    {-3, -7, -9, -11, 2, 6, 8, 10},
    {-4, -7, -8, -11, 3, 6, 7, 10},
    {-3, -5, -8, -11, 2, 4, 7, 10},
    {-2, -6, -8, -10, 1, 5, 7, 9},
    {-2, -5, -8, -10, 1, 4, 7, 9},
    {-2, -4, -8, -10, 1, 3, 7, 9},
    {-2, -5, -7, -10, 1, 4, 6, 9},
    {-3, -4, -7, -10, 2, 3, 6, 9},
    {-1, -2, -3, -10, 0, 1, 2, 9},
    {-4, -6, -8, -9, 3, 5, 7, 8},
    {-3, -5, -7, -9, 2, 4, 6, 8}
};

#if COMPRESS_R11_EAC_SLOW

// Pack the base codeword, palette, and multiplier into the 64 bits necessary
// to decode it.
static uint64_t pack_r11eac_block(uint16_t base_cw, uint16_t palette, uint16_t multiplier,
                                  uint64_t indices) {
    SkASSERT(palette < 16);
    SkASSERT(multiplier < 16);
    SkASSERT(indices < (static_cast<uint64_t>(1) << 48));

    const uint64_t b = static_cast<uint64_t>(base_cw) << 56;
    const uint64_t m = static_cast<uint64_t>(multiplier) << 52;
    const uint64_t p = static_cast<uint64_t>(palette) << 48;
    return SkEndian_SwapBE64(b | m | p | indices);
}

// Given a base codeword, a modifier, and a multiplier, compute the proper
// pixel value in the range [0, 2047].
static uint16_t compute_r11eac_pixel(int base_cw, int modifier, int multiplier) {
    int ret = (base_cw * 8 + 4) + (modifier * multiplier * 8);
    return (ret > 2047)? 2047 : ((ret < 0)? 0 : ret);
}

// Compress a block into R11 EAC format.
// The compression works as follows:
// 1. Find the center of the span of the block's values. Use this as the base codeword.
// 2. Choose a multiplier based roughly on the size of the span of block values
// 3. Iterate through each palette and choose the one with the most accurate
// modifiers.
static inline uint64_t compress_heterogeneous_r11eac_block(const uint8_t block[16]) {
    // Find the center of the data...
    uint16_t bmin = block[0];
    uint16_t bmax = block[0];
    for (int i = 1; i < 16; ++i) {
        bmin = SkTMin<uint16_t>(bmin, block[i]);
        bmax = SkTMax<uint16_t>(bmax, block[i]);
    }

    uint16_t center = (bmax + bmin) >> 1;
    SkASSERT(center <= 255);

    // Based on the min and max, we can guesstimate a proper multiplier
    // This is kind of a magic choice to start with.
    uint16_t multiplier = (bmax - center) / 10;

    // Now convert the block to 11 bits and transpose it to match
    // the proper layout
    uint16_t cblock[16];
    for (int i = 0; i < 4; ++i) {
        for (int j = 0; j < 4; ++j) {
            int srcIdx = i*4+j;
            int dstIdx = j*4+i;
            cblock[dstIdx] = (block[srcIdx] << 3) | (block[srcIdx] >> 5);
        }
    }

    // Finally, choose the proper palette and indices
    uint32_t bestError = 0xFFFFFFFF;
    uint64_t bestIndices = 0;
    uint16_t bestPalette = 0;
    for (uint16_t paletteIdx = 0; paletteIdx < kNumR11EACPalettes; ++paletteIdx) {
        const int *palette = kR11EACModifierPalettes[paletteIdx];

        // Iterate through each pixel to find the best palette index
        // and update the indices with the choice. Also store the error
        // for this palette to be compared against the best error...
        uint32_t error = 0;
        uint64_t indices = 0;
        for (int pixelIdx = 0; pixelIdx < 16; ++pixelIdx) {
            const uint16_t pixel = cblock[pixelIdx];

            // Iterate through each palette value to find the best index
            // for this particular pixel for this particular palette.
            uint16_t bestPixelError =
                abs_diff(pixel, compute_r11eac_pixel(center, palette[0], multiplier));
            int bestIndex = 0;
            for (int i = 1; i < kR11EACPaletteSize; ++i) {
                const uint16_t p = compute_r11eac_pixel(center, palette[i], multiplier);
                const uint16_t perror = abs_diff(pixel, p);

                // Is this index better?
                if (perror < bestPixelError) {
                    bestIndex = i;
                    bestPixelError = perror;
                }
            }

            SkASSERT(bestIndex < 8);

            error += bestPixelError;
            indices <<= 3;
            indices |= bestIndex;
        }

        SkASSERT(indices < (static_cast<uint64_t>(1) << 48));

        // Is this palette better?
        if (error < bestError) {
            bestPalette = paletteIdx;
            bestIndices = indices;
            bestError = error;
        }
    }

    // Finally, pack everything together...
    return pack_r11eac_block(center, bestPalette, multiplier, bestIndices);
}
#endif // COMPRESS_R11_EAC_SLOW

#if COMPRESS_R11_EAC_FAST
// This function takes into account that most blocks that we compress have a gradation from
// fully opaque to fully transparent. The compression scheme works by selecting the
// palette and multiplier that has the tightest fit to the 0-255 range. This is encoded
// as the block header (0x8490). The indices are then selected by considering the top
// three bits of each alpha value. For alpha masks, this reduces the dynamic range from
// 17 to 8, but the quality is still acceptable.
//
// There are a few caveats that need to be taken care of...
//
// 1. The block is read in as scanlines, so the indices are stored as:
//     0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
//    However, the decomrpession routine reads them in column-major order, so they
//    need to be packed as:
//     0 4 8 12 1 5 9 13 2 6 10 14 3 7 11 15
//    So when reading, they must be transposed.
//
// 2. We cannot use the top three bits as an index directly, since the R11 EAC palettes
//    above store the modulation values first decreasing and then increasing:
//      e.g. {-3, -6, -9, -15, 2, 5, 8, 14}
//    Hence, we need to convert the indices with the following mapping:
//      From: 0 1 2 3 4 5 6 7
//      To:   3 2 1 0 4 5 6 7
static inline uint64_t compress_heterogeneous_r11eac_block(const uint8_t block[16]) {
    uint64_t retVal = static_cast<uint64_t>(0x8490) << 48;
    for(int i = 0; i < 4; ++i) {
        for(int j = 0; j < 4; ++j) {
            const int shift = 45-3*(j*4+i);
            SkASSERT(shift <= 45);
            const uint64_t idx = block[i*4+j] >> 5;
            SkASSERT(idx < 8);

            // !SPEED! This is slightly faster than having an if-statement.
            switch(idx) {
                case 0:
                case 1:
                case 2:
                case 3:
                    retVal |= (3-idx) << shift;
                    break;
                default:
                    retVal |= idx << shift;
                    break;
            }
        }
    }

    return SkEndian_SwapBE64(retVal);
}
#endif // COMPRESS_R11_EAC_FAST

#if (COMPRESS_R11_EAC_SLOW) || (COMPRESS_R11_EAC_FAST)
static uint64_t compress_r11eac_block(const uint8_t block[16]) {
    // Are all blocks a solid color?
    bool solid = true;
    for (int i = 1; i < 16; ++i) {
        if (block[i] != block[0]) {
            solid = false;
            break;
        }
    }

    if (solid) {
        switch(block[0]) {
            // Fully transparent? We know the encoding...
            case 0:
                // (0x0020 << 48) produces the following:
                // basw_cw: 0
                // mod: 0, palette: {-3, -6, -9, -15, 2, 5, 8, 14}
                // multiplier: 2
                // mod_val: -3
                //
                // this gives the following formula:
                // clamp[0, 2047](0*8+4+(-3)*2*8) = 0
                //
                // Furthermore, it is impervious to endianness:
                // 0x0020000000002000ULL
                // Will produce one pixel with index 2, which gives:
                // clamp[0, 2047](0*8+4+(-9)*2*8) = 0
                return 0x0020000000002000ULL;

            // Fully opaque? We know this encoding too...
            case 255:

                // -1 produces the following:
                // basw_cw: 255
                // mod: 15, palette: {-3, -5, -7, -9, 2, 4, 6, 8}
                // mod_val: 8
                //
                // this gives the following formula:
                // clamp[0, 2047](255*8+4+8*8*8) = clamp[0, 2047](2556) = 2047
                return 0xFFFFFFFFFFFFFFFFULL;

            default:
                // !TODO! krajcevski:
                // This will probably never happen, since we're using this format
                // primarily for compressing alpha maps. Usually the only
                // non-fullly opaque or fully transparent blocks are not a solid
                // intermediate color. If we notice that they are, then we can
                // add another optimization...
                break;
        }
    }

    return compress_heterogeneous_r11eac_block(block);
}

// This function is used by R11 EAC to compress 4x4 blocks
// of 8-bit alpha into 64-bit values that comprise the compressed data.
// We need to make sure that the dimensions of the src pixels are divisible
// by 4, and copy 4x4 blocks one at a time for compression.
typedef uint64_t (*A84x4To64BitProc)(const uint8_t block[]);

static bool compress_4x4_a8_to_64bit(uint8_t* dst, const uint8_t* src,
                                     int width, int height, size_t rowBytes,
                                     A84x4To64BitProc proc) {
    // Make sure that our data is well-formed enough to be considered for compression
    if (0 == width || 0 == height || (width % 4) != 0 || (height % 4) != 0) {
        return false;
    }

    int blocksX = width >> 2;
    int blocksY = height >> 2;

    uint8_t block[16];
    uint64_t* encPtr = reinterpret_cast<uint64_t*>(dst);
    for (int y = 0; y < blocksY; ++y) {
        for (int x = 0; x < blocksX; ++x) {
            // Load block
            for (int k = 0; k < 4; ++k) {
                memcpy(block + k*4, src + k*rowBytes + 4*x, 4);
            }

            // Compress it
            *encPtr = proc(block);
            ++encPtr;
        }
        src += 4 * rowBytes;
    }

    return true;
}
#endif  // (COMPRESS_R11_EAC_SLOW) || (COMPRESS_R11_EAC_FAST)

// This function converts an integer containing four bytes of alpha
// values into an integer containing four bytes of indices into R11 EAC.
// Note, there needs to be a mapping of indices:
// 0 1 2 3 4 5 6 7
// 3 2 1 0 4 5 6 7
//
// To compute this, we first negate each byte, and then add three, which
// gives the mapping
// 3 2 1 0 -1 -2 -3 -4
//
// Then we mask out the negative values, take their absolute value, and
// add three.
//
// Most of the voodoo in this function comes from Hacker's Delight, section 2-18
static inline uint32_t convert_indices(uint32_t x) {
    // Take the top three bits...
    x = SkTextureCompressor::ConvertToThreeBitIndex(x);

    // Negate...
    x = ~((0x80808080 - x) ^ 0x7F7F7F7F);

    // Add three
    const uint32_t s = (x & 0x7F7F7F7F) + 0x03030303;
    x = ((x ^ 0x03030303) & 0x80808080) ^ s;

    // Absolute value
    const uint32_t a = x & 0x80808080;
    const uint32_t b = a >> 7;

    // Aside: mask negatives (m is three if the byte was negative)
    const uint32_t m = (a >> 6) | b;

    // .. continue absolute value
    x = (x ^ ((a - b) | a)) + b;

    // Add three
    return x + m;
}

#if COMPRESS_R11_EAC_FASTEST
template<unsigned shift>
static inline uint64_t swap_shift(uint64_t x, uint64_t mask) {
    const uint64_t t = (x ^ (x >> shift)) & mask;
    return x ^ t ^ (t << shift);
}

static inline uint64_t interleave6(uint64_t topRows, uint64_t bottomRows) {
    // If our 3-bit block indices are laid out as:
    // a b c d
    // e f g h
    // i j k l
    // m n o p
    //
    // This function expects topRows and bottomRows to contain the first two rows
    // of indices interleaved in the least significant bits of a and b. In other words...
    //
    // If the architecture is big endian, then topRows and bottomRows will contain the following:
    // Bits 31-0:
    // a: 00 a e 00 b f 00 c g 00 d h
    // b: 00 i m 00 j n 00 k o 00 l p
    //
    // If the architecture is little endian, then topRows and bottomRows will contain
    // the following:
    // Bits 31-0:
    // a: 00 d h 00 c g 00 b f 00 a e
    // b: 00 l p 00 k o 00 j n 00 i m
    //
    // This function returns a 48-bit packing of the form:
    // a e i m b f j n c g k o d h l p
    //
    // !SPEED! this function might be even faster if certain SIMD intrinsics are
    // used..

    // For both architectures, we can figure out a packing of the bits by
    // using a shuffle and a few shift-rotates...
    uint64_t x = (static_cast<uint64_t>(topRows) << 32) | static_cast<uint64_t>(bottomRows);

    // x: 00 a e 00 b f 00 c g 00 d h 00 i m 00 j n 00 k o 00 l p

    x = swap_shift<10>(x, 0x3FC0003FC00000ULL);

    // x: b f 00 00 00 a e c g i m 00 00 00 d h j n 00 k o 00 l p

    x = (x | ((x << 52) & (0x3FULL << 52)) | ((x << 20) & (0x3FULL << 28))) >> 16;

    // x: 00 00 00 00 00 00 00 00 b f l p a e c g i m k o d h j n

    x = swap_shift<6>(x, 0xFC0000ULL);

#if defined (SK_CPU_BENDIAN)
    // x: 00 00 00 00 00 00 00 00 b f l p a e i m c g k o d h j n

    x = swap_shift<36>(x, 0x3FULL);

    // x: 00 00 00 00 00 00 00 00 b f j n a e i m c g k o d h l p

    x = swap_shift<12>(x, 0xFFF000000ULL);
#else
    // If our CPU is little endian, then the above logic will
    // produce the following indices:
    // x: 00 00 00 00 00 00 00 00 c g i m d h l p b f j n a e k o

    x = swap_shift<36>(x, 0xFC0ULL);

    // x: 00 00 00 00 00 00 00 00 a e i m d h l p b f j n c g k o

    x = (x & (0xFFFULL << 36)) | ((x & 0xFFFFFFULL) << 12) | ((x >> 24) & 0xFFFULL);
#endif

    // x: 00 00 00 00 00 00 00 00 a e i m b f j n c g k o d h l p
    return x;
}

// This function follows the same basic procedure as compress_heterogeneous_r11eac_block
// above when COMPRESS_R11_EAC_FAST is defined, but it avoids a few loads/stores and
// tries to optimize where it can using SIMD.
static uint64_t compress_r11eac_block_fast(const uint8_t* src, size_t rowBytes) {
    // Store each row of alpha values in an integer
    const uint32_t alphaRow1 = *(reinterpret_cast<const uint32_t*>(src));
    const uint32_t alphaRow2 = *(reinterpret_cast<const uint32_t*>(src + rowBytes));
    const uint32_t alphaRow3 = *(reinterpret_cast<const uint32_t*>(src + 2*rowBytes));
    const uint32_t alphaRow4 = *(reinterpret_cast<const uint32_t*>(src + 3*rowBytes));

    // Check for solid blocks. The explanations for these values
    // can be found in the comments of compress_r11eac_block above
    if (alphaRow1 == alphaRow2 && alphaRow1 == alphaRow3 && alphaRow1 == alphaRow4) {
        if (0 == alphaRow1) {
            // Fully transparent block
            return 0x0020000000002000ULL;
        } else if (0xFFFFFFFF == alphaRow1) {
            // Fully opaque block
            return 0xFFFFFFFFFFFFFFFFULL;
        }
    }

    // Convert each integer of alpha values into an integer of indices
    const uint32_t indexRow1 = convert_indices(alphaRow1);
    const uint32_t indexRow2 = convert_indices(alphaRow2);
    const uint32_t indexRow3 = convert_indices(alphaRow3);
    const uint32_t indexRow4 = convert_indices(alphaRow4);

    // Interleave the indices from the top two rows and bottom two rows
    // prior to passing them to interleave6. Since each index is at most
    // three bits, then each byte can hold two indices... The way that the
    // compression scheme expects the packing allows us to efficiently pack
    // the top two rows and bottom two rows. Interleaving each 6-bit sequence
    // and tightly packing it into a uint64_t is a little trickier, which is
    // taken care of in interleave6.
    const uint32_t r1r2 = (indexRow1 << 3) | indexRow2;
    const uint32_t r3r4 = (indexRow3 << 3) | indexRow4;
    const uint64_t indices = interleave6(r1r2, r3r4);

    // Return the packed incdices in the least significant bits with the magic header
    return SkEndian_SwapBE64(0x8490000000000000ULL | indices);
}

static bool compress_a8_to_r11eac_fast(uint8_t* dst, const uint8_t* src,
                                       int width, int height, size_t rowBytes) {
    // Make sure that our data is well-formed enough to be considered for compression
    if (0 == width || 0 == height || (width % 4) != 0 || (height % 4) != 0) {
        return false;
    }

    const int blocksX = width >> 2;
    const int blocksY = height >> 2;

    uint64_t* encPtr = reinterpret_cast<uint64_t*>(dst);
    for (int y = 0; y < blocksY; ++y) {
        for (int x = 0; x < blocksX; ++x) {
            // Compress it
            *encPtr = compress_r11eac_block_fast(src + 4*x, rowBytes);
            ++encPtr;
        }
        src += 4 * rowBytes;
    }
    return true;
}
#endif // COMPRESS_R11_EAC_FASTEST

////////////////////////////////////////////////////////////////////////////////
//
// Utility functions used by the blitter
//
////////////////////////////////////////////////////////////////////////////////

// The R11 EAC format expects that indices are given in column-major order. Since
// we receive alpha values in raster order, this usually means that we have to use
// pack6 above to properly pack our indices. However, if our indices come from the
// blitter, then each integer will be a column of indices, and hence can be efficiently
// packed. This function takes the bottom three bits of each byte and places them in
// the least significant 12 bits of the resulting integer.
static inline uint32_t pack_indices_vertical(uint32_t x) {
#if defined (SK_CPU_BENDIAN)
    return
        (x & 7) |
        ((x >> 5) & (7 << 3)) |
        ((x >> 10) & (7 << 6)) |
        ((x >> 15) & (7 << 9));
#else
    return
        ((x >> 24) & 7) |
        ((x >> 13) & (7 << 3)) |
        ((x >> 2) & (7 << 6)) |
        ((x << 9) & (7 << 9));
#endif
}

// This function returns the compressed format of a block given as four columns of
// alpha values. Each column is assumed to be loaded from top to bottom, and hence
// must first be converted to indices and then packed into the resulting 64-bit
// integer.
inline void compress_block_vertical(uint8_t* dstPtr, const uint8_t *block) {

    const uint32_t* src = reinterpret_cast<const uint32_t*>(block);
    uint64_t* dst = reinterpret_cast<uint64_t*>(dstPtr);

    const uint32_t alphaColumn0 = src[0];
    const uint32_t alphaColumn1 = src[1];
    const uint32_t alphaColumn2 = src[2];
    const uint32_t alphaColumn3 = src[3];

    if (alphaColumn0 == alphaColumn1 &&
        alphaColumn2 == alphaColumn3 &&
        alphaColumn0 == alphaColumn2) {

        if (0 == alphaColumn0) {
            // Transparent
            *dst = 0x0020000000002000ULL;
            return;
        }
        else if (0xFFFFFFFF == alphaColumn0) {
            // Opaque
            *dst = 0xFFFFFFFFFFFFFFFFULL;
            return;
        }
    }

    const uint32_t indexColumn0 = convert_indices(alphaColumn0);
    const uint32_t indexColumn1 = convert_indices(alphaColumn1);
    const uint32_t indexColumn2 = convert_indices(alphaColumn2);
    const uint32_t indexColumn3 = convert_indices(alphaColumn3);

    const uint32_t packedIndexColumn0 = pack_indices_vertical(indexColumn0);
    const uint32_t packedIndexColumn1 = pack_indices_vertical(indexColumn1);
    const uint32_t packedIndexColumn2 = pack_indices_vertical(indexColumn2);
    const uint32_t packedIndexColumn3 = pack_indices_vertical(indexColumn3);

    *dst = SkEndian_SwapBE64(0x8490000000000000ULL |
                             (static_cast<uint64_t>(packedIndexColumn0) << 36) |
                             (static_cast<uint64_t>(packedIndexColumn1) << 24) |
                             static_cast<uint64_t>(packedIndexColumn2 << 12) |
                             static_cast<uint64_t>(packedIndexColumn3));
}

static inline int get_r11_eac_index(uint64_t block, int x, int y) {
    SkASSERT(x >= 0 && x < 4);
    SkASSERT(y >= 0 && y < 4);
    const int idx = x*4 + y;
    return (block >> ((15-idx)*3)) & 0x7;
}

static void decompress_r11_eac_block(uint8_t* dst, int dstRowBytes, const uint8_t* src) {
    const uint64_t block = SkEndian_SwapBE64(*(reinterpret_cast<const uint64_t *>(src)));

    const int base_cw = (block >> 56) & 0xFF;
    const int mod = (block >> 52) & 0xF;
    const int palette_idx = (block >> 48) & 0xF;

    const int* palette = kR11EACModifierPalettes[palette_idx];

    for (int j = 0; j < 4; ++j) {
        for (int i = 0; i < 4; ++i) {
            const int idx = get_r11_eac_index(block, i, j);
            const int val = base_cw*8 + 4 + palette[idx]*mod*8;
            if (val < 0) {
                dst[i] = 0;
            } else if (val > 2047) {
                dst[i] = 0xFF;
            } else {
                dst[i] = (val >> 3) & 0xFF;
            }
        }
        dst += dstRowBytes;
    }
}

// This is the type passed as the CompressorType argument of the compressed
// blitter for the R11 EAC format. The static functions required to be in this
// struct are documented in SkTextureCompressor_Blitter.h
struct CompressorR11EAC {
    static inline void CompressA8Vertical(uint8_t* dst, const uint8_t* src) {
        compress_block_vertical(dst, src);
    }

    static inline void CompressA8Horizontal(uint8_t* dst, const uint8_t* src,
                                            int srcRowBytes) {
        *(reinterpret_cast<uint64_t*>(dst)) = compress_r11eac_block_fast(src, srcRowBytes);
    }

#if PEDANTIC_BLIT_RECT
    static inline void UpdateBlock(uint8_t* dst, const uint8_t* src, int srcRowBytes,
                                   const uint8_t* mask) {
        // TODO: krajcevski
        // The implementation of this function should be similar to that of LATC, since
        // the R11EAC indices directly correspond to pixel values.
        SkFAIL("Implement me!");
    }
#endif
};

////////////////////////////////////////////////////////////////////////////////

namespace SkTextureCompressor {

bool CompressA8ToR11EAC(uint8_t* dst, const uint8_t* src, int width, int height, size_t rowBytes) {

#if (COMPRESS_R11_EAC_SLOW) || (COMPRESS_R11_EAC_FAST)

    return compress_4x4_a8_to_64bit(dst, src, width, height, rowBytes, compress_r11eac_block);

#elif COMPRESS_R11_EAC_FASTEST

    return compress_a8_to_r11eac_fast(dst, src, width, height, rowBytes);

#else
#error "Must choose R11 EAC algorithm"
#endif
}

SkBlitter* CreateR11EACBlitter(int width, int height, void* outputBuffer,
                               SkTBlitterAllocator* allocator) {

    if ((width % 4) != 0 || (height % 4) != 0) {
        return NULL;
    }

    // Memset the output buffer to an encoding that decodes to zero. We must do this
    // in order to avoid having uninitialized values in the buffer if the blitter
    // decides not to write certain scanlines (and skip entire rows of blocks).
    // In the case of R11, we use the encoding from recognizing all zero pixels from above.
    const int nBlocks = (width * height / 16);  // 4x4 pixel blocks.
    uint64_t *dst = reinterpret_cast<uint64_t *>(outputBuffer);
    for (int i = 0; i < nBlocks; ++i) {
        *dst = 0x0020000000002000ULL;
        ++dst;
    }

    return allocator->createT<
        SkTCompressedAlphaBlitter<4, 8, CompressorR11EAC>, int, int, void*>
        (width, height, outputBuffer);
}

void DecompressR11EAC(uint8_t* dst, int dstRowBytes, const uint8_t* src, int width, int height) {
    for (int j = 0; j < height; j += 4) {
        for (int i = 0; i < width; i += 4) {
            decompress_r11_eac_block(dst + i, dstRowBytes, src);
            src += 8;
        }
        dst += 4 * dstRowBytes;
    }
}

}  // namespace SkTextureCompressor


text:
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('core', '0001_0_8_initial'),
    ]

    operations = [
        migrations.CreateModel(
            name='Event',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('tag', models.CharField(max_length=128, unique=True, verbose_name='Tag')),
            ],
        ),
    ]


text:
namespace Scene
{
   // FXAA: Fast Approximate Anti-Aliasing
   // http://developer.download.nvidia.com/assets/gamedev/files/sdk/11/FXAA_WhitePaper.pdf

   class FXAAComponent : public Rendering::RenderPostProcess
   {
      private:
         typedef Rendering::RenderPostProcess Parent;

      protected:
         Graphics::Shader*          mFinalShader;
         Graphics::ViewTableEntry*  mFinalView;

      public:
         FXAAComponent();
         ~FXAAComponent();
         virtual void process();
   };
}

#endif


text:
class SampleIn3 {
    // class variables
    private in;
}

// class properties
class SampleIn4 {
    private var;
    set in(value) {}
    get in() {
        return this.var;
    }
}

class SampleIn5 {
    in() {} // class methods
}

// interface declarations
interface SampleIn6 {
    in: any;
}


text:
package org.sugr.gearshift.core;

import android.app.Activity;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Parcel;
import android.os.Parcelable;
import android.text.TextUtils;

import org.sugr.gearshift.G;
import org.sugr.gearshift.GearShiftApplication;
import org.sugr.gearshift.ui.util.Colorizer;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;

public class TransmissionProfile implements Parcelable, Comparable<TransmissionProfile> {
    private String id;
    private String name = "";
    private String host = "";
    private int port = 9091;
    private String path = "/transmission/rpc";
    private String username = "";
    private String password = "";

    private boolean useSSL = false;

    private int timeout = 40;
    private int retries = 3;

    private String lastDirectory;
    private boolean moveData = true;
    private boolean deleteLocal = false;
    private boolean startPaused = false;

    private Set<String> directories = new HashSet<>();

    private boolean useProxy = false;
    private String proxyHost = "";
    private int proxyPort = 8080;

    private int updateInterval = 1;
    private int fullUpdate = 2;

    private int color;

    private SharedPreferences defaultPrefs;

    public static TransmissionProfile[] readProfiles(SharedPreferences prefs) {
        Set<String> profile_ids = prefs.getStringSet(G.PREF_PROFILES, new HashSet<String>());
        TransmissionProfile[] profiles = new TransmissionProfile[profile_ids.size()];
        int index = 0;

        for (String id : profile_ids) {
            profiles[index++] = new TransmissionProfile(id, prefs);
        }

        Arrays.sort(profiles);
        return profiles;
    }

    public static String getCurrentProfileId(SharedPreferences prefs) {
        return prefs.getString(G.PREF_CURRENT_PROFILE, null);
    }

    public static void setCurrentProfile(TransmissionProfile profile, SharedPreferences prefs) {
        Editor e = prefs.edit();

        if (profile == null) {
            e.putString(G.PREF_CURRENT_PROFILE, null);
        } else {
            e.putString(G.PREF_CURRENT_PROFILE, profile.getId());
        }
        e.commit();
    }

    public static String generateId() {
        return UUID.randomUUID().toString();
    }

    public static String getPreferencesName() {
        return G.PROFILES_PREF_NAME;
    }

    public static void cleanTemporaryPreferences() {
        SharedPreferences prefs = GearShiftApplication.get().getSharedPreferences(getPreferencesName(),
            Activity.MODE_PRIVATE);
        Editor e = prefs.edit();

        for (String key : G.UNPREFIXED_PROFILE_PREFERENCE_KEYS) {
            e.remove(key);
        }

        e.apply();
    }

    public TransmissionProfile(SharedPreferences prefs) {
        id = generateId();

        this.defaultPrefs = prefs;
    }

    public TransmissionProfile(String id, SharedPreferences prefs) {
        this.id = id;

        this.defaultPrefs = prefs;
        load();
    }

    public boolean isValid() {
        return !TextUtils.isEmpty(name) && (!TextUtils.isEmpty(host) && !host.equals("example.com")) &&
                (!useProxy || ((!TextUtils.isEmpty(proxyHost) && !proxyHost.equals("example.com")) &&
                        proxyPort > 0 && proxyPort < 65535));
    }

    public String getId() {
        return id;
    }

    public String getName() {
        return name;
    }
    public String getHost() {
        return host;
    }
    public int getPort() {
        return port;
    }
    public String getPath() {
        return path;
    }
    public String getUsername() {
        return username;
    }
    public String getPassword() {
        return password;
    }
    public boolean isUseSSL() {
        return useSSL;
    }
    public int getTimeout() {
        return timeout;
    }
    public int getRetries() {
        return retries;
    }
    public Set<String> getDirectories() {
        return directories;
    }
    public void setName(String name) {
        this.name = name;
    }
    public void setHost(String host) {
        this.host = host;
    }
    public void setPort(int port) {
        this.port = port;
    }
    public void setPath(String path) {
        this.path = path;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public void setUseSSL(boolean useSSL) {
        this.useSSL = useSSL;
    }
    public void setTimeout(int timeout) {
        this.timeout = timeout;
    }
    public void setRetries(int retries) {
        this.retries = retries;
    }
    public void setDirectories(Set<String> directories) {
        this.directories = directories;
    }

    public boolean isUseProxy() {
        return useProxy;
    }

    public void setUseProxy(boolean useProxy) {
        this.useProxy = useProxy;
    }

    public String getProxyHost() {
        return proxyHost;
    }

    public void setProxyHost(String host) {
        this.proxyHost = host;
    }

    public void setProxyPort(int port) {
        this.proxyPort = port;
    }

    public int getProxyPort() {
        return proxyPort;
    }

    public int getUpdateInterval() {
        return updateInterval;
    }

    public void setUpdateInterval(int interval) {
        updateInterval = interval;
    }

    public int getFullUpdate() {
        return fullUpdate;
    }

    public void setFullUpdate(int every) {
        fullUpdate = every;
    }

    public boolean updateActiveTorrentsOnly() {
        return fullUpdate > 0;
    }

    public int getColor() {
        return color;
    }

    public void setColor(int color) {
        this.color = color;
    }

    public void load() {
        SharedPreferences pref = getPreferences();

        name = pref.getString(G.PREF_NAME + id, "").trim();
        host = pref.getString(G.PREF_HOST + id, "").trim();
        try {
             port = Integer.parseInt(pref.getString(G.PREF_PORT + id, "9091"));
            if (port < 1) {
                 port = 1;
            } else if ( port > 65535) {
                 port = 65535;
            }
        } catch (NumberFormatException e) {
             port = 65535;
        }
        path = pref.getString(G.PREF_PATH + id, "").trim();
        username = pref.getString(G.PREF_USER + id, "").trim();
        password = pref.getString(G.PREF_PASS + id, "").trim();
        useSSL = pref.getBoolean(G.PREF_SSL + id, false);
        try {
            timeout = Integer.parseInt(pref.getString(G.PREF_TIMEOUT + id, "-1"));
        } catch (NumberFormatException e) {
            timeout = Integer.MAX_VALUE;
        }
        try {
            retries = Integer.parseInt(pref.getString(G.PREF_RETRIES + id, "-1"));
        } catch (NumberFormatException e) {
            retries = Integer.MAX_VALUE;
        }
        directories = pref.getStringSet(G.PREF_DIRECTORIES + id, new HashSet<String>());

        lastDirectory = pref.getString(G.PREF_LAST_DIRECTORY + id, "");
        moveData = pref.getBoolean(G.PREF_MOVE_DATA + id, true);
        deleteLocal = pref.getBoolean(G.PREF_DELETE_LOCAL + id, false);
        startPaused = pref.getBoolean(G.PREF_START_PAUSED + id, false);

        useProxy = pref.getBoolean(G.PREF_PROXY + id, false);
        proxyHost = pref.getString(G.PREF_PROXY_HOST + id, "").trim();
        try {
            proxyPort = Integer.parseInt(pref.getString(G.PREF_PROXY_PORT + id, "8080"));
            if (proxyPort < 1) {
                proxyPort = 1;
            } else if ( proxyPort > 65535) {
                proxyPort = 65535;
            }
        } catch (NumberFormatException e) {
            proxyPort = 65535;
        }

        try {
            updateInterval = Integer.parseInt(pref.getString(G.PREF_UPDATE_INTERVAL + id, "1"));
        } catch (NumberFormatException e) {
            updateInterval = 1;
        }
        try {
            fullUpdate = Integer.parseInt(pref.getString(G.PREF_FULL_UPDATE + id, "2"));
        } catch (NumberFormatException e) {
            fullUpdate = 2;
        }

        color = pref.getInt(G.PREF_COLOR + id, 0);
        if (color == 0) {
            color = Colorizer.defaultColor(GearShiftApplication.get());
        }
    }

    public void save() {
        SharedPreferences pref = getPreferences();
        Editor e = pref.edit();

        e.putString(G.PREF_NAME + id, name);
        e.putString(G.PREF_HOST + id, host);
        e.putString(G.PREF_PORT + id, Integer.toString(port));
        e.putString(G.PREF_PATH + id, path);
        e.putString(G.PREF_USER + id, username);
        e.putString(G.PREF_PASS + id, password);
        e.putBoolean(G.PREF_SSL + id, useSSL);
        e.putString(G.PREF_TIMEOUT + id, Integer.toString(timeout));
        e.putString(G.PREF_RETRIES + id, Integer.toString(retries));
        e.putStringSet(G.PREF_DIRECTORIES + id, directories);
        e.putBoolean(G.PREF_PROXY + id, useProxy);
        e.putString(G.PREF_PROXY_HOST + id, proxyHost);
        e.putString(G.PREF_PROXY_PORT + id, Integer.toString(proxyPort));
        e.putString(G.PREF_UPDATE_INTERVAL + id, Integer.toString(updateInterval));
        e.putString(G.PREF_FULL_UPDATE + id, Integer.toString(fullUpdate));
        e.putInt(G.PREF_COLOR + id, color);

        e.commit();

        G.logD("Saving profile to prefs: id %s, name %s, host %s, port %d",
            new Object[] {id, name, host, port});

        e = defaultPrefs.edit();

        Set<String> ids = defaultPrefs.getStringSet(G.PREF_PROFILES, new HashSet<String>());

        if (ids.add(id)) {
            e.remove(G.PREF_PROFILES);
            e.apply();

            if (ids.size() == 1 && !defaultPrefs.getString(G.PREF_CURRENT_PROFILE, "").equals(id)) {
                e.putString(G.PREF_CURRENT_PROFILE, id);
            }
            e.putStringSet(G.PREF_PROFILES, ids);
            e.commit();

            G.logD("Adding the profile %s to the set of profiles",
                    new Object[] {id});
        }
    }

    public void delete() {
        SharedPreferences pref = getPreferences();
        Editor e = pref.edit();

        for (String key : G.UNPREFIXED_PROFILE_PREFERENCE_KEYS) {
            e.remove(key + id);
        }

        e.commit();

        e = defaultPrefs.edit();

        Set<String> ids = defaultPrefs.getStringSet(G.PREF_PROFILES, new HashSet<String>());

        if (ids.remove(id)) {
            e.remove(G.PREF_PROFILES);
            e.apply();
            e.putStringSet(G.PREF_PROFILES, ids);
            e.commit();

            G.logD("Removing the profile %s from the set of profiles",
                    new Object[] {id});
        }

        G.logD("Deleting profile from prefs: id %s, name %s, host %s, port %d",
                new Object[] {id, name, host, port});
    }

    public void fillTemporatyPreferences() {
        SharedPreferences pref = getPreferences();
        Editor e = pref.edit();

        e.putString(G.PREF_NAME, name);
        e.putString(G.PREF_HOST, host);
        e.putString(G.PREF_PORT, Integer.toString(port));
        e.putString(G.PREF_PATH, path);
        e.putString(G.PREF_USER, username);
        e.putString(G.PREF_PASS, password);
        e.putBoolean(G.PREF_SSL, useSSL);
        e.putString(G.PREF_TIMEOUT, Integer.toString(timeout));
        e.putString(G.PREF_RETRIES, Integer.toString(retries));
        e.putStringSet(G.PREF_DIRECTORIES, directories);
        e.putBoolean(G.PREF_PROXY, useProxy);
        e.putString(G.PREF_PROXY_HOST, proxyHost);
        e.putString(G.PREF_PROXY_PORT, Integer.toString(proxyPort));
        e.putString(G.PREF_UPDATE_INTERVAL, Integer.toString(updateInterval));
        e.putString(G.PREF_FULL_UPDATE, Integer.toString(fullUpdate));
        e.putInt(G.PREF_COLOR, color);

        e.apply();
    }

    public String getLastDownloadDirectory() {
        return getPreferences().getString(G.PREF_LAST_DIRECTORY + id, "");
    }

    public void setLastDownloadDirectory(String directory) {
        SharedPreferences pref = getPreferences();
        Editor e = pref.edit();

        lastDirectory = directory;

        e.putString(G.PREF_LAST_DIRECTORY + id, directory);
        e.apply();
    }

    public boolean getMoveData() {
        return moveData;
    }

    public void setMoveData(boolean move) {
        SharedPreferences pref = getPreferences();
        Editor e = pref.edit();

        moveData = move;

        e.putBoolean(G.PREF_MOVE_DATA + id, move);
        e.apply();
    }

    public boolean getDeleteLocal() {
        return deleteLocal;
    }

    public void setDeleteLocal(boolean delete) {
        SharedPreferences pref = getPreferences();
        Editor e = pref.edit();

        deleteLocal = delete;

        e.putBoolean(G.PREF_DELETE_LOCAL + id, delete);
        e.apply();
    }

    public boolean getStartPaused() {
        return startPaused;
    }

    public void setStartPaused(boolean paused) {
        SharedPreferences pref = getPreferences();
        Editor e = pref.edit();

        startPaused = paused;

        e.putBoolean(G.PREF_START_PAUSED + id, paused);
        e.commit();
    }

    @Override public int compareTo(TransmissionProfile another) {
        return name.compareToIgnoreCase(another.getName());
    }

    @Override public String toString() {
        return name + "://" + username + '@' + host + ':' + port;
    }

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

        TransmissionProfile that = (TransmissionProfile) o;

        if (id != null ? !id.equals(that.id) : that.id != null) return false;

        return true;
    }

    @Override
    public int hashCode() {
        return id != null ? id.hashCode() : 0;
    }

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel in, int flags) {
        in.writeString(id);
        in.writeString(name);
        in.writeString(host);
        in.writeInt(port);
        in.writeString(path);
        in.writeString(username);
        in.writeString(password);
        in.writeInt(useSSL ? 1 : 0);
        in.writeInt(timeout);
        in.writeInt(retries);
        in.writeStringList(new ArrayList<>(directories));
        in.writeString(lastDirectory);
        in.writeInt(moveData ? 1 : 0);
        in.writeInt(deleteLocal ? 1 : 0);
        in.writeInt(startPaused ? 1 : 0);
        in.writeInt(useProxy ? 1 : 0);
        in.writeString(proxyHost);
        in.writeInt(proxyPort);
        in.writeInt(updateInterval);
        in.writeInt(fullUpdate);
        in.writeInt(color);
    }

    public static final Parcelable.Creator<TransmissionProfile> CREATOR
            = new Parcelable.Creator<TransmissionProfile>() {
        @Override
        public TransmissionProfile createFromParcel(Parcel in) {
            return new TransmissionProfile(in);
        }

        @Override
        public TransmissionProfile[] newArray(int size) {
            return new TransmissionProfile[size];
        }
    };

    private TransmissionProfile(Parcel in) {
        id = in.readString();
        name = in.readString();
        host = in.readString();
        port = in.readInt();
        path = in.readString();
        username = in.readString();
        password = in.readString();
        useSSL = in.readInt() == 1;
        timeout = in.readInt();
        retries = in.readInt();

        ArrayList<String> directories = new ArrayList<>();
        in.readStringList(directories);
        this.directories = new HashSet<>(directories);
        lastDirectory = in.readString();

        moveData = in.readInt() == 1;
        deleteLocal = in.readInt() == 1;
        startPaused = in.readInt() == 1;
        useProxy = in.readInt() == 1;
        proxyHost = in.readString();
        proxyPort = in.readInt();
        updateInterval = in.readInt();
        fullUpdate = in.readInt();
        color = in.readInt();
    }

    private SharedPreferences getPreferences() {
        return GearShiftApplication.get().getSharedPreferences(
            getPreferencesName(), Activity.MODE_PRIVATE);
    }

}