text:
using System.IO;

namespace MetaMorpheusGUI
{
    public class RawDataForDataGrid
    {
        #region Public Constructors

        public RawDataForDataGrid(string path)
        {
            FileName = Path.GetFileName(path);
            Use = true;
            FilePath = path;
        }

        #endregion Public Constructors

        #region Public Properties

        public bool Use { get; set; }
        public string FileName { get; private set; }
        public string Parameters { get; private set; }
        public bool InProgress { get; private set; }
        public string FilePath { get; private set; }

        #endregion Public Properties

        #region Public Methods

        /// <summary>
        /// Method to mark as in progress. Need the property setter to be private so user could not check off in GUI
        /// </summary>
        /// <param name="inProgress"></param>
        public void SetInProgress(bool inProgress)
        {
            InProgress = inProgress;
        }

        public void SetParametersText(string text)
        {
            Parameters = text;
        }

        #endregion Public Methods
    }
}


text:
Clazz.declarePackage ("J.renderbio");
Clazz.load (["J.renderbio.BioShapeRenderer"], "J.renderbio.BackboneRenderer", ["JU.C"], function () {
c$ = Clazz.decorateAsClass (function () {
this.isDataFrame = false;
Clazz.instantialize (this, arguments);
}, J.renderbio, "BackboneRenderer", J.renderbio.BioShapeRenderer);
Clazz.overrideMethod (c$, "renderBioShape",
function (bioShape) {
var showSteps = this.vwr.getBoolean (603979811) && bioShape.bioPolymer.isNucleic ();
this.isDataFrame = this.vwr.ms.isJmolDataFrameForModel (bioShape.modelIndex);
for (var i = this.bsVisible.nextSetBit (0); i >= 0; i = this.bsVisible.nextSetBit (i + 1)) {
var atomA = this.ms.at[this.leadAtomIndices[i]];
var cA = this.colixes[i];
this.mad = this.mads[i];
this.drawSegment (atomA, this.ms.at[this.leadAtomIndices[i + 1]], cA, this.colixes[i + 1], 100);
if (showSteps) {
var g = this.monomers[i];
var bps = g.getBasePairs ();
if (bps != null) {
for (var j = bps.size (); --j >= 0; ) {
var iAtom = bps.get (j).getPartnerAtom (g);
if (iAtom > i) this.drawSegment (atomA, this.ms.at[iAtom], cA, cA, 1000);
}
}}}
}, "J.shapebio.BioShape");
Clazz.defineMethod (c$, "drawSegment",
 function (atomA, atomB, colixA, colixB, max) {
if (atomA.nBackbonesDisplayed == 0 || atomB.nBackbonesDisplayed == 0 || this.ms.isAtomHidden (atomB.i) || !this.isDataFrame && atomA.distanceSquared (atomB) > max) return;
colixA = JU.C.getColixInherited (colixA, atomA.colixAtom);
colixB = JU.C.getColixInherited (colixB, atomB.colixAtom);
if (!this.isExport && !this.isPass2 && !this.setBioColix (colixA) && !this.setBioColix (colixB)) return;
var xA = atomA.sX;
var yA = atomA.sY;
var zA = atomA.sZ;
var xB = atomB.sX;
var yB = atomB.sY;
var zB = atomB.sZ;
var mad = this.mad;
if (max == 1000) mad = mad >> 1;
if (mad < 0) {
this.g3d.drawLine (colixA, colixB, xA, yA, zA, xB, yB, zB);
} else {
var width = Clazz.floatToInt (this.exportType == 1 ? mad : this.vwr.tm.scaleToScreen (Clazz.doubleToInt ((zA + zB) / 2), mad));
this.g3d.fillCylinderXYZ (colixA, colixB, 3, width, xA, yA, zA, xB, yB, zB);
}}, "JM.Atom,JM.Atom,~N,~N,~N");
});

redpajama_set_name: RedPajamaGithub


text:
package com.logicmaster63.tdgalaxy.tools;

import java.util.zip.ZipFile;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.assets.loaders.FileHandleResolver;
import com.badlogic.gdx.files.FileHandle;

public class ArchiveFileHandleResolver implements FileHandleResolver {

    private final ZipFile archive;

    public ArchiveFileHandleResolver (ZipFile archive) {
        this.archive = archive;
    }

    @Override
    public FileHandle resolve (String fileName) {
        if(fileName.endsWith(".wav") || fileName.endsWith(".mp3") || fileName.endsWith(".ogg"))
            return Tools.getRealFileHandle(fileName, archive);
        return new ArchiveFileHandle(archive, fileName);
    }
}


text:
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Resources;
using System.Diagnostics;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Input.Touch;
using Lumberjack;

namespace Lumberjack.Source.Tree
{
    public class TreeController
    {
        Viewport viewport;
        Vector2 size;
        int StandardX;

        Texture2D baseTreeTxtr;
        Texture2D[] sides = new Texture2D[3];
        /// <summary>
        /// IMPORTANT - MUST READ
        /// [0] - TREE WITH BRANCH ON LEFT
        /// [1] - TREE WITH BRANCH ON RIGHT
        /// [2] - TREE WITH NO BRANCHES
        /// </summary>

        float[] locations = new float[2];

        List<Tree> Trees;
        float DownRate;
        ContentManager content;

        public TreeController(Viewport vp, ContentManager content)
        {
            Trees = new List<Tree>();

            baseTreeTxtr = content.Load<Texture2D>(@"Tree/Base");
            sides[0] = content.Load<Texture2D>(@"Tree/LogLeft");
            sides[1] = content.Load<Texture2D>(@"Tree/LogRight");
            sides[2] = content.Load<Texture2D>(@"Tree/LogNEU");

            viewport = vp;
            float xSize = viewport.Width * 0.5f;
            size = new Vector2(xSize, xSize * 0.7407f);
            StandardX = Convert.ToInt32(viewport.Width / 2);

            DownRate = size.Y;
            float sizeX = viewport.Width * 0.25f;

            Vector2 baseSize = new Vector2(sizeX, sizeX * 0.1125f);
            Vector2 baseLocation = new Vector2(StandardX, viewport.Height - (baseSize.Y * 7));
            Tree baseLog = new Tree(baseLocation, baseSize, baseTreeTxtr);

            locations[0] = xSize / 4;
            locations[1] = StandardX - (xSize / 4);
            Trees.Add(baseLog);

            for (int i = 1; i < 12; i++)
            {
                Tree prevT = Trees[i - 1];
                Tree t = new Tree(new Vector2(locations[i % 2], prevT.location.Y - size.Y), size, sides[i % 2]);
                Trees.Add(t);
            }
        }

        public void Update()
        {
            for (int i = 1; i < Trees.Count; i++)
            {
                Trees[i].Update(DownRate);
            }

            Trees.RemoveAt(1);
            Tree prevT = Trees[Trees.Count - 1];
            Tree t = new Tree(new Vector2(locations[0], prevT.location.Y - size.Y), size, sides[0]);
            Trees.Add(t);
        }

        public void Draw(SpriteBatch spritebatch)
        {
            for (int i = 0; i < Trees.Count; i++)
            {
                Trees[i].Draw(spritebatch);
            }
        }
    }
}


text:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public abstract class CharacterComponent : MonoBehaviour
{
    public IslandComponent island;  // Never set directly other than in Unity inspector, always use Move* functions.
    public WaypointComponent islandWaypoint;
    public List<IslandComponent> islandHistory = new List<IslandComponent> ();
    public float turnSpeed = 4.0f;
    public float moveSpeed = 10.0f;
    public float positionTolerance = 0.4f;
    public float characterFeetHeight = 0.0f;
    private Quaternion facing;
    private Vector3 towardTarget;
    private Vector3 newPosition;

    public void MoveToIsland (IslandComponent newIsland)
    {
        if (newIsland != this.island) {
            // Un-occupy our existing waypoint.
            if (this.islandWaypoint) {
                this.islandWaypoint.occupiedBy = null;
            }
            // Occupy a new one.
            this.islandWaypoint = newIsland.UnoccupiedWaypoint ();
            this.islandWaypoint.occupiedBy = this;

            AudioSource walkingNoise = GetComponent<AudioSource> ();
            walkingNoise.PlayDelayed (Random.Range (0.0f, 0.5f));
        }
        transform.LookAt (this.islandWaypoint.transform.position);
        this.island = newIsland;
        islandHistory.Add (this.island);
    }

    public void MoveTowardsIsland (WorldState state, IslandComponent target)
    {
        try {
            List<IslandComponent> foundPath = state.ShortestBridgePath (this.island, target);
            if (foundPath.Count > 0) {
                this.MoveToIsland (foundPath [0]);
            }
        } catch (WorldState.NoPathException) {
            // Do nothing, no path...
        }
    }

    // Update is called once per frame
    void Update ()
    {
        Vector3 towardTarget = this.islandWaypoint.transform.position - transform.position;

        if (Mathf.Abs (towardTarget.magnitude) > positionTolerance) {
            Vector3 newPosition = transform.position + towardTarget.normalized * moveSpeed * Time.deltaTime;
            transform.position = new Vector3 (newPosition.x, characterFeetHeight, newPosition.z);

        }
    }

    public abstract void TurnUpdate (WorldState state);
}


text:
module JSONAPI
  module Resources
    module Matchers
      class Relationship

        attr_accessor(:name,
                      :relationship_type,
                      :resource,
                      :expected_class_name,
                      :expected_relation_name)

        def initialize(relationship_type, name)
          self.relationship_type = relationship_type
          self.name = name
        end

        def description
          "#{humanized_relationship_type} `#{name}`"
        end

        def humanized_relationship_type
          relationship_type.to_s.gsub('_',' ')
        end

        def matches?(resource)
          self.resource = resource

          is_serializable? &&
          has_key_in_relationships? &&
            matches_class_name? &&
            matches_relation_name?
        end

        def is_serializable?
          CheckSerialization.(self.resource)
        end

        def has_key_in_relationships?
          relationships = resource.class._relationships
          return false if relationships.blank?

          formatter = JSONAPI.configuration.key_formatter

          expected_key = formatter.format(name.to_s)
          relationship_keys = relationships.keys.map do |key|
            formatter.format(key.to_s)
          end

          relationship_keys.include?(expected_key)
        end

        def with_class_name(name)
          self.expected_class_name = name
          self
        end

        def with_relation_name(name)
          self.expected_relation_name = name
          self
        end

        def failure_message
          resource_name = resource.class.name.demodulize
          message = ["expected `#{resource_name}` to #{humanized_relationship_type} `#{name}`"]
          if self.expected_class_name
            message << "with class name `#{self.expected_class_name}`"
          end
          if self.expected_relation_name
            message << "with relation name `#{self.expected_relation_name}`"
          end
          message.join(" ")
        end

        def matches_class_name?
          return true if self.expected_class_name.nil?
          association = resource.class._relationships[name]
          actual_class_name = association.class_name
          self.expected_class_name == actual_class_name
        end

        def matches_relation_name?
          return true if self.expected_relation_name.nil?
          association = resource.class._relationships[name]
          actual_relation_name = association.relation_name({})
          self.expected_relation_name == actual_relation_name
        end

      end
    end
  end
end


text:
<?php

class OAClient extends OAAPIBase
{
	protected $sessionId;
	protected $curlHandle;
	protected $rawResponse;
	protected $debug = true;
	protected $config;

	public function __construct( OAClientConfig $config=null )
	{
		if ( $config )
		{
			$this->config = $config;
		}
		else
		{
			$this->config = new OAClientConfig();
		}

	}

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

	public function connect( $apiToken='', $apiKey='', $endpointUrl='', $portNumber='' )
	{
		if ( $apiToken )
			$this->config->apiToken = $apiToken;
		if ( $apiKey )
			$this->config->apiKey = $apiKey;
		if ( $endpointUrl )
			$this->config->endpointUrl = $endpointUrl;
		if ( $portNumber )
			$this->config->portNumber = $portNumber;

		$connectRequest = new OAConnectRequest();
		$connectRequest->user_api_token = $this->config->apiToken;
		$connectRequest->user_api_key = $this->config->apiKey;

		$response = $this->sendRequest( $connectRequest );

		$body = json_decode( $response->body );

		if ( $body->success )
		{
			$this->sessionId = $response->session_id;
		}
		else
		{
			$this->sessionId = null;
			throw new Exception( $body->error );
		}
		return $response;
	}

	public function disconnect()
	{
		$disconnectRequest = new OADisconnectRequest();
		$response = $this->sendRequest( $disconnectRequest );
		if ( $response->success )
		{
			curl_close( $this->curlHandle );
		}
		return $response;
	}

	public function sendRequest( OAAPIRequest $request )
	{
		$params = $request->getParams();
		$queryString = '';
		$connectUrl = $this->config->endpointUrl . $request->action;

		$fieldPairs = array();
		foreach( $params as $key=>$value )
		{
			$fieldPairs[] = $key . '=' . urlencode($value);
		}
		$queryString = implode( $fieldPairs, '&' );

		$this->curlHandle = curl_init();

		// Set the URL, POST var count, and POST data
		$options = array(
				CURLOPT_RETURNTRANSFER => 1,
				CURLOPT_HEADER => 0,
				CURLOPT_TIMEOUT => 5,
				CURLOPT_URL => $connectUrl,
				CURLOPT_POST => count( $params ),
				CURLOPT_POSTFIELDS => $queryString,
				CURLOPT_PORT => $this->config->portNumber,
			);

		if ( $this->sessionId )
		{
			$options[CURLOPT_COOKIE] = 'PHPSESSID=' . $this->sessionId;
		}

		curl_setopt_array( $this->curlHandle, $options );

		$this->response = $this->execCurl();

		if ( $this->debug && ! $this->response->success )
		{
			$this->response->postFields = $queryString;
		}

		$body = json_decode( $this->response->body );

		//if ( $body->success )
		//{
		$this->response->success = $this->response->success && $body->success;
		//}

		return $this->response;

	}

	protected function execCurl()
	{
		$this->rawResponse = curl_exec( $this->curlHandle );

		$error = curl_error( $this->curlHandle );

		$response = new OAAPIResponse();

		if ( $error )
		{
			$response->error = $error;
			return $response;
		}

		$response->body = $this->rawResponse;
		$response->httpCode = curl_getinfo( $this->curlHandle, CURLINFO_HTTP_CODE );
		$response->lastUrl = curl_getinfo( $this->curlHandle, CURLINFO_EFFECTIVE_URL );

		if ( $jsonResult = json_decode( $response->body ) )
		{
			$response->success = false;
			if( isset($jsonResult->success) ) {
				$response->success = $jsonResult->success;
			}

			if (isset($jsonResult->data))
			{
				if ( $jsonResult->data instanceof stdClass )
				{
					$response->merge( $jsonResult->data );
				}
				else
				{
					$response->setRecords( $jsonResult->data );
				}
			} else {
				$response->merge( $jsonResult );
			}
		}
		else
		{
			$response->error = 'Unable to json_decode the response from the server.';
		}

		return $response;
	}

}


text:
All notable changes to this project will be documented in this file.

## Unreleased

## 1.0.8 - 2016-01-26
### Fixed
- Fixed an issue where `get_application_access_token` using Graph API versions 2.3+ would
  return JSON instead of a query string, resulting in an `AttributeError` to be thrown.

## 1.0.7 - 2015-09-08
### Fixed
- Fixed an issue where `get_extended_access_token` using Graph API versions 2.3+ would
  return JSON instead of a query string, resulting in an `AttributeError` to be thrown.
- `FacebookError` instances now contain additional data about the error.

## 1.0.6 - 2015-01-07
### Fixed
- Fixed an issue where pagination of nested resources would break.

## 1.0.5 - 2015-01-05
### Added
- You may now specify the API version to use with `GraphAPI`.

## 1.0.4 - 2014-09-28
### Added
- Facepy now proxies the error message from Facebook for 5XX responses.
- Facepy now raises `FacebookError` on any response in the 5XX range.

## 1.0.3 - 2014-06-17
### Added
- `FacebookError`, `HTTPError`, `OAuthError` and `SignedRequestError` are now available
from the `facepy` module for convenience.
- `GraphAPI` now raises `FacebookError` upon receiving HTTP 500 from Facebook.

## 1.0.2 - 2014-06-10
### Added
- `GraphAPI` now accepts an argument `timeout`, which can be either `None` or an
integer describing how many seconds to wait for a response.

## 1.0.1 - 2014-05-22
### Fixed
- Fixed an issue where six would cause an `ImportError` unless already
installed. It is now a direct dependency.

## 1.0.0 - 2014-05-22
### Added
- `GraphAPI` now supports securing Graph API requests with application secret proofs.
- `GraphAPI#post` now supports user-generated images.

### Fixed
- The last bit of the tuple returned from `get_extended_access_token` is now `None`
if the access token won't expire.
- `GraphAPI#batch` can now handle more than 50 requests at a time.
- Fixed a bug that caused unicode URLs to fail.

## 0.9.0 - 2014-02-12
### Added
- Changed `GraphAPI` methods to return `decimal.Decimal` instances for floating-point
numbers instead of `float`, which can cause precision losses not acceptable for
financial operations.
- Nested dictionaries, lists and sets are now automatically encoded as JSON.
- You may now elect to not verify Facebook's SSL certificate.
- You may now substitute colons with underscores in keys such as `fb:explicitly_shared`.
- Facepy is now compatible with Python 3.

### Fixed
- Fixed a bug that caused parsing signed requests to fail when the `user` key
is not present.

## 0.8.4 - 2012-11-13
### Fixed
- Fixed a bug that caused a KeyError for signed requests that were missing
some keys for its "page" attribute.

## 0.8.3 - 2012-10-04
### Added
- You may now extend access tokens with `get_extended_access_token`.

### Fixed
- Fixed a bug that caused batch requests with a body to fail.
- Fixed a bug that caused paths that started with a slash to fail.
- Fixed a bug that caused exception messages to be omitted.

## 0.8.2 - 2012-07-03
### Added
- Facepy exceptions may now be pickled.

## 0.8.1 - 2012-07-02
### Fixed
- Fixed a bug that caused pagination to stop prematurely.

## 0.8.0 - 2012-06-22
### Added
- You may now query application access tokens with `get_application_access_token`.
- `SignedRequest.parse` now returns a dictionary describing the payload of the signed request
instead of a `SignedRequest` instance.
- `SignedRequest.__init__` now accepts arguments `signed_request` and `application_secret_key`
and no longer facilitates for constructing arbitrary signed requests.
- `SignedRequest#generate` no longer requires the provision of `application_secret_key`.
- `GraphAPI` now supports retries for `get`, `post`, `delete`, `search` and `fql`.
- `GraphAPI#get` is now more intelligent about pagination and should no longer query Facebook for another page
of results if the current page has less elements than `limit`.

### Removed
- `SignedRequest#oauth_token` and `SignedRequest.OAuthToken` have been removed (deprecated since v0.6).

### Fixed
- Fixed a bug that caused some exceptions to be returned rather than raised.

## 0.7.0 - 2012-06-13
### Added
- You may now access the original data of the signed request from `SignedRequest#raw`.
- You may now issue FQL queries with `GraphAPI#fql`.
- `FacebookError` exceptions yielded from `GraphAPI#batch` now include the request that
produced the error.

### Fixed
- Fixed a bug that caused `GraphAPI#batch` to crash upon receiving legacy errors from Facebook.

## 0.6.9 - 2012-05-27
### Added
- Facepy will now raise `OAuthError` for authorization-related errors.
- Facepy will now reuse the connection to Facebook.

## 0.6.8 - 2012-04-25
### Fixed
- Fixed a bug that caused a KeyError upon parsing errors without an error code.

## 0.6.7 - 2012-04-23
### Added
- Facepy now raises `GraphAPI.HTTPError` for requests whose transport failed,
and `GraphAPI.FacebookError` for requests that produced an error in Facebook's API.

### Fixed
- Fixed a bug that caused some errors to be ignored.
- Fixed a bug that caused an error for empty batch responses.

## 0.6.6 - 2012-03-28
### Added
- Facepy now supports batch requests.

## 0.6.5 - 2012-03-09
### Added
- Updated requests.

## 0.6.4 - 2012-01-16
### Fixed
- Fixed a bug that caused `SignedRequest.User#has_authorized_application` to be incorrect for
signed requests with an user id, but no OAuth Token.
- Fixed a bug that caused queries that returned 3xx status codes to yield a blank string

## 0.6.3 - 2012-01-12
### Fixed
- Fixed a bug that caused installation to fail in some circumstances.

## 0.6.2 - 2012-01-10
### Fixed
- Fixed a bug that caused a KeyError upon parsing a signed request that didn't include the user's age.

## 0.6.1 - 2012-01-06
### Fixed
- Fixed a bug that caused a NameError upon providing a list of strings as a Graph API parameter.

## 0.6.0 - 2012-01-05
### Added
- Search results may now be paged.
- `facepy.VERSION` is now `facepy.__version__`

## 0.5.1 - 2011-12-03
### Added
- It is now considerably easier to create signed requests programmatically.

## 0.5.0 - 2011-11-07
### Added
- Facepy now returns the complete API response instead of just its "data" attribute.

## 0.4.2 - 2011-11-03
### Added
- Facepy is now compatible with Python 2.4.

### Fixed
- Fixed a bug that caused a KeyError if the user's locale or country is missing from the signed request.

## 0.4.1 - 2011-11-02
### Fixed
- Fixed a bug that caused a TypeError upon parsing signed requests in unicode.

## 0.4.0 - 2011-11-02
### Added
- Added support for parsing and reverse-engineering signed requests.
- Added support for file-like objects in POST and PUT.

## 0.3.1 - 2011-09-17
### Fixed
- Fixed a bug that prevented the 'page' argument to GraphAPI#get from working
correctly.

## 0.3.0 - 2011-09-16
### Added
- GraphAPI#get now has a new argument 'page', which returns a generator
that iterates over each page of results.

## 0.2.3 - 2011-08-15
### Added
- The GraphAPI class may now be initialized by signed request.

## 0.2.2 - 2011-05-26
### Fixed
- Fix a bug that caused non-JSON data (e.g. pictures) to raise a ValueError.

## 0.2.1 - 2011-05-10
### Fixed
- Fix a bug that caused a TypeError if the 'path' argument is an integer.

## 0.2.0 - 2011-05-10
### Added
- Exceptions have been moved.


text:
package filedesc

import (
	"bytes"
	"fmt"
	"sync"
	"sync/atomic"

	"google.golang.org/protobuf/internal/descfmt"
	"google.golang.org/protobuf/internal/descopts"
	"google.golang.org/protobuf/internal/encoding/defval"
	"google.golang.org/protobuf/internal/pragma"
	"google.golang.org/protobuf/internal/strs"
	pref "google.golang.org/protobuf/reflect/protoreflect"
	"google.golang.org/protobuf/reflect/protoregistry"
)

// The types in this file may have a suffix:
//	• L0: Contains fields common to all descriptors (except File) and
//	must be initialized up front.
//	• L1: Contains fields specific to a descriptor and
//	must be initialized up front.
//	• L2: Contains fields that are lazily initialized when constructing
//	from the raw file descriptor. When constructing as a literal, the L2
//	fields must be initialized up front.
//
// The types are exported so that packages like reflect/protodesc can
// directly construct descriptors.

type (
	File struct {
		fileRaw
		L1 FileL1

		once uint32     // atomically set if L2 is valid
		mu   sync.Mutex // protects L2
		L2   *FileL2
	}
	FileL1 struct {
		Syntax  pref.Syntax
		Path    string
		Package pref.FullName

		Enums      Enums
		Messages   Messages
		Extensions Extensions
		Services   Services
	}
	FileL2 struct {
		Options   func() pref.ProtoMessage
		Imports   FileImports
		Locations SourceLocations
	}
)

func (fd *File) ParentFile() pref.FileDescriptor { return fd }
func (fd *File) Parent() pref.Descriptor         { return nil }
func (fd *File) Index() int                      { return 0 }
func (fd *File) Syntax() pref.Syntax             { return fd.L1.Syntax }
func (fd *File) Name() pref.Name                 { return fd.L1.Package.Name() }
func (fd *File) FullName() pref.FullName         { return fd.L1.Package }
func (fd *File) IsPlaceholder() bool             { return false }
func (fd *File) Options() pref.ProtoMessage {
	if f := fd.lazyInit().Options; f != nil {
		return f()
	}
	return descopts.File
}
func (fd *File) Path() string                          { return fd.L1.Path }
func (fd *File) Package() pref.FullName                { return fd.L1.Package }
func (fd *File) Imports() pref.FileImports             { return &fd.lazyInit().Imports }
func (fd *File) Enums() pref.EnumDescriptors           { return &fd.L1.Enums }
func (fd *File) Messages() pref.MessageDescriptors     { return &fd.L1.Messages }
func (fd *File) Extensions() pref.ExtensionDescriptors { return &fd.L1.Extensions }
func (fd *File) Services() pref.ServiceDescriptors     { return &fd.L1.Services }
func (fd *File) SourceLocations() pref.SourceLocations { return &fd.L2.Locations }
func (fd *File) Format(s fmt.State, r rune)            { descfmt.FormatDesc(s, r, fd) }
func (fd *File) ProtoType(pref.FileDescriptor)         {}
func (fd *File) ProtoInternal(pragma.DoNotImplement)   {}

func (fd *File) lazyInit() *FileL2 {
	if atomic.LoadUint32(&fd.once) == 0 {
		fd.lazyInitOnce()
	}
	return fd.L2
}

func (fd *File) lazyInitOnce() {
	fd.mu.Lock()
	if fd.L2 == nil {
		fd.lazyRawInit() // recursively initializes all L2 structures
	}
	atomic.StoreUint32(&fd.once, 1)
	fd.mu.Unlock()
}

// ProtoLegacyRawDesc is a pseudo-internal API for allowing the v1 code
// to be able to retrieve the raw descriptor.
//
// WARNING: This method is exempt from the compatibility promise and may be
// removed in the future without warning.
func (fd *File) ProtoLegacyRawDesc() []byte {
	return fd.builder.RawDescriptor
}

// GoPackagePath is a pseudo-internal API for determining the Go package path
// that this file descriptor is declared in.
//
// WARNING: This method is exempt from the compatibility promise and may be
// removed in the future without warning.
func (fd *File) GoPackagePath() string {
	return fd.builder.GoPackagePath
}

type (
	Enum struct {
		Base
		L1 EnumL1
		L2 *EnumL2 // protected by fileDesc.once
	}
	EnumL1 struct {
		eagerValues bool // controls whether EnumL2.Values is already populated
	}
	EnumL2 struct {
		Options        func() pref.ProtoMessage
		Values         EnumValues
		ReservedNames  Names
		ReservedRanges EnumRanges
	}

	EnumValue struct {
		Base
		L1 EnumValueL1
	}
	EnumValueL1 struct {
		Options func() pref.ProtoMessage
		Number  pref.EnumNumber
	}
)

func (ed *Enum) Options() pref.ProtoMessage {
	if f := ed.lazyInit().Options; f != nil {
		return f()
	}
	return descopts.Enum
}
func (ed *Enum) Values() pref.EnumValueDescriptors {
	if ed.L1.eagerValues {
		return &ed.L2.Values
	}
	return &ed.lazyInit().Values
}
func (ed *Enum) ReservedNames() pref.Names       { return &ed.lazyInit().ReservedNames }
func (ed *Enum) ReservedRanges() pref.EnumRanges { return &ed.lazyInit().ReservedRanges }
func (ed *Enum) Format(s fmt.State, r rune)      { descfmt.FormatDesc(s, r, ed) }
func (ed *Enum) ProtoType(pref.EnumDescriptor)   {}
func (ed *Enum) lazyInit() *EnumL2 {
	ed.L0.ParentFile.lazyInit() // implicitly initializes L2
	return ed.L2
}

func (ed *EnumValue) Options() pref.ProtoMessage {
	if f := ed.L1.Options; f != nil {
		return f()
	}
	return descopts.EnumValue
}
func (ed *EnumValue) Number() pref.EnumNumber            { return ed.L1.Number }
func (ed *EnumValue) Format(s fmt.State, r rune)         { descfmt.FormatDesc(s, r, ed) }
func (ed *EnumValue) ProtoType(pref.EnumValueDescriptor) {}

type (
	Message struct {
		Base
		L1 MessageL1
		L2 *MessageL2 // protected by fileDesc.once
	}
	MessageL1 struct {
		Enums        Enums
		Messages     Messages
		Extensions   Extensions
		IsMapEntry   bool // promoted from google.protobuf.MessageOptions
		IsMessageSet bool // promoted from google.protobuf.MessageOptions
	}
	MessageL2 struct {
		Options               func() pref.ProtoMessage
		Fields                Fields
		Oneofs                Oneofs
		ReservedNames         Names
		ReservedRanges        FieldRanges
		RequiredNumbers       FieldNumbers // must be consistent with Fields.Cardinality
		ExtensionRanges       FieldRanges
		ExtensionRangeOptions []func() pref.ProtoMessage // must be same length as ExtensionRanges
	}

	Field struct {
		Base
		L1 FieldL1
	}
	FieldL1 struct {
		Options         func() pref.ProtoMessage
		Number          pref.FieldNumber
		Cardinality     pref.Cardinality // must be consistent with Message.RequiredNumbers
		Kind            pref.Kind
		JSONName        jsonName
		IsWeak          bool // promoted from google.protobuf.FieldOptions
		HasPacked       bool // promoted from google.protobuf.FieldOptions
		IsPacked        bool // promoted from google.protobuf.FieldOptions
		HasEnforceUTF8  bool // promoted from google.protobuf.FieldOptions
		EnforceUTF8     bool // promoted from google.protobuf.FieldOptions
		Default         defaultValue
		ContainingOneof pref.OneofDescriptor // must be consistent with Message.Oneofs.Fields
		Enum            pref.EnumDescriptor
		Message         pref.MessageDescriptor
	}

	Oneof struct {
		Base
		L1 OneofL1
	}
	OneofL1 struct {
		Options func() pref.ProtoMessage
		Fields  OneofFields // must be consistent with Message.Fields.ContainingOneof
	}
)

func (md *Message) Options() pref.ProtoMessage {
	if f := md.lazyInit().Options; f != nil {
		return f()
	}
	return descopts.Message
}
func (md *Message) IsMapEntry() bool                   { return md.L1.IsMapEntry }
func (md *Message) Fields() pref.FieldDescriptors      { return &md.lazyInit().Fields }
func (md *Message) Oneofs() pref.OneofDescriptors      { return &md.lazyInit().Oneofs }
func (md *Message) ReservedNames() pref.Names          { return &md.lazyInit().ReservedNames }
func (md *Message) ReservedRanges() pref.FieldRanges   { return &md.lazyInit().ReservedRanges }
func (md *Message) RequiredNumbers() pref.FieldNumbers { return &md.lazyInit().RequiredNumbers }
func (md *Message) ExtensionRanges() pref.FieldRanges  { return &md.lazyInit().ExtensionRanges }
func (md *Message) ExtensionRangeOptions(i int) pref.ProtoMessage {
	if f := md.lazyInit().ExtensionRangeOptions[i]; f != nil {
		return f()
	}
	return descopts.ExtensionRange
}
func (md *Message) Enums() pref.EnumDescriptors           { return &md.L1.Enums }
func (md *Message) Messages() pref.MessageDescriptors     { return &md.L1.Messages }
func (md *Message) Extensions() pref.ExtensionDescriptors { return &md.L1.Extensions }
func (md *Message) ProtoType(pref.MessageDescriptor)      {}
func (md *Message) Format(s fmt.State, r rune)            { descfmt.FormatDesc(s, r, md) }
func (md *Message) lazyInit() *MessageL2 {
	md.L0.ParentFile.lazyInit() // implicitly initializes L2
	return md.L2
}

// IsMessageSet is a pseudo-internal API for checking whether a message
// should serialize in the proto1 message format.
//
// WARNING: This method is exempt from the compatibility promise and may be
// removed in the future without warning.
func (md *Message) IsMessageSet() bool {
	return md.L1.IsMessageSet
}

func (fd *Field) Options() pref.ProtoMessage {
	if f := fd.L1.Options; f != nil {
		return f()
	}
	return descopts.Field
}
func (fd *Field) Number() pref.FieldNumber      { return fd.L1.Number }
func (fd *Field) Cardinality() pref.Cardinality { return fd.L1.Cardinality }
func (fd *Field) Kind() pref.Kind               { return fd.L1.Kind }
func (fd *Field) HasJSONName() bool             { return fd.L1.JSONName.has }
func (fd *Field) JSONName() string              { return fd.L1.JSONName.get(fd) }
func (fd *Field) IsPacked() bool {
	if !fd.L1.HasPacked && fd.L0.ParentFile.L1.Syntax != pref.Proto2 && fd.L1.Cardinality == pref.Repeated {
		switch fd.L1.Kind {
		case pref.StringKind, pref.BytesKind, pref.MessageKind, pref.GroupKind:
		default:
			return true
		}
	}
	return fd.L1.IsPacked
}
func (fd *Field) IsExtension() bool { return false }
func (fd *Field) IsWeak() bool      { return fd.L1.IsWeak }
func (fd *Field) IsList() bool      { return fd.Cardinality() == pref.Repeated && !fd.IsMap() }
func (fd *Field) IsMap() bool       { return fd.Message() != nil && fd.Message().IsMapEntry() }
func (fd *Field) MapKey() pref.FieldDescriptor {
	if !fd.IsMap() {
		return nil
	}
	return fd.Message().Fields().ByNumber(1)
}
func (fd *Field) MapValue() pref.FieldDescriptor {
	if !fd.IsMap() {
		return nil
	}
	return fd.Message().Fields().ByNumber(2)
}
func (fd *Field) HasDefault() bool                           { return fd.L1.Default.has }
func (fd *Field) Default() pref.Value                        { return fd.L1.Default.get(fd) }
func (fd *Field) DefaultEnumValue() pref.EnumValueDescriptor { return fd.L1.Default.enum }
func (fd *Field) ContainingOneof() pref.OneofDescriptor      { return fd.L1.ContainingOneof }
func (fd *Field) ContainingMessage() pref.MessageDescriptor {
	return fd.L0.Parent.(pref.MessageDescriptor)
}
func (fd *Field) Enum() pref.EnumDescriptor {
	return fd.L1.Enum
}
func (fd *Field) Message() pref.MessageDescriptor {
	if fd.L1.IsWeak {
		if d, _ := protoregistry.GlobalFiles.FindDescriptorByName(fd.L1.Message.FullName()); d != nil {
			return d.(pref.MessageDescriptor)
		}
	}
	return fd.L1.Message
}
func (fd *Field) Format(s fmt.State, r rune)     { descfmt.FormatDesc(s, r, fd) }
func (fd *Field) ProtoType(pref.FieldDescriptor) {}

// EnforceUTF8 is a pseudo-internal API to determine whether to enforce UTF-8
// validation for the string field. This exists for Google-internal use only
// since proto3 did not enforce UTF-8 validity prior to the open-source release.
// If this method does not exist, the default is to enforce valid UTF-8.
//
// WARNING: This method is exempt from the compatibility promise and may be
// removed in the future without warning.
func (fd *Field) EnforceUTF8() bool {
	if fd.L1.HasEnforceUTF8 {
		return fd.L1.EnforceUTF8
	}
	return fd.L0.ParentFile.L1.Syntax == pref.Proto3
}

func (od *Oneof) Options() pref.ProtoMessage {
	if f := od.L1.Options; f != nil {
		return f()
	}
	return descopts.Oneof
}
func (od *Oneof) Fields() pref.FieldDescriptors  { return &od.L1.Fields }
func (od *Oneof) Format(s fmt.State, r rune)     { descfmt.FormatDesc(s, r, od) }
func (od *Oneof) ProtoType(pref.OneofDescriptor) {}

type (
	Extension struct {
		Base
		L1 ExtensionL1
		L2 *ExtensionL2 // protected by fileDesc.once
	}
	ExtensionL1 struct {
		Number      pref.FieldNumber
		Extendee    pref.MessageDescriptor
		Cardinality pref.Cardinality
		Kind        pref.Kind
	}
	ExtensionL2 struct {
		Options  func() pref.ProtoMessage
		JSONName jsonName
		IsPacked bool // promoted from google.protobuf.FieldOptions
		Default  defaultValue
		Enum     pref.EnumDescriptor
		Message  pref.MessageDescriptor
	}
)

func (xd *Extension) Options() pref.ProtoMessage {
	if f := xd.lazyInit().Options; f != nil {
		return f()
	}
	return descopts.Field
}
func (xd *Extension) Number() pref.FieldNumber                   { return xd.L1.Number }
func (xd *Extension) Cardinality() pref.Cardinality              { return xd.L1.Cardinality }
func (xd *Extension) Kind() pref.Kind                            { return xd.L1.Kind }
func (xd *Extension) HasJSONName() bool                          { return xd.lazyInit().JSONName.has }
func (xd *Extension) JSONName() string                           { return xd.lazyInit().JSONName.get(xd) }
func (xd *Extension) IsPacked() bool                             { return xd.lazyInit().IsPacked }
func (xd *Extension) IsExtension() bool                          { return true }
func (xd *Extension) IsWeak() bool                               { return false }
func (xd *Extension) IsList() bool                               { return xd.Cardinality() == pref.Repeated }
func (xd *Extension) IsMap() bool                                { return false }
func (xd *Extension) MapKey() pref.FieldDescriptor               { return nil }
func (xd *Extension) MapValue() pref.FieldDescriptor             { return nil }
func (xd *Extension) HasDefault() bool                           { return xd.lazyInit().Default.has }
func (xd *Extension) Default() pref.Value                        { return xd.lazyInit().Default.get(xd) }
func (xd *Extension) DefaultEnumValue() pref.EnumValueDescriptor { return xd.lazyInit().Default.enum }
func (xd *Extension) ContainingOneof() pref.OneofDescriptor      { return nil }
func (xd *Extension) ContainingMessage() pref.MessageDescriptor  { return xd.L1.Extendee }
func (xd *Extension) Enum() pref.EnumDescriptor                  { return xd.lazyInit().Enum }
func (xd *Extension) Message() pref.MessageDescriptor            { return xd.lazyInit().Message }
func (xd *Extension) Format(s fmt.State, r rune)                 { descfmt.FormatDesc(s, r, xd) }
func (xd *Extension) ProtoType(pref.FieldDescriptor)             {}
func (xd *Extension) ProtoInternal(pragma.DoNotImplement)        {}
func (xd *Extension) lazyInit() *ExtensionL2 {
	xd.L0.ParentFile.lazyInit() // implicitly initializes L2
	return xd.L2
}

type (
	Service struct {
		Base
		L1 ServiceL1
		L2 *ServiceL2 // protected by fileDesc.once
	}
	ServiceL1 struct{}
	ServiceL2 struct {
		Options func() pref.ProtoMessage
		Methods Methods
	}

	Method struct {
		Base
		L1 MethodL1
	}
	MethodL1 struct {
		Options           func() pref.ProtoMessage
		Input             pref.MessageDescriptor
		Output            pref.MessageDescriptor
		IsStreamingClient bool
		IsStreamingServer bool
	}
)

func (sd *Service) Options() pref.ProtoMessage {
	if f := sd.lazyInit().Options; f != nil {
		return f()
	}
	return descopts.Service
}
func (sd *Service) Methods() pref.MethodDescriptors     { return &sd.lazyInit().Methods }
func (sd *Service) Format(s fmt.State, r rune)          { descfmt.FormatDesc(s, r, sd) }
func (sd *Service) ProtoType(pref.ServiceDescriptor)    {}
func (sd *Service) ProtoInternal(pragma.DoNotImplement) {}
func (sd *Service) lazyInit() *ServiceL2 {
	sd.L0.ParentFile.lazyInit() // implicitly initializes L2
	return sd.L2
}

func (md *Method) Options() pref.ProtoMessage {
	if f := md.L1.Options; f != nil {
		return f()
	}
	return descopts.Method
}
func (md *Method) Input() pref.MessageDescriptor       { return md.L1.Input }
func (md *Method) Output() pref.MessageDescriptor      { return md.L1.Output }
func (md *Method) IsStreamingClient() bool             { return md.L1.IsStreamingClient }
func (md *Method) IsStreamingServer() bool             { return md.L1.IsStreamingServer }
func (md *Method) Format(s fmt.State, r rune)          { descfmt.FormatDesc(s, r, md) }
func (md *Method) ProtoType(pref.MethodDescriptor)     {}
func (md *Method) ProtoInternal(pragma.DoNotImplement) {}

// Surrogate files are can be used to create standalone descriptors
// where the syntax is only information derived from the parent file.
var (
	SurrogateProto2 = &File{L1: FileL1{Syntax: pref.Proto2}, L2: &FileL2{}}
	SurrogateProto3 = &File{L1: FileL1{Syntax: pref.Proto3}, L2: &FileL2{}}
)

type (
	Base struct {
		L0 BaseL0
	}
	BaseL0 struct {
		FullName   pref.FullName // must be populated
		ParentFile *File         // must be populated
		Parent     pref.Descriptor
		Index      int
	}
)

func (d *Base) Name() pref.Name         { return d.L0.FullName.Name() }
func (d *Base) FullName() pref.FullName { return d.L0.FullName }
func (d *Base) ParentFile() pref.FileDescriptor {
	if d.L0.ParentFile == SurrogateProto2 || d.L0.ParentFile == SurrogateProto3 {
		return nil // surrogate files are not real parents
	}
	return d.L0.ParentFile
}
func (d *Base) Parent() pref.Descriptor             { return d.L0.Parent }
func (d *Base) Index() int                          { return d.L0.Index }
func (d *Base) Syntax() pref.Syntax                 { return d.L0.ParentFile.Syntax() }
func (d *Base) IsPlaceholder() bool                 { return false }
func (d *Base) ProtoInternal(pragma.DoNotImplement) {}

type jsonName struct {
	has  bool
	once sync.Once
	name string
}

// Init initializes the name. It is exported for use by other internal packages.
func (js *jsonName) Init(s string) {
	js.has = true
	js.name = s
}

func (js *jsonName) get(fd pref.FieldDescriptor) string {
	if !js.has {
		js.once.Do(func() {
			js.name = strs.JSONCamelCase(string(fd.Name()))
		})
	}
	return js.name
}

func DefaultValue(v pref.Value, ev pref.EnumValueDescriptor) defaultValue {
	dv := defaultValue{has: v.IsValid(), val: v, enum: ev}
	if b, ok := v.Interface().([]byte); ok {
		// Store a copy of the default bytes, so that we can detect
		// accidental mutations of the original value.
		dv.bytes = append([]byte(nil), b...)
	}
	return dv
}

func unmarshalDefault(b []byte, k pref.Kind, pf *File, ed pref.EnumDescriptor) defaultValue {
	var evs pref.EnumValueDescriptors
	if k == pref.EnumKind {
		// If the enum is declared within the same file, be careful not to
		// blindly call the Values method, lest we bind ourselves in a deadlock.
		if e, ok := ed.(*Enum); ok && e.L0.ParentFile == pf {
			evs = &e.L2.Values
		} else {
			evs = ed.Values()
		}

		// If we are unable to resolve the enum dependency, use a placeholder
		// enum value since we will not be able to parse the default value.
		if ed.IsPlaceholder() && pref.Name(b).IsValid() {
			v := pref.ValueOfEnum(0)
			ev := PlaceholderEnumValue(ed.FullName().Parent().Append(pref.Name(b)))
			return DefaultValue(v, ev)
		}
	}

	v, ev, err := defval.Unmarshal(string(b), k, evs, defval.Descriptor)
	if err != nil {
		panic(err)
	}
	return DefaultValue(v, ev)
}

type defaultValue struct {
	has   bool
	val   pref.Value
	enum  pref.EnumValueDescriptor
	bytes []byte
}

func (dv *defaultValue) get(fd pref.FieldDescriptor) pref.Value {
	// Return the zero value as the default if unpopulated.
	if !dv.has {
		if fd.Cardinality() == pref.Repeated {
			return pref.Value{}
		}
		switch fd.Kind() {
		case pref.BoolKind:
			return pref.ValueOfBool(false)
		case pref.Int32Kind, pref.Sint32Kind, pref.Sfixed32Kind:
			return pref.ValueOfInt32(0)
		case pref.Int64Kind, pref.Sint64Kind, pref.Sfixed64Kind:
			return pref.ValueOfInt64(0)
		case pref.Uint32Kind, pref.Fixed32Kind:
			return pref.ValueOfUint32(0)
		case pref.Uint64Kind, pref.Fixed64Kind:
			return pref.ValueOfUint64(0)
		case pref.FloatKind:
			return pref.ValueOfFloat32(0)
		case pref.DoubleKind:
			return pref.ValueOfFloat64(0)
		case pref.StringKind:
			return pref.ValueOfString("")
		case pref.BytesKind:
			return pref.ValueOfBytes(nil)
		case pref.EnumKind:
			if evs := fd.Enum().Values(); evs.Len() > 0 {
				return pref.ValueOfEnum(evs.Get(0).Number())
			}
			return pref.ValueOfEnum(0)
		}
	}

	if len(dv.bytes) > 0 && !bytes.Equal(dv.bytes, dv.val.Bytes()) {
		// TODO: Avoid panic if we're running with the race detector
		// and instead spawn a goroutine that periodically resets
		// this value back to the original to induce a race.
		panic("detected mutation on the default bytes")
	}
	return dv.val
}


text:
import copy
import operator
import os
import unittest
import subprocess
import sys
import re

from collections import deque
from test import test_support

from java.lang import (ClassCastException, ExceptionInInitializerError, String, Runnable, System,
        Runtime, Math, Byte)
from java.math import BigDecimal, BigInteger
from java.io import (ByteArrayInputStream, ByteArrayOutputStream, File, FileInputStream,
                     FileNotFoundException, FileOutputStream, FileWriter, ObjectInputStream,
                     ObjectOutputStream, OutputStreamWriter, UnsupportedEncodingException)
from java.util import ArrayList, Date, HashMap, Hashtable, StringTokenizer, Vector

from java.awt import Dimension, Color, Component, Container
from java.awt.event import ComponentEvent
from javax.swing.tree import TreePath

from org.python.core.util import FileUtil
from org.python.tests import (BeanImplementation, Child, Child2,
                              CustomizableMapHolder, Listenable, ToUnicode)
from org.python.tests.mro import (ConfusedOnGetitemAdd, FirstPredefinedGetitem, GetitemAdder)
from javatests import Issue1833
from javatests.ProxyTests import NullToString, Person

class InstantiationTest(unittest.TestCase):
    def test_cant_instantiate_abstract(self):
        self.assertRaises(TypeError, Component)

    def test_no_public_constructors(self):
        self.assertRaises(TypeError, Math)

    def test_invalid_self_to_java_constructor(self):
        self.assertRaises(TypeError, Color.__init__, 10, 10, 10)

    def test_str_doesnt_coerce_to_int(self):
        self.assertRaises(TypeError, Date, '99-01-01', 1, 1)

    def test_class_in_failed_constructor(self):
        try:
            Dimension(123, 456, 789)
        except TypeError, exc:
            self.failUnless("java.awt.Dimension" in exc.message)

class BeanTest(unittest.TestCase):
    def test_shared_names(self):
        self.failUnless(callable(Vector.size),
                'size method should be preferred to writeonly field')

    def test_multiple_listeners(self):
        '''Check that multiple BEP can be assigned to a single cast listener'''
        m = Listenable()
        called = []
        def f(evt, called=called):
            called.append(0)

        m.componentShown = f
        m.componentHidden = f

        m.fireComponentShown(ComponentEvent(Container(), 0))
        self.assertEquals(1, len(called))
        m.fireComponentHidden(ComponentEvent(Container(), 0))
        self.assertEquals(2, len(called))

    def test_bean_interface(self):
        b = BeanImplementation()
        self.assertEquals("name", b.getName())
        self.assertEquals("name", b.name)
        # Tests for #610576
        class SubBean(BeanImplementation):
            def __init__(bself):
                self.assertEquals("name", bself.getName())
        SubBean()

    def test_inheriting_half_bean(self):
        c = Child()
        self.assertEquals("blah", c.value)
        c.value = "bleh"
        self.assertEquals("bleh", c.value)
        self.assertEquals(7, c.id)
        c.id = 16
        self.assertEquals(16, c.id)

    def test_inheriting_half_bean_issue1333(self):
        # http://bugs.jython.org/issue1333
        c = Child2()
        self.assertEquals("blah", c.value)
        c.value = "bleh"
        self.assertEquals("Child2 bleh", c.value)

    def test_awt_hack(self):
        # We ignore several deprecated methods in java.awt.* in favor of bean properties that were
        # addded in Java 1.1.  This tests that one of those bean properties is visible.
        c = Container()
        c.size = 400, 300
        self.assertEquals(Dimension(400, 300), c.size)

class SysIntegrationTest(unittest.TestCase):
    def setUp(self):
        self.orig_stdout = sys.stdout

    def tearDown(self):
        sys.stdout = self.orig_stdout

    def test_stdout_outputstream(self):
        out = FileOutputStream(test_support.TESTFN)
        sys.stdout = out
        print 'hello',
        out.close()
        f = open(test_support.TESTFN)
        self.assertEquals('hello', f.read())
        f.close()

class IOTest(unittest.TestCase):
    def test_io_errors(self):
        "Check that IOException isn't mangled into an IOError"
        self.assertRaises(UnsupportedEncodingException, OutputStreamWriter, System.out, "garbage")
        self.assertRaises(IOError, OutputStreamWriter, System.out, "garbage")

    def test_fileio_error(self):
        self.assertRaises(FileNotFoundException, FileInputStream, "garbage")

    def test_unsupported_tell(self):
        fp = FileUtil.wrap(System.out)
        self.assertRaises(IOError, fp.tell)

class JavaReservedNamesTest(unittest.TestCase):
    "Access to reserved words"

    def test_system_in(self):
        s = System.in
        self.assert_("java.io.BufferedInputStream" in str(s))

    def test_runtime_exec(self):
        e = Runtime.getRuntime().exec
        self.assert_(re.search("method .*exec", str(e)) is not None)

    def test_byte_class(self):
        b = Byte(10)
        self.assert_("java.lang.Byte" in str(b.class))

class Keywords(object):
    pass

Keywords.in = lambda self: "in"
Keywords.exec = lambda self: "exec"
Keywords.class = lambda self: "class"
Keywords.print = lambda self: "print"
Keywords.and = lambda self: "and"
Keywords.as = lambda self: "as"
Keywords.assert = lambda self: "assert"
Keywords.break = lambda self: "break"
Keywords.continue = lambda self: "continue"
Keywords.def = lambda self: "def"
Keywords.del = lambda self: "del"
Keywords.elif = lambda self: "elif"
Keywords.else = lambda self: "else"
Keywords.except = lambda self: "except"
Keywords.finally = lambda self: "finally"
Keywords.from = lambda self: "from"
Keywords.for = lambda self: "for"
Keywords.global = lambda self: "global"
Keywords.if = lambda self: "if"
Keywords.import = lambda self: "import"
Keywords.is = lambda self: "is"
Keywords.lambda = lambda self: "lambda"
Keywords.pass = lambda self: "pass"
Keywords.print = lambda self: "print"
Keywords.raise = lambda self: "raise"
Keywords.return = lambda self: "return"
Keywords.try = lambda self: "try"
Keywords.while = lambda self: "while"
Keywords.with = lambda self: "with"
Keywords.yield = lambda self: "yield"

class PyReservedNamesTest(unittest.TestCase):
    "Access to reserved words"

    def setUp(self):
        self.kws = Keywords()

    def test_in(self):
        self.assertEquals(self.kws.in(), "in")

    def test_exec(self):
        self.assertEquals(self.kws.exec(), "exec")

    def test_class(self):
        self.assertEquals(self.kws.class(), "class")

    def test_print(self):
        self.assertEquals(self.kws.print(), "print")

    def test_and(self):
        self.assertEquals(self.kws.and(), "and")

    def test_as(self):
        self.assertEquals(self.kws.as(), "as")

    def test_assert(self):
        self.assertEquals(self.kws.assert(), "assert")

    def test_break(self):
        self.assertEquals(self.kws.break(), "break")

    def test_continue(self):
        self.assertEquals(self.kws.continue(), "continue")

    def test_def(self):
        self.assertEquals(self.kws.def(), "def")

    def test_del(self):
        self.assertEquals(self.kws.del(), "del")

    def test_elif(self):
        self.assertEquals(self.kws.elif(), "elif")

    def test_else(self):
        self.assertEquals(self.kws.else(), "else")

    def test_except(self):
        self.assertEquals(self.kws.except(), "except")

    def test_finally(self):
        self.assertEquals(self.kws.finally(), "finally")

    def test_from(self):
        self.assertEquals(self.kws.from(), "from")

    def test_for(self):
        self.assertEquals(self.kws.for(), "for")

    def test_global(self):
        self.assertEquals(self.kws.global(), "global")

    def test_if(self):
        self.assertEquals(self.kws.if(), "if")

    def test_import(self):
        self.assertEquals(self.kws.import(), "import")

    def test_is(self):
        self.assertEquals(self.kws.is(), "is")

    def test_lambda(self):
        self.assertEquals(self.kws.lambda(), "lambda")

    def test_pass(self):
        self.assertEquals(self.kws.pass(), "pass")

    def test_print(self):
        self.assertEquals(self.kws.print(), "print")

    def test_raise(self):
        self.assertEquals(self.kws.raise(), "raise")

    def test_return(self):
        self.assertEquals(self.kws.return(), "return")

    def test_try(self):
        self.assertEquals(self.kws.try(), "try")

    def test_while(self):
        self.assertEquals(self.kws.while(), "while")

    def test_with(self):
        self.assertEquals(self.kws.with(), "with")

    def test_yield(self):
        self.assertEquals(self.kws.yield(), "yield")

class ImportTest(unittest.TestCase):
    def test_bad_input_exception(self):
        self.assertRaises(ValueError, __import__, '')

    def test_broken_static_initializer(self):
        self.assertRaises(ExceptionInInitializerError, __import__, "org.python.tests.BadStaticInitializer")

class ColorTest(unittest.TestCase):
    def test_assigning_over_method(self):
        self.assertRaises(TypeError, setattr, Color.RED, "getRGB", 4)

    def test_static_fields(self):
        self.assertEquals(Color(255, 0, 0), Color.RED)
        # The bean accessor for getRed should be active on instances, but the static field red
        # should be visible on the class
        self.assertEquals(255, Color.red.red)
        self.assertEquals(Color(0, 0, 255), Color.blue)

    def test_is_operator(self):
        red = Color.red
        self.assert_(red is red)
        self.assert_(red is Color.red)

class TreePathTest(unittest.TestCase):
    def test_overloading(self):
        treePath = TreePath([1,2,3])
        self.assertEquals(len(treePath.path), 3, "Object[] not passed correctly")
        self.assertEquals(TreePath(treePath.path).path, treePath.path, "Object[] not passed and returned correctly")

class BigNumberTest(unittest.TestCase):
    def test_coerced_bigdecimal(self):
        from javatests import BigDecimalTest
        x = BigDecimal("123.4321")
        y = BigDecimalTest().asBigDecimal()

        self.assertEqual(type(x), type(y), "BigDecimal coerced")
        self.assertEqual(x, y, "coerced BigDecimal not equal to directly created version")

    def test_biginteger_in_long(self):
        '''Checks for #608628, that long can take a BigInteger in its constructor'''
        ns = '10000000000'
        self.assertEquals(ns, str(long(BigInteger(ns))))

class JavaStringTest(unittest.TestCase):
    def test_string_not_iterable(self):
        x = String('test')
        self.assertRaises(TypeError, list, x)

class JavaDelegationTest(unittest.TestCase):
    def test_list_delegation(self):
        for c in ArrayList, Vector:
            a = c()
            self.assertRaises(IndexError, a.__getitem__, 0)
            a.add("blah")
            self.assertTrue("blah" in a)
            self.assertEquals(1, len(a))
            n = 0
            for i in a:
                n += 1
                self.assertEquals("blah", i)
            self.assertEquals(1, n)
            self.assertEquals("blah", a[0])
            a[0] = "bleh"
            del a[0]
            self.assertEquals(0, len(a))

    def test_map_delegation(self):
        m = HashMap()
        m["a"] = "b"
        self.assertTrue("a" in m)
        self.assertEquals("b", m["a"])
        n = 0
        for k in m:
            n += 1
            self.assertEquals("a", k)
        self.assertEquals(1, n)
        del m["a"]
        self.assertEquals(0, len(m))

    def test_enumerable_delegation(self):
        tokenizer = StringTokenizer('foo bar')
        self.assertEquals(list(iter(tokenizer)), ['foo', 'bar'])

    def test_vector_delegation(self):
        class X(Runnable):
            pass
        v = Vector()
        v.addElement(1)
        v.indexOf(X())# Compares the Java object in the vector to a Python subclass
        for i in v:
            pass

    def test_comparable_delegation(self):
        first_file = File("a")
        first_date = Date(100)
        for a, b, c in [(first_file, File("b"), File("c")), (first_date, Date(1000), Date())]:
            self.assertTrue(a.compareTo(b) < 0)
            self.assertEquals(-1, cmp(a, b))
            self.assertTrue(a.compareTo(c) < 0)
            self.assertEquals(-1, cmp(a, c))
            self.assertEquals(0, a.compareTo(a))
            self.assertEquals(0, cmp(a, a))
            self.assertTrue(b.compareTo(a) > 0)
            self.assertEquals(1, cmp(b, a))
            self.assertTrue(c.compareTo(b) > 0)
            self.assertEquals(1, cmp(c, b))
            self.assertTrue(a < b)
            self.assertTrue(a <= a)
            self.assertTrue(b > a)
            self.assertTrue(c >= a)
            self.assertTrue(a != b)
            l = [b, c, a]
            self.assertEquals(a, min(l))
            self.assertEquals(c, max(l))
            l.sort()
            self.assertEquals([a, b, c], l)
        # Check that we fall back to the default comparison(class name) instead of using compareTo
        # on non-Comparable types
        self.assertRaises(ClassCastException, first_file.compareTo, first_date)
        self.assertEquals(-1, cmp(first_file, first_date))
        self.assertTrue(first_file < first_date)
        self.assertTrue(first_file <= first_date)
        self.assertTrue(first_date > first_file)
        self.assertTrue(first_date >= first_file)

    def test_equals(self):
        # Test for bug #1338
        a = range(5)

        x = ArrayList()
        x.addAll(a)

        y = Vector()
        y.addAll(a)

        z = ArrayList()
        z.addAll(range(1, 6))

        self.assertTrue(x.equals(y))
        self.assertEquals(x, y)
        self.assertTrue(not (x != y))

        self.assertTrue(not x.equals(z))
        self.assertNotEquals(x, z)
        self.assertTrue(not (x == z))

class SecurityManagerTest(unittest.TestCase):
    def test_nonexistent_import_with_security(self):
        if os._name == 'nt':
            # http://bugs.jython.org/issue1371
            return
        script = test_support.findfile("import_nonexistent.py")
        home = os.path.realpath(sys.prefix)
        if not os.path.commonprefix((home, os.path.realpath(script))) == home:
            # script must lie within python.home for this test to work
            return
        policy = test_support.findfile("python_home.policy")
        self.assertEquals(subprocess.call([sys.executable,  "-J-Dpython.cachedir.skip=true",
            "-J-Djava.security.manager", "-J-Djava.security.policy=%s" % policy, script]),
            0)

class JavaWrapperCustomizationTest(unittest.TestCase):
    def tearDown(self):
        CustomizableMapHolder.clearAdditions()

    def test_adding_item_access(self):
        m = CustomizableMapHolder()
        self.assertRaises(TypeError, operator.getitem, m, "initial")
        CustomizableMapHolder.addGetitem()
        self.assertEquals(m.held["initial"], m["initial"])
        # dict would throw a KeyError here, but Map returns null for a missing key
        self.assertEquals(None, m["nonexistent"])
        self.assertRaises(TypeError, operator.setitem, m, "initial")
        CustomizableMapHolder.addSetitem()
        m["initial"] = 12
        self.assertEquals(12, m["initial"])

    def test_adding_attributes(self):
        m = CustomizableMapHolder()
        self.assertRaises(AttributeError, getattr, m, "initial")
        CustomizableMapHolder.addGetattribute()
        self.assertEquals(7, m.held["initial"], "Existing fields should still be accessible")
        self.assertEquals(7, m.initial)
        self.assertEquals(None, m.nonexistent, "Nonexistent fields should be passed on to the Map")

    def test_adding_on_interface(self):
        GetitemAdder.addPredefined()
        class UsesInterfaceMethod(FirstPredefinedGetitem):
            pass
        self.assertEquals("key", UsesInterfaceMethod()["key"])

    def test_add_on_mro_conflict(self):
        """Adding same-named methods to Java classes with MRO conflicts produces TypeError"""
        GetitemAdder.addPredefined()
        self.assertRaises(TypeError, __import__, "org.python.tests.mro.ConfusedOnImport")
        self.assertRaises(TypeError, GetitemAdder.addPostdefined)

    def test_null_tostring(self):
        # http://bugs.jython.org/issue1819
        nts = NullToString()
        self.assertEqual(repr(nts), '')
        self.assertEqual(str(nts), '')
        self.assertEqual(unicode(nts), '')

def roundtrip_serialization(obj):
    """Returns a deep copy of an object, via serializing it

    see http://weblogs.java.net/blog/emcmanus/archive/2007/04/cloning_java_ob.html
    """
    output = ByteArrayOutputStream()
    serializer = CloneOutput(output)
    serializer.writeObject(obj)
    serializer.close()
    input = ByteArrayInputStream(output.toByteArray())
    unserializer = CloneInput(input, serializer) # to get the list of classes seen, in order
    return unserializer.readObject()

class CloneOutput(ObjectOutputStream):
    def __init__(self, output):
        ObjectOutputStream.__init__(self, output)
        self.classQueue = deque()

    def annotateClass(self, c):
        self.classQueue.append(c)

    def annotateProxyClass(self, c):
        self.classQueue.append(c)

class CloneInput(ObjectInputStream):

    def __init__(self, input, output):
        ObjectInputStream.__init__(self, input)
        self.output = output

    def resolveClass(self, obj_stream_class):
        return self.output.classQueue.popleft()

    def resolveProxyClass(self, interfaceNames):
        return self.output.classQueue.popleft()

class SerializationTest(unittest.TestCase):

    def test_java_serialization(self):
        date_list = [Date(), Date()]
        self.assertEqual(date_list, roundtrip_serialization(date_list))

    def test_java_serialization_pycode(self):

        def universal_answer():
            return 42

        serialized_code = roundtrip_serialization(universal_answer.func_code)
        self.assertEqual(eval(serialized_code), universal_answer())

    def test_builtin_names(self):
        import __builtin__
        names = [x for x in dir(__builtin__)]
        self.assertEqual(names, roundtrip_serialization(names))

class CopyTest(unittest.TestCase):

    def test_copy(self):
        fruits = ArrayList(["apple", "banana"])
        fruits_copy = copy.copy(fruits)
        self.assertEqual(fruits, fruits_copy)
        self.assertNotEqual(id(fruits), id(fruits_copy))

    def test_deepcopy(self):
        items = ArrayList([ArrayList(["apple", "banana"]),
                           ArrayList(["trs80", "vic20"])])
        items_copy = copy.deepcopy(items)
        self.assertEqual(items, items_copy)
        self.assertNotEqual(id(items), id(items_copy))
        self.assertNotEqual(id(items[0]), id(items_copy[0]))
        self.assertNotEqual(id(items[1]), id(items_copy[1]))

    def test_copy_when_not_cloneable(self):
        bdfl = Person("Guido", "von Rossum")
        self.assertRaises(TypeError, copy.copy, bdfl)

        # monkeypatching in a __copy__ should now work
        Person.__copy__ = lambda p: Person(p.firstName, p.lastName)
        copy_bdfl = copy.copy(bdfl)
        self.assertEqual(str(bdfl), str(copy_bdfl))

    def test_copy_when_not_serializable(self):
        bdfl = Person("Guido", "von Rossum")
        self.assertRaises(TypeError, copy.deepcopy, bdfl)

        # monkeypatching in a __deepcopy__ should now work
        Person.__deepcopy__ = lambda p, memo: Person(p.firstName, p.lastName)
        copy_bdfl = copy.deepcopy(bdfl)
        self.assertEqual(str(bdfl), str(copy_bdfl))

    def test_immutable(self):
        abc = String("abc")
        abc_copy = copy.copy(abc)
        self.assertEqual(id(abc), id(abc_copy))

        fruits = ArrayList([String("apple"), String("banana")])
        fruits_copy = copy.copy(fruits)
        self.assertEqual(fruits, fruits_copy)
        self.assertNotEqual(id(fruits), id(fruits_copy))

class UnicodeTest(unittest.TestCase):

    def test_unicode_conversion(self):
        test = unicode(ToUnicode())
        self.assertEqual(type(test), unicode)
        self.assertEqual(test, u"Circle is 360\u00B0")

class BeanPropertyTest(unittest.TestCase):

    def test_issue1833(self):
        class TargetClass(object):
            def _getattribute(self):
                return self.__attribute
            def _setattribute(self, value):
                self.__attribute = value
            attribute = property(_getattribute, _setattribute)

        target = TargetClass()
        test = Issue1833(target=target)
        value = ('bleh', 'blah')
        test.value = value
        self.assertEqual(target.attribute, value)

def test_main():
    test_support.run_unittest(InstantiationTest,
                              BeanTest,
                              SysIntegrationTest,
                              IOTest,
                              JavaReservedNamesTest,
                              PyReservedNamesTest,
                              ImportTest,
                              ColorTest,
                              TreePathTest,
                              BigNumberTest,
                              JavaStringTest,
                              JavaDelegationTest,
                              SecurityManagerTest,
                              JavaWrapperCustomizationTest,
                              SerializationTest,
                              CopyTest,
                              UnicodeTest,
                              BeanPropertyTest)

if __name__ == "__main__":
    test_main()


text:
nfs-provisioner is released on an as-needed basis. The process is as follows:

1. An issue is proposing a new release with a changelog since the last release
1. An OWNER runs `make test` to make sure tests pass
1. An OWNER runs `git tag -a $VERSION` and inserts the changelog and pushes the tag with `git push $VERSION`
1. An OWNER runs `make push` to build and push the image
1. The release issue is closed


text:
layout: post
title: Oficinas de Python para a OBI
categories:
- noticias
---

Com a proximidade da  Olimpíada
Brasileira de Informática, o Clube de Programação UPF irá ministrar
oficinas *gratuitas* de **Programação em Python**, nos dias **3, 5 e 10 de maio**,
das 13:30 às 17:30, no Laboratório Central de Informática da UPF.

As oficinas são abertas a todos os estudantes de Passo Fundo e região
interessados em participar da OBI, cuja primeira fase será dia **12 de maio**,
das 14:00 às 16:00. Não é necessário inscrição para as oficinas.

As inscrições para a OBI são gratuitas e podem ser feitas enviando email para o
Prof. Eder Pazinatto (ederpazinatto [at] upf br), contendo os seguintes dados:

- Nome completo
- Data de nascimento
- Número de matrícula (se você for da UPF)
- Nome da sua instituição de ensino (caso contrário)

Contamos com a participação de cada um de vocês! Nos vemos no LCI da UPF! \o/

Curta a página no Facebook:
Clube de Programação UPF


text:
from sklearn import tree
from timeit import default_timer as timer
from random import randint, sample, shuffle
from os.path import isfile
import os
import csv
import pylru
# local dependencies
import bots
import decks

# how many can we fit into memory?
ML_MODEL_CACHE_SIZE = 50

# cache of previously trained models in memory
models = pylru.lrucache(ML_MODEL_CACHE_SIZE)

#
# train a new model using the training data collected
#
def trainModel (botname, deckname):
    global models

    # start timing, so we know how long we're spending doing training
    start = timer()

    # get the path of the CSV with the training data
    trainingdata = bots.getFileName(botname, deckname)
    # no training data available
    if isfile(trainingdata) == False:
        return None

    # train a decision tree
    data = []
    target = []
    headers = None
    trainingrecords = 0
    with open(trainingdata, "rb") as trainingfile:
        reader = csv.reader(trainingfile, delimiter=",")
        headers = reader.next()
        for row in reader:
            data.append(row[:-1])
            target.append(row[-1])
            trainingrecords += 1

    dt = tree.DecisionTreeClassifier()
    dt.fit(data, target)

    # stop timing
    end = timer()

    # cache the decision tree so we can reuse it without training
    models[trainingdata] = dt

    return { "model" : dt, "training" : { "time" : (end - start), "hands" : len(data) } }

#
# gets the predictive model - fetching a previously trained model
#  if one is available in the cache, or creating a new one otherwise
def getModel (botname, deckname):
    global models
    trainingdata = bots.getFileName(botname, deckname)
    try:
        return models[trainingdata]
    except KeyError:
        newtraining = trainModel(botname, deckname)
        if newtraining is None:
            return None
        else:
            return newtraining["model"]

def compareNumbers (first, second):
    if first > second:
        return 1
    elif first < second:
        return -1
    else:
        return 0

def sortChoices (first, second):
    if first["outcome"] == 1 and second["outcome"] == 1:
        return compareNumbers(first["confidence"], second["confidence"])
    elif first["outcome"] == 1:
        return 1
    elif second["outcome"] == 1:
        return -1
    elif first["outcome"] == 0 and second["outcome"] == 0:
        return compareNumbers(second["confidence"], first["confidence"])
    elif first["outcome"] == 0:
        return 1
    elif second["outcome"] == 0:
        return -1
    else:
        return compareNumbers(second["confidence"], first["confidence"])

def randomChoice (rules):
    choice = sample(rules.keys(), 1)[0]
    print "Computer chose : %s" % (choice)
    return choice

def predict (botname, deckname, card):
    model = getModel(botname, deckname)

    deck = decks.get(deckname)
    rules = deck["rules"]

    if model is None:
        return { "confidence" : 0, "choice" : randomChoice(rules) }

    data = []

    optionidx = 0
    for option in rules.keys():
        optionData = []
        for attribute in rules.keys():
            optionData.append(card[attribute])
        optionData.append(optionidx)
        optionidx += 1

        data.append(optionData)

    predictions = model.predict_proba(data)

    print predictions

    if len(predictions) != len(rules.keys()):
        print "Insufficient training. Resorting to random."
        return { "confidence" : 0, "choice" : randomChoice(rules) }

    choices = []
    optionidx = 0
    for option in rules.keys():
        print option

        print len(predictions[optionidx])

        # we need predictions for win/loss/draw
        #  which only happen once all options have been
        #  represented in the training data
        if len(predictions[optionidx]) != 3:
            print "Insufficient training. Resorting to random."
            return { "confidence" : 0, "choice" : randomChoice(rules) }

        loss_prob = predictions[optionidx][0]
        draw_prob = predictions[optionidx][1]
        win_prob = predictions[optionidx][2]
        print "probability of losing " + str(predictions[optionidx][0])
        print "probability of drawing " + str(predictions[optionidx][1])
        print "probability of winning " + str(predictions[optionidx][2])
        if win_prob >= draw_prob and win_prob > loss_prob:
            choices.append({
                "choice" : option,
                "outcome" : 1,
                "confidence" : win_prob * 100
            })
        elif (draw_prob > win_prob and draw_prob > loss_prob) or (win_prob == loss_prob and win_prob > draw_prob):
            choices.append({
                "choice" : option,
                "outcome" : 0,
                "confidence" : draw_prob * 100
            })
        else:
            choices.append({
                "choice" : option,
                "outcome" : -1,
                "confidence" : loss_prob * 100
            })

        optionidx += 1

    sortedChoices = sorted(choices, cmp=sortChoices, reverse=True)

    choice = sortedChoices[0]["choice"]
    print "Computer chose : %s" % (choice)

    outcome = ""
    if sortedChoices[0]["outcome"] == 1:
        outcome = "win"
    elif sortedChoices[0]["outcome"] == 0:
        outcome = "at least draw"
    else:
        outcome = "draw"

    message = "(expecting that it would %s with %d percent confidence)"
    print message % (outcome, sortedChoices[0]["confidence"])

    return sortedChoices[0]


text:
title: Homework2: UML
---

Due Feb 3.

## Setup

+ Download and install [StarUML](http://staruml.io/)
+ Review the website [Conway's Game of Life](http://pmav.eu/stuff/javascript-game-of-life-v3.1.1/)
+ Recall the [rules for Game of Life](http://en.wikipedia.org/wiki/Conway%27s_Game_of_Life#Rules)
+ Consider the [GOL UML design v1](https://www.evernote.com/shard/s14/sh/f4f0b03f-4f57-42fb-8a1e-db9a3235d522/ad332a2c5889878b/res/e7343116-cfb5-44d3-b538-3f88535914c4.png?resizeSmall&width=832)

## Individually

+ Using StarUML, design your own GOL UML design v2.

## As a group

+ Once all the v2 designs are made,
+ Meet to review all designs and create your group GOL UML design v3
+ As you create v3, write down the rules you used to say
  "this part of this v2 needs to be changed to that".

## Hand in:

Your v2 and v3 designs. _Do not write your individual name on your v2 design_.

Specifically, I want to see, stapled together, in order:

+ [Rubric2](rubric2.html), one column filled in
+ **All** your v2 designs (one per person)
+ Your v3 design
+ The most revised v2 design (that is most different to the v3 design).
+ The rules that guided you from v2 to v3.
     + Number each rule.
	 + On the print out of the designs, add that number in **red**
	   pen where it is relevant to v3 and the most revised v2 design
+ All the other v2 designs.


text:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical">

    <com.mogujie.tt.ui.widget.CustomViewPager
        android:id="@+id/viewPager"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />

    <RelativeLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical">

        <RelativeLayout
            android:id="@+id/top"
            android:layout_width="match_parent"
            android:layout_height="@dimen/top_bar_default_height"
            android:layout_alignParentTop="true"
            android:background="#86222222">

            <ImageView
                android:id="@+id/back_btn"
                android:layout_width="57dp"
                android:layout_height="match_parent"
                android:layout_alignParentLeft="true"
                android:scaleType="center"
                android:src="@drawable/tt_back_btn" />

            <ImageView
                android:id="@+id/select_btn"
                android:layout_width="57dp"
                android:layout_height="match_parent"
                android:layout_alignParentRight="true"
                android:layout_centerVertical="true"
                android:scaleType="center"
                android:src="@drawable/tt_album_img_selected" />
        </RelativeLayout>

        <RelativeLayout
            android:layout_width="fill_parent"
            android:layout_height="@dimen/bottom_bar_default_height"
            android:layout_alignParentBottom="true"
            android:background="#86222222"
            android:gravity="center_vertical"
            android:orientation="horizontal"
            android:paddingLeft="20dp"
            android:paddingRight="15dp"></RelativeLayout>
    </RelativeLayout>

    <RelativeLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <LinearLayout
            android:id="@+id/viewGroup"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:layout_marginBottom="20dp"
            android:gravity="center_horizontal"
            android:orientation="horizontal"></LinearLayout>
    </RelativeLayout>

</FrameLayout>


text:
package org.apache.flex.forks.batik.util.gui.xmleditor;

/**
 * XML Token
 *
 * @author Tonny Kohar
 * @version $Id$
 */
public class XMLToken {

    private int context;
    private int startOffset;
    private int endOffset;

    /** Creates a new instance of XMLToken */
    public XMLToken(int context, int startOffset, int endOffset) {
        this.context = context;
        this.startOffset = startOffset;
        this.endOffset = endOffset;
    }

    public int getContext() {
        return context;
    }

    public int getStartOffset() {
        return startOffset;
    }

    public int getEndOffset() {
        return endOffset;
    }
}


text:
// Copyright (C) 2002-2008 Nikolaus Gebhardt
// This file is part of the "Irrlicht Engine".
// For conditions of distribution and use, see copyright notice in irrlicht.h

#ifndef __COLOR_H_INCLUDED__
#define __COLOR_H_INCLUDED__

#include "irrTypes.h"
#include "irrMath.h"

namespace irr
{
namespace video
{
	//! Creates a 16 bit A1R5G5B5 color
	inline u16 RGBA16(u32 r, u32 g, u32 b, u32 a=0xFF)
	{
		return ((a & 0x80) << 8 |
			(r & 0xF8) << 7 |
			(g & 0xF8) << 2 |
			(b & 0xF8) >> 3);
	}

	//! Creates a 16 bit A1R5G5B5 color
	inline u16 RGB16(u32 r, u32 g, u32 b)
	{
		return RGBA16(r,g,b);
	}

	//! Creates a 16bit A1R5G5B5 color, based on 16bit input values
	inline u16 RGB16from16(u16 r, u16 g, u16 b)
	{
		return (0x8000 |
				(r & 0x1F) << 10 |
				(g & 0x1F) << 5  |
				(b & 0x1F));
	}

	//! Converts a 32bit (X8R8G8B8) color to a 16bit A1R5G5B5 color
	inline u16 X8R8G8B8toA1R5G5B5(u32 color)
	{
		return (0x8000 |
			( color & 0x00F80000) >> 9 |
			( color & 0x0000F800) >> 6 |
			( color & 0x000000F8) >> 3);
	}

	//! Converts a 32bit (A8R8G8B8) color to a 16bit A1R5G5B5 color
	inline u16 A8R8G8B8toA1R5G5B5(u32 color)
	{
		return (( color & 0x80000000) >> 16|
			( color & 0x00F80000) >> 9 |
			( color & 0x0000F800) >> 6 |
			( color & 0x000000F8) >> 3);
	}

	//! Converts a 32bit (A8R8G8B8) color to a 16bit R5G6B5 color
	inline u16 A8R8G8B8toR5G6B5(u32 color)
	{
		return (( color & 0x00F80000) >> 8 |
			( color & 0x0000FC00) >> 5 |
			( color & 0x000000F8) >> 3);
	}

	//! Convert A8R8G8B8 Color from A1R5G5B5 color
	/** build a nicer 32bit Color by extending dest lower bits with source high bits. */
	inline u32 A1R5G5B5toA8R8G8B8(u16 color)
	{
		return ( (( -( (s32) color & 0x00008000 ) >> (s32) 31 ) & 0xFF000000 ) |
				(( color & 0x00007C00 ) << 9) | (( color & 0x00007000 ) << 4) |
				(( color & 0x000003E0 ) << 6) | (( color & 0x00000380 ) << 1) |
				(( color & 0x0000001F ) << 3) | (( color & 0x0000001C ) >> 2)
				);
	}

	//! Returns A8R8G8B8 Color from R5G6B5 color
	inline u32 R5G6B5toA8R8G8B8(u16 color)
	{
		return 0xFF000000 |
			((color & 0xF800) << 8)|
			((color & 0x07E0) << 5)|
			((color & 0x001F) << 3);
	}

	//! Returns A1R5G5B5 Color from R5G6B5 color
	inline u16 R5G6B5toA1R5G5B5(u16 color)
	{
		return 0x8000 | (((color & 0xFFC0) >> 1) | (color & 0x1F));
	}

	//! Returns R5G6B5 Color from A1R5G5B5 color
	inline u16 A1R5G5B5toR5G6B5(u16 color)
	{
		return (((color & 0x7FE0) << 1) | (color & 0x1F));
	}

	//! Returns the alpha component from A1R5G5B5 color
	inline u32 getAlpha(u16 color)
	{
		return ((color >> 15)&0x1);
	}

	//! Returns the red component from A1R5G5B5 color.
	/** Shift left by 3 to get 8 bit value. */
	inline u32 getRed(u16 color)
	{
		return ((color >> 10)&0x1F);
	}

	//! Returns the green component from A1R5G5B5 color
	/** Shift left by 3 to get 8 bit value. */
	inline u32 getGreen(u16 color)
	{
		return ((color >> 5)&0x1F);
	}

	//! Returns the blue component from A1R5G5B5 color
	/** Shift left by 3 to get 8 bit value. */
	inline u32 getBlue(u16 color)
	{
		return (color & 0x1F);
	}

	//! Returns the average from a 16 bit A1R5G5B5 color
	inline s32 getAverage(s16 color)
	{
		return ((getRed(color)<<3) + (getGreen(color)<<3) + (getBlue(color)<<3)) / 3;
	}

	//! Class representing a 32 bit ARGB color.
	/** The color values for alpha, red, green, and blue are
	stored in a single u32. So all four values may be between 0 and 255.
	This class is used by most parts of the Irrlicht Engine
	to specify a color. Another way is using the class SColorf, which
	stores the color values in 4 floats.
	*/
	class SColor
	{
	public:

		//! Constructor of the Color. Does nothing.
		/** The color value is not initialized to save time. */
		SColor() {}

		//! Constructs the color from 4 values representing the alpha, red, green and blue component.
		/** Must be values between 0 and 255. */
		SColor (u32 a, u32 r, u32 g, u32 b)
			: color(((a & 0xff)<<24) | ((r & 0xff)<<16) | ((g & 0xff)<<8) | (b & 0xff)) {}

		//! Constructs the color from a 32 bit value. Could be another color.
		SColor(u32 clr)
			: color(clr) {}

		//! Returns the alpha component of the color.
		/** The alpha component defines how transparent a color should
		be. 255 means not transparent (opaque), 0 means fully
		transparent. */
		u32 getAlpha() const { return color>>24; }

		//! Returns the red component of the color.
		/** \return Value between 0 and 255, specifying how red the color is.
		0 means no red, 255 means full red. */
		u32 getRed() const { return (color>>16) & 0xff; }

		//! Returns the green component of the color.
		/** \return Value between 0 and 255, specifying how green the color is.
		0 means no green, 255 means full green. */
		u32 getGreen() const { return (color>>8) & 0xff; }

		//! Returns the blue component of the color.
		/** \return Value between 0 and 255, specifying how blue the color is.
		0 means no blue, 255 means full blue. */
		u32 getBlue() const { return color & 0xff; }

		//! Returns the luminance of the color.
		f32 getLuminance() const
		{
			return 0.3f*getRed() + 0.59f*getGreen() + 0.11f*getBlue();
		}

		//! Returns the average intensity of the color.
		u32 getAverage() const
		{
			return ( getRed() + getGreen() + getBlue() ) / 3;
		}

		//! Sets the alpha component of the Color.
		/** The alpha component defines how transparent a color should
		be.
		\param a: Has to be a value between 0 and 255.
		255 means not transparent (opaque), 0 means fully transparent. */
		void setAlpha(u32 a) { color = ((a & 0xff)<<24) | (color & 0x00ffffff); }

		//! Sets the red component of the Color.
		/** \param r: Has to be a value between 0 and 255.
		0 means no red, 255 means full red. */
		void setRed(u32 r) { color = ((r & 0xff)<<16) | (color & 0xff00ffff); }

		//! Sets the green component of the Color.
		/** \param g: Has to be a value between 0 and 255.
		0 means no green, 255 means full green. */
		void setGreen(u32 g) { color = ((g & 0xff)<<8) | (color & 0xffff00ff); }

		//! Sets the blue component of the Color.
		/** \param b: Has to be a value between 0 and 255.
		0 means no blue, 255 means full blue. */
		void setBlue(u32 b) { color = (b & 0xff) | (color & 0xffffff00); }

		//! Calculates a 16 bit A1R5G5B5 value of this color.
		/** \return 16 bit A1R5G5B5 value of this color. */
		u16 toA1R5G5B5() const { return A8R8G8B8toA1R5G5B5(color); }

		//! Converts color to OpenGL color format
		/** From ARGB to RGBA in 4 byte components for endian aware
		passing to OpenGL
		\param dest: address where the 4x8 bit OpenGL color is stored. */
		void toOpenGLColor(u8* dest) const
		{
			*dest =   getRed();
			*++dest = getGreen();
			*++dest = getBlue();
			*++dest = getAlpha();
		}

		//! Sets all four components of the color at once.
		/** Constructs the color from 4 values representing the alpha,
		red, green and blue components of the color. Must be values
		between 0 and 255.
		\param a: Alpha component of the color. The alpha component
		defines how transparent a color should be. Has to be a value
		between 0 and 255. 255 means not transparent (opaque), 0 means
		fully transparent.
		\param r: Sets the red component of the Color. Has to be a
		value between 0 and 255. 0 means no red, 255 means full red.
		\param g: Sets the green component of the Color. Has to be a
		value between 0 and 255. 0 means no green, 255 means full
		green.
		\param b: Sets the blue component of the Color. Has to be a
		value between 0 and 255. 0 means no blue, 255 means full blue. */
		void set(u32 a, u32 r, u32 g, u32 b)
		{
			color = (((a & 0xff)<<24) | ((r & 0xff)<<16) | ((g & 0xff)<<8) | (b & 0xff));
		}
		void set(u32 col) { color = col; }

		//! Compares the color to another color.
		/** \return True if the colors are the same, and false if not. */
		bool operator==(const SColor& other) const { return other.color == color; }

		//! Compares the color to another color.
		/** \return True if the colors are different, and false if they are the same. */
		bool operator!=(const SColor& other) const { return other.color != color; }

		//! comparison operator
		/** \return True if this color is smaller than the other one */
		bool operator<(const SColor& other) const { return (color < other.color); }

		//! Adds two colors, result is clamped to 0..255 values
		/** \param other Color to add to this color
		\return Addition of the two colors, clamped to 0..255 values */
		SColor operator+(const SColor& other) const
		{
			return SColor(core::min_(getAlpha() + other.getAlpha(), 255u),
					core::min_(getRed() + other.getRed(), 255u),
					core::min_(getGreen() + other.getGreen(), 255u),
					core::min_(getBlue() + other.getBlue(), 255u));
		}

		//! Interpolates the color with a f32 value to another color
		/** \param other: Other color
		\param d: value between 0.0f and 1.0f
		\return Interpolated color. */
		SColor getInterpolated(const SColor &other, f32 d) const
		{
			d = core::clamp(d, 0.f, 1.f);
			const f32 inv = 1.0f - d;
			return SColor((u32)(other.getAlpha()*inv + getAlpha()*d),
				(u32)(other.getRed()*inv + getRed()*d),
				(u32)(other.getGreen()*inv + getGreen()*d),
				(u32)(other.getBlue()*inv + getBlue()*d));
		}

		//! Returns interpolated color. ( quadratic )
		/** \param c1: first color to interpolate with
		\param c2: second color to interpolate with
		\param d: value between 0.0f and 1.0f. */
		SColor getInterpolated_quadratic(const SColor& c1, const SColor& c2, f32 d) const
		{
			// this*(1-d)*(1-d) + 2 * c1 * (1-d) + c2 * d * d;
			d = core::clamp(d, 0.f, 1.f);
			const f32 inv = 1.f - d;
			const f32 mul0 = inv * inv;
			const f32 mul1 = 2.f * d * inv;
			const f32 mul2 = d * d;

			return SColor(
					core::clamp( core::floor32(
							getAlpha() * mul0 + c1.getAlpha() * mul1 + c2.getAlpha() * mul2 ), 0, 255 ),
					core::clamp( core::floor32(
							getRed()   * mul0 + c1.getRed()   * mul1 + c2.getRed()   * mul2 ), 0, 255 ),
					core::clamp ( core::floor32(
							getGreen() * mul0 + c1.getGreen() * mul1 + c2.getGreen() * mul2 ), 0, 255 ),
					core::clamp ( core::floor32(
							getBlue()  * mul0 + c1.getBlue()  * mul1 + c2.getBlue()  * mul2 ), 0, 255 ));
		}

		//! color in A8R8G8B8 Format
		u32 color;
	};

	//! Class representing a color with four floats.
	/** The color values for red, green, blue
	and alpha are each stored in a 32 bit floating point variable.
	So all four values may be between 0.0f and 1.0f.
	Another, faster way to define colors is using the class SColor, which
	stores the color values in a single 32 bit integer.
	*/
	class SColorf
	{
	public:
		//! Constructs a color from up to four color values: red, green, blue, and alpha.
		/** \param r: Red color component. Should be a value between
		0.0f meaning no red and 1.0f, meaning full red.
		\param g: Green color component. Should be a value between 0.0f
		meaning no green and 1.0f, meaning full green.
		\param b: Blue color component. Should be a value between 0.0f
		meaning no blue and 1.0f, meaning full blue.
		\param a: Alpha color component of the color. The alpha
		component defines how transparent a color should be. Has to be
		a value between 0.0f and 1.0f, 1.0f means not transparent
		(opaque), 0.0f means fully transparent. */
		SColorf(f32 r=0.f, f32 g=0.f, f32 b=0.f, f32 a=1.f) : r(r), g(g), b(b), a(a) {}

		//! Constructs a color from 32 bit Color.
		/** \param c: 32 bit color from which this SColorf class is
		constructed from. */
		SColorf(SColor c)
		{
			const f32 inv = 1.0f / 255.0f;
			r = c.getRed() * inv;
			g = c.getGreen() * inv;
			b = c.getBlue() * inv;
			a = c.getAlpha() * inv;
		}

		//! Converts this color to a SColor without floats.
		SColor toSColor() const
		{
			return SColor((u32)(a*255.0f), (u32)(r*255.0f), (u32)(g*255.0f), (u32)(b*255.0f));
		}

		//! Sets three color components to new values at once.
		/** \param rr: Red color component. Should be a value between 0.0f meaning
		no red (=black) and 1.0f, meaning full red.
		\param gg: Green color component. Should be a value between 0.0f meaning
		no green (=black) and 1.0f, meaning full green.
		\param bb: Blue color component. Should be a value between 0.0f meaning
		no blue (=black) and 1.0f, meaning full blue. */
		void set(f32 rr, f32 gg, f32 bb) {r = rr; g =gg; b = bb; }

		//! Sets all four color components to new values at once.
		/** \param aa: Alpha component. Should be a value between 0.0f meaning
		fully transparent and 1.0f, meaning opaque.
		\param rr: Red color component. Should be a value between 0.0f meaning
		no red and 1.0f, meaning full red.
		\param gg: Green color component. Should be a value between 0.0f meaning
		no green and 1.0f, meaning full green.
		\param bb: Blue color component. Should be a value between 0.0f meaning
		no blue and 1.0f, meaning full blue. */
		void set(f32 aa, f32 rr, f32 gg, f32 bb) {a = aa; r = rr; g =gg; b = bb; }

		//! Interpolates the color with a f32 value to another color
		/** \param other: Other color
		\param d: value between 0.0f and 1.0f
		\return Interpolated color. */
		SColorf getInterpolated(const SColorf &other, f32 d) const
		{
			d = core::clamp(d, 0.f, 1.f);
			const f32 inv = 1.0f - d;
			return SColorf(other.r*inv + r*d,
				other.g*inv + g*d, other.b*inv + b*d, other.a*inv + a*d);
		}

		//! Returns interpolated color. ( quadratic )
		/** \param c1: first color to interpolate with
		\param c2: second color to interpolate with
		\param d: value between 0.0f and 1.0f. */
		inline SColorf getInterpolated_quadratic(const SColorf& c1, const SColorf& c2,
				f32 d) const
		{
			d = core::clamp(d, 0.f, 1.f);
			// this*(1-d)*(1-d) + 2 * c1 * (1-d) + c2 * d * d;
			const f32 inv = 1.f - d;
			const f32 mul0 = inv * inv;
			const f32 mul1 = 2.f * d * inv;
			const f32 mul2 = d * d;

			return SColorf (r * mul0 + c1.r * mul1 + c2.r * mul2,
					g * mul0 + c1.g * mul1 + c2.g * mul2,
					g * mul0 + c1.b * mul1 + c2.b * mul2,
					a * mul0 + c1.a * mul1 + c2.a * mul2);
		}

		//! Sets a color component by index. R=0, G=1, B=2, A=3
		void setColorComponentValue(s32 index, f32 value)
		{
			switch(index)
			{
			case 0: r = value; break;
			case 1: g = value; break;
			case 2: b = value; break;
			case 3: a = value; break;
			}
		}

		//! Returns the alpha component of the color in the range 0.0 to 1.0
		f32 getAlpha() const { return a; }

		//! Returns the red component of the color in the range 0.0 to 1.0
		f32 getRed() const { return r; }

		//! Returns the green component of the color in the range 0.0 to 1.0
		f32 getGreen() const { return g; }

		//! Returns the blue component of the color in the range 0.0 to 1.0
		f32 getBlue() const { return b; }

		//! red color component
		f32 r;

		//! green color component
		f32 g;

		//! blue component
		f32 b;

		//! alpha color component
		f32 a;
	};

	//! Class representing a color in HSV format
	/** The color values for hue, saturation, value
	are stored in a 32 bit floating point variable.
	*/
	class SColorHSL
	{
	public:
		SColorHSL ( f32 h = 0.f, f32 s = 0.f, f32 l = 0.f )
			: Hue ( h ), Saturation ( s ), Luminance ( l ) {}

//		void setfromRGB ( const SColor &color );
		void settoRGB ( SColor &color ) const;

		f32 Hue;
		f32 Saturation;
		f32 Luminance;

	private:
		inline u32 toRGB1(f32 rm1, f32 rm2, f32 rh) const;

	};

	inline void SColorHSL::settoRGB ( SColor &color ) const
	{
		if ( Saturation == 0.0f) // grey
		{
			u8 c = (u8) ( Luminance * 255.0 );
			color.setRed ( c );
			color.setGreen ( c );
			color.setBlue ( c );
			return;
		}

		f32 rm2;

		if ( Luminance <= 0.5f )
		{
			rm2 = Luminance + Luminance * Saturation;
		}
		else
		{
			rm2 = Luminance + Saturation - Luminance * Saturation;
		}

		const f32 rm1 = 2.0f * Luminance - rm2;

		color.setRed ( toRGB1(rm1, rm2, Hue + (120.0f * core::DEGTORAD )) );
		color.setGreen ( toRGB1(rm1, rm2, Hue) );
		color.setBlue ( toRGB1(rm1, rm2, Hue - (120.0f * core::DEGTORAD) ) );
	}

	inline u32 SColorHSL::toRGB1(f32 rm1, f32 rm2, f32 rh) const
	{
		while ( rh > 2.f * core::PI )
			rh -= 2.f * core::PI;

		while ( rh < 0.f )
			rh += 2.f * core::PI;

		if (rh < 60.0f * core::DEGTORAD )
			rm1 = rm1 + (rm2 - rm1) * rh / (60.0f * core::DEGTORAD);
		else if (rh < 180.0f * core::DEGTORAD )
			rm1 = rm2;
		else if (rh < 240.0f * core::DEGTORAD )
			rm1 = rm1 + (rm2 - rm1) * ( ( 240.0f * core::DEGTORAD ) - rh) /
				(60.0f * core::DEGTORAD);

		return (u32) (rm1 * 255.f);
	}

} // end namespace video
} // end namespace irr

#endif